Convert PDFs to Images on iOS
To render an 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 } // Create a render request from your `Document`. let request = MutableRenderRequest(document: document) request.imageSize = pageImageSize 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.