Convert Images to PDFs 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 PdfProcessor API enables you to convert a bitmap into a PDF file with minimal code.

First, create a PageImage object — it contains which image should be used and how it should be compressed. Then, create a NewPage, which contains the information specifying how large the page should be and that it should include the previously created PageImage.

Next, use a PdfProcessorTask and add the NewPage instance as the first page. Finally, PdfProcessor generates the actual PDF and writes it to the disk to the specified outputFile:

val image: Bitmap = ...
val outputFile: File = ...
val imageSize = Size(image.width.toFloat(), image.height.toFloat())
val pageImage = PageImage(image, PagePosition.CENTER)
pageImage.setJpegQuality(70)
val newPage = NewPage
    .emptyPage(imageSize)
    .withPageItem(pageImage)
    .build()


val task = PdfProcessorTask.newPage(newPage)
val disposable = PdfProcessor.processDocumentAsync(task, outputFile)
    .subscribe { progress ->  }
final Bitmap image = ...
final File outputFile = ...
final Size imageSize = new Size(image.getWidth(), image.getHeight());
final PageImage pageImage = new PageImage(image, PagePosition.CENTER);
pageImage.setJpegQuality(70);
final NewPage newPage = NewPage
    .emptyPage(imageSize)
    .withPageItem(pageImage)
    .build();


final PdfProcessorTask task = PdfProcessorTask.newPage(newPage);
final Disposable disposable = PdfProcessor.processDocumentAsync(task, outputFile)
    .subscribe(progress -> { });

Generating a PDF with Multiple Images

To generate a PDF file with multiple images, you can create multiple PageImage and NewPage pairs, each with its own image. Then, use the addNewPage method of PdfProcessorTask to add the extra pages, like so:

val task = PdfProcessorTask
    .newPage(firstPage)
    .addNewPage(secondPage, 1)
    .addNewPage(thirdPage, 2)
    .addNewPage(fourthPage, 3);
final PdfProcessorTask task = PdfProcessorTask
    .newPage(firstPage)
    .addNewPage(secondPage, 1)
    .addNewPage(thirdPage, 2)
    .addNewPage(fourthPage, 3);