如何使用 dart_pdf 在 flutter 中将资产图像和图标转换为 Pdf 图像

How to convert Assets Images & Icons to PdfImage in flutter using dart_pdf

Used Library: dart_pdf After searching I found the same issue in GITHUB 但无法解决问题。我试过了,但出现了模糊的图像。请帮忙!!

  ByteData data = await rootBundle.load('assets/test.jpg');
  var codec = await instantiateImageCodec(data.buffer.asUint8List());
  var frame = await codec.getNextFrame();

  var imageBytes = await frame.image.toByteData();
  PdfImage assetImage = PdfImage(pdf.document,
      image: imageBytes.buffer.asUint8List(), width: 86, height: 80);

渲染图像:

改用这个:

final PdfImage assetImage = await pdfImageFromImageProvider(
    pdf: pdf.document, 
    image: const AssetImage('assets/test.jpg'),
);

此函数将使用图像和自定义数据创建您的 pdf

 var pdf = new pw.Document();

 Future<pw.Document> createPDF() async {
    var assetImage = pw.MemoryImage(
      (await rootBundle.load('assets/images/delivery.png'))
          .buffer
          .asUint8List(),
    );

    pdf.addPage(pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          var width = MediaQuery.of(this.context).size.width;
          var height = MediaQuery.of(this.context).size.height;
          return pw.Container(
            margin: pw.EdgeInsets.only(top: height * 0.1),
            child: pw.ListView(
              children: [
                // your image here
                pw.Container(
                    height: height * 0.25, child: pw.Image(assetImage)),
              // other contents
                pw.Row(
                  mainAxisAlignment: pw.MainAxisAlignment.spaceAround,
                  children: [
                    pw.Text("order Id:"),
                    pw.Text(widget.doc['orderId']),
                  ],
                ),
              ],
            ),
          );
        }));
        
    return pdf;
  }

使用此功能保存

 Future savePdf(pw.Document pdfnew) async {
    String pdfName;
    File file;

    try {
      
      var documentDirectory = await AndroidPathProvider.downloadsPath; // for android downloads folder
    //  var localDirectory = await getApplicationDocumentsDirectory(); // for local directory
    
      setState(() {
        pdfName = "your_pdf_name";
      });
  
      file = File("$documentDirectory/$pdfName.pdf");
      await file.writeAsBytes(await pdf.save());
   
      return file.path;
    } catch (e) {
      print(e);
    }
  
  }