Generate PDFs Programmatically on Android

PSPDFKit for Android offers several different ways to programmatically create PDF files. Check out the following guides for generating a:

Optionally, you can also use Android’s built-in APIs provided by PdfDocument to generate a PDF.

Using the Android APIs

For maximum flexibility, you can write your own drawing code to generate PDFs. The provided APIs are fairly straightforward, so if you already have existing drawing code, this can be a good approach for PDF creation.

Here’s an example of how the API should be used:

// Create a new document.
val document = PdfDocument()

// Create the first page.
val firstPageInfo = PageInfo.Builder(100, 100, 1).create()
val firstPage = document.startPage(firstPageInfo)

// Draw to the first page.
val firstPageContent: View = getViewRepresentingTheFirstPage()
firstPageContent.draw(firstPage.canvas)
document.finishPage(firstPage)

// Create the second page.
val secondPageInfo = PageInfo.Builder(100, 100, 2).create()
val secondPage = document.startPage(secondPageInfo)

// Draw to the second page.
val secondPageContent: View = getViewRepresentingTheSecondPage()
secondPageContent.draw(secondPage.canvas)
document.finishPage(secondPage)

// Save the document.
document.writeTo(outputStream)
document.close()
// Create a new document.
PdfDocument document = new PdfDocument();

// Create the first page.
PageInfo firstPageInfo = new PageInfo.Builder(100, 100, 1).create();
Page firstPage = document.startPage(firstPageInfo);

// Draw to the first page.
View firstPageContent = getViewRepresentingTheFirstPage();
firstPageContent.draw(firstPage.getCanvas());
document.finishPage(firstPage);

// Create the second page.
PageInfo secondPageInfo = new PageInfo.Builder(100, 100, 2).create();
Page secondPage = document.startPage(secondPageInfo);

// Draw to the second page.
View secondPageContent = getViewRepresentingTheSecondPage();
secondPageContent.draw(secondPage.getCanvas());
document.finishPage(secondPage);

// Save the document.
document.writeTo(outputStream);
document.close();