Generate a PDF from an image in Flutter
To convert an image to a PDF, follow the steps below.
- Create a
PdfImagePage
object(opens in a new tab) to specify the location of the image and instructions for compression. - Create a
NewPage
object(opens in a new tab) to specify the page size and the previously createdPdfImagePage
object(opens in a new tab). - Call the
PspdfkitProcessor.generatePdf()
method with the following parameters:- A list of
NewPage
objects(opens in a new tab). - An
outputFile
parameter specifying the location where to save the generated PDF.
- A list of
Generate PDFs from images
The following code demonstrates how to create a PDF from an image:
// Image file from which to generate the PDF.File img = File('<readable-image-path>');
// File path where the generated PDF will be saved.String outputPath = '<writable-output-file-path>';
// A list of PDF pages from the image URI.List<NewPage> pages = [ NewPage.fromImage( PdfImagePage.fromUri(img.uri, PagePosition.center)), NewPage.fromImage( PdfImagePage.fromUri(img.uri, PagePosition.center)),];// Generate a PDF from an image and save it at `[outputPath]`.var filePath = await PspdfkitProcessor.instance.generatePdf( pages, outputPath); // Or `generatePDFFromImage`.
For more information on generating PDF files from HTML strings and URLs, see the PspdfkitProcessor
(opens in a new tab) documentation and the PDF Generation Example(opens in a new tab) from the Catalog app(opens in a new tab).