Flutter pdf generation too slow with image

3,040

flutter_html_to_pdf plugin for iOS and Android for generating PDF files from HTML.

use:

https://pub.dev/packages/flutter_html_to_pdf

instead of:

https://pub.dev/packages/pdf

First, add flutter_html_to_pdf as a dependency in your pubspec.yaml file.

 dependencies:
 flutter_html_to_pdf: ^0.5.2

Now in your Dart code, you can use:

 import 'package:flutter_html_to_pdf/flutter_html_to_pdf.dart';

Usage #

 var htmlContent =
 """
 <!DOCTYPE html>
 <html>
 <head>
   <style>
   table, th, td {
   border: 1px solid black;
     border-collapse: collapse;
   }
   th, td, p {
     padding: 5px;
     text-align: left;
   }
   </style>
 </head>
   <body>
     <h2>PDF Generated with flutter_html_to_pdf plugin</h2>
     <table style="width:100%">
       <caption>Sample HTML Table</caption>
       <tr>
         <th>Month</th>
         <th>Savings</th>
       </tr>
       <tr>
        <td>January</td>
         <td>100</td>
       </tr>
       <tr>
         <td>February</td>
         <td>50</td>
       </tr>
     </table>
     <p>Image loaded from web</p>
     <img src="https://i.imgur.com/wxaJsXF.png" alt="web-img">
   </body>
 </html>
 """;

 var targetPath = "/your/sample/path";
 var targetFileName = "example_pdf_file"

 var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
     htmlContent, targetPath, targetFileName);

You can also pass File object with HTML content inside as parameter

 var file = File("/sample_path/example.html");
 var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFile(
     file, targetPath, targetFileName);

or even just path to this file

 var filePath = "/sample_path/example.html";
 var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFilePath(
     filePath, targetPath, targetFileName);

Images If you want to add local image from device to your HTML you need to pass path to image as src value.

 <img src="file:///storage/example/your_sample_image.png" alt="web-img">

or if you want to use the image File object

 <img src="${imageFile.path}" alt="web-img">

And for Multiple images you can add multiple tags like:

 <img src="your source" alt="your alternative">
 <img src="your source" alt="your alternative">
 <img src="your source" alt="your alternative">
 <img src="your source" alt="your alternative">
 <img src="your source" alt="your alternative">
Share:
3,040
Juan Jose Rodrigo
Author by

Juan Jose Rodrigo

Updated on December 06, 2022

Comments

  • Juan Jose Rodrigo
    Juan Jose Rodrigo over 1 year

    im working on a pdf generator app in flutter, but when i want to add an image to the pdf, it takes too long also i wanted to know how it is possible to add multiple images.

    Im using 3 libraries, image picker - pdf - printing

    here is my code:

    Future getImage() async {
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      final tempDir = await getTemporaryDirectory();
      final path = tempDir.path;
      int rand = new Math.Random().nextInt(10000000);
      imge.Image imagee = imge.decodeImage(image.readAsBytesSync());
      imge.Image smallerImage = imge.copyResize(imagee, 500);
      setState(() {
       var  _image =  new   File('$path/img_$rand.jpg')..writeAsBytesSync(imge.encodeJpg(smallerImage, quality: 85));
    
       _sharePdf(_image);
      });
    
    
    }
    
    
    
     PDFDocument _generateDocument(File _image)  {
        final pdf = new PDFDocument(deflate: zlib.encode);
        final page = new PDFPage(pdf, pageFormat: PDFPageFormat.LETTER);
        final g = page.getGraphics();
        final font = new PDFFont(pdf);
        final top = page.pageFormat.height;
    
        print(top);
    
        imge.Image img = imge.decodeImage(_image.readAsBytesSync());
    
    
        PDFImage image = new PDFImage(
           pdf,
           image: img.data.buffer.asUint8List(),
           width: img.width,
           height: img.height);
    
       g.drawImage(image, 100.0, top - 150.0, 80.0, 100.0);
    
        return pdf;
      }
    
      void _sharePdf(File _image) {
        print("Share ...");
        final pdf = _generateDocument(_image);
    
        // Calculate the widget center for iPad sharing popup position
        final RenderBox referenceBox =
        shareWidget.currentContext.findRenderObject();
        final topLeft =
        referenceBox.localToGlobal(referenceBox.paintBounds.topLeft);
        final bottomRight =
        referenceBox.localToGlobal(referenceBox.paintBounds.bottomRight);
        final bounds = new Rect.fromPoints(topLeft, bottomRight);
    
        Printing.sharePdf(document: pdf, bounds: bounds);
      }
    

    Then im calling the function getImage().

    After i pick the image it takes 2-3 minutes in which everything freezes then you can share the pdf!

    • boformer
      boformer over 5 years
      Did you try to debug your code with breakpoints to find out what takes so long?
    • Juan Jose Rodrigo
      Juan Jose Rodrigo over 5 years
      yes it is the generation of the image in the pdf, because picking the image is fast
    • boformer
      boformer over 5 years
      This part? writeAsBytesSync(imge.encodeJpg(smallerImage, quality: 85))
    • Juan Jose Rodrigo
      Juan Jose Rodrigo over 5 years
      when it calls _sharePdf(_image); freezes, the compression and getting image its ok
    • Dan Field
      Dan Field over 5 years
      Can you provide a complete but minimal reproduction of this?