Generate PDF Thumbnails on iOS
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 iOS, you need to do the following:
// Create a URL for the PDF file. guard let path = Bundle.main.path(forResource: "report", ofType: "pdf") else { return } let url = URL(fileURLWithPath: path) // Instantiate a `Document` from the PDF file's URL. let document = Document(url: url) let pageIndex: PageIndex = 0 guard let pageImageSize = document.pageInfoForPage(at: pageIndex)?.mediaBox.size else { return } // Set the thumbnail size to be five times smaller than the actual page size. let thumbnailImageSize = CGSize(width: pageImageSize.width / 5, height: pageImageSize.height / 5) // Create a render request from your `Document`. let request = MutableRenderRequest(document: document) request.imageSize = thumbnailImageSize request.pageIndex = pageIndex do { // Create a render task using the `MutableRenderRequest`. let task = try RenderTask(request: request) task.priority = .utility PSPDFKit.SDK.shared.renderManager.renderQueue.schedule(task) // The page is rendered as a `UIImage`. let image = try PSPDFKit.SDK.shared.cache.image(for: request, imageSizeMatching: [.allowLarger]) } catch { // Handle error. }
The RenderTask
API used in the above example is an asynchronous API that won’t block the main thread when rendering a PDF page to an image. It includes an image cache by default, so multiple render calls for the same page are fetched directly from the cache. For a more detailed explanation of image rendering, check out our guide on rendering PDF pages and our blog post on converting a PDF to an image.
Additionally, PSPDFKit provides another API to render a PDF page to an image: imageForPage:at:size:clippedTo:annotations:options
. One thing to keep in mind is that this is a synchronous call that will block the main thread when it’s rendering a particularly large or complex PDF page.