Generate PDF Thumbnails on Android

A thumbnail is a low-resolution image representation of a PDF page. Thumbnails are generally used to recognize, navigate, or organize PDF pages. Generating a thumbnail preview of a PDF page is a common use case for any app that displays PDFs.

To render a thumbnail image from a PDF file in PSPDFKit for Android, you need to do the following:

try {
    // Create a Uri for the PDF file.
    val uri = Uri.parse("path/to/file.pdf")

    // Instantiate a `Document` from the PDF file's URL.
    val document =  PdfDocumentLoader.openDocument(context, uri)

    val pageIndex = 0
    val pageImageSize = document.getPageSize(pageIndex).toRect()

    // Set the thumbnail size to be five times smaller than the actual page size.
    val thumbnailImageSize = RectF(0f, 0f, pageImageSize.width() / 5, pageImageSize.height() / 5)
    // Create the image
    val bitmap = document.renderPageToBitmap(
        context,
        pageIndex
        thumbnailImageSize.width().toInt()
        thumbnailImageSize.height().toInt()
    )
} catch(ex: Exception) {
    // Handle error.
}
try {
    // Create a Uri for the PDF file.
    final Uri uri = Uri.parse("path/to/file.pdf");

    // Instantiate a `Document` from the PDF file's URL.
    final PdfDocument document =  PdfDocumentLoader.openDocument(context, uri);

    final int pageIndex = 0;
    final RectF pageImageSize = document.getPageSize(pageIndex).toRect();

    //
    // Set the thumbnail size to be five times smaller than the actual page size.
    final RectF thumbnailImageSize = new RectF(0f, 0f, pageImageSize.width() / 5, pageImageSize.height() / 5);
    //

    // Create the image.
    final Bitmap bitmap = document.renderPageToBitmap(
        context,
        pageIndex,
        (int)thumbnailImageSize.width()
        (int)thumbnailImageSize.height()
    );
} catch(final Exception exception) {
    // Handle error.
}

Note that the renderPageToBitmap API used in the above example is a synchronous API that will block whatever thread it’s called into, so make sure to either call it on a background thread or use the asynchronous method, renderPageToBitmapAsync.