Create PDFs from HTML in Flutter

PspdfkitProcessor provides powerful APIs for generating PDF files directly from HTML strings and URIs. It relies on the WebView system for Android and WebKit for the iOS implementation. This means there are certain aspects of the conversion process that Nutrient cannot support. This includes, for example, any possible WebView or WebKit bugs. The following examples show how to generate a PDF from an HTML string and URI/URL.

License

To generate a PDF from HTML, contact Sales to add HTML-to-PDF conversion to your license.

Generating a PDF from an HTML string

The code below shows how to generate a PDF from an HTML string:

const html = '''
<html>
    <head>
        <style type="text/css">
            h1 {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>Hello, world!</h1>
    </body>
</html>
''';

// Writable output path.
final outputFilePath = '<writable-output-file-path>'

// Generate the PDF from the HTML string.
String? generatedPdf = await PspdfkitProcessor.instance
    .generatePdfFromHtmlString(html, outputFilePath);
if (generatedPdf == null) {
    print('Failed to generate PDF from HTML string.');
    return;
}

// Display the generated PDF.
await Pspdfkit.present(generatedPdf);

Generating a PDF from an HTML URL/URI

The code below shows how to generate a PDF from an HTML URL or URI:

// Writable output path.
final htmlUrl =  Uri.parse('https://pspdfkit.com');
final outputFilePath = <writable-output-path>;

   // Generate the PDF from the HTML URL.
   String? generatedPdf = await PspdfkitProcessor.instance
       .generatePdfFromHtmlUri(htmlUri, outputFilePath);
   
   if (generatedPdf == null) {
   print('Failed to generate PDF from HTML URI.');
   return;
   }

   // Display the generated PDF.
   await Pspdfkit.present(generatedPdf);

For more information on generating PDF files from HTML strings and URLs, see the PspdfkitProcessor documentation and the PDF Generation Example from the Catalog app.