Generate PDFs from Images on Android

Images are universal and can be used in various ways, such as showing relevant content or graphics. However, there might be an occasion where dealing with an image doesn’t suffice and you require a PDF instead. Using the versatile Processor API enables you to convert a UIImage into a PDF file with minimal code.

First, create a PDFNewPageConfiguration object — it holds the information on how to build the page. It contains which image should be used and how it should be compressed, as well as the information specifying how large the page should be.

Next, use a Processor.Configuration and add the PDFNewPageConfiguration instance as the configuration for the first page. Finally, Processor generates the actual PDF and writes it to the disk at the specified outputFilePath:

let image: UIImage = ...
let outputFileURL: URL = ... // Writable file URL.
let pageTemplate = PageTemplate(pageType: .emptyPage, identifier: nil)
let newPageConfiguration = PDFNewPageConfiguration(pageTemplate: pageTemplate) { builder in
    builder.item = ProcessorItem(image: image, jpegCompressionQuality: 0.7, builderBlock: nil)
    builder.pageSize = image.size

let configuration = Processor.Configuration()
configuration.addNewPage(at: 0, configuration: newPageConfiguration)

do {
    try Processor(configuration: configuration, securityOptions: nil).write(toFileURL: outputFileURL)
} catch {
    print("Could not create PDF file: \(error)")

Generating a PDF with Multiple Images

To generate a PDF file with multiple images, you can create multiple PDFNewPageConfiguration objects, each with its own image. Then, add the newPageConfigurations to Processor.Configuration, just like you did above:

configuration.addNewPage(at: 0, configuration: newPageConfiguration0)
configuration.addNewPage(at: 1, configuration: newPageConfiguration1)
configuration.addNewPage(at: 2, configuration: newPageConfiguration2)

We use cookies to improve your experience and for marketing. Learn more in our privacy policy.