Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 but unable to resolve the issue. I tried this but blurry image appears. Please help!!

  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);

Rendered Image:

enter image description here

like image 283
jazzbpn Avatar asked Jul 05 '19 05:07

jazzbpn


2 Answers

Use this instead:

final PdfImage assetImage = await pdfImageFromImageProvider(
    pdf: pdf.document, 
    image: const AssetImage('assets/test.jpg'),
);
like image 162
Dav Avatar answered Sep 27 '22 17:09

Dav


This function will create your pdf with image and custom data

 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;
  }

use this function to save

 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);
    }
  
  }
like image 39
Deepak Yadav Avatar answered Sep 27 '22 17:09

Deepak Yadav