Skip to Content
NexPDF

Rendering pages

Render PDF pages and thumbnails to PNG with NexPDF for iOS (Swift), and map PDF coordinates to view points.

English

License module

Rendering is part of the viewer module and works without a key. Unlicensed and trial renders carry a watermark; commercial keys render without one.

Render a page to PNG

renderPagePng(pageIndex:dpi:) returns the PNG data of a page. At 72 dpi one pixel is one PDF point. For a sharp image on screen, multiply 72 by the screen scale and the zoom:

import NexPdf
import UIKit

let doc = try NexPdfDocument.open(url: url)
let dpi = 72 * UIScreen.main.scale            // 144 on a 2x screen, 216 on 3x
let image = UIImage(data: try doc.renderPagePng(pageIndex: 0, dpi: dpi))

Render a thumbnail

renderThumbPng(pageIndex:maxDim:) fits the page into a square of maxDim pixels, keeping the aspect ratio:

let thumb = try doc.renderThumbPng(pageIndex: 0, maxDim: 256)

Rendering is synchronous. Run it off the main thread for large pages, one document per queue:

let queue = DispatchQueue(label: "pdf.render")
queue.async {
    let png = try? doc.renderPagePng(pageIndex: 3, dpi: 144)
    DispatchQueue.main.async { imageView.image = png.flatMap(UIImage.init(data:)) }
}

Page size and orientation

pageSize(_:) returns the displayed size in points as a CGSize, with the crop box, /Rotate and /UserUnit applied. pageViewJson(pageIndex:) adds the rotation, the crop box and the matrix from PDF user space to the displayed page:

let size = doc.pageSize(0)
let view = NexPdf.json(try doc.pageViewJson(pageIndex: 0)) as? [String: Any]
print(view?["rotation"] ?? 0, view?["crop"] ?? [], view?["to_display"] ?? [])

To place a PDF rectangle (for example a search hit) on a rendered image, apply to_display [a, b, c, d, e, f] and multiply by dpi / 72. The result has its origin at the top-left, like UIKit:

func toPixels(_ m: [Double], x: Double, y: Double, dpi: Double) -> CGPoint {
    let s = dpi / 72
    return CGPoint(x: (m[0] * x + m[2] * y + m[4]) * s, y: (m[1] * x + m[3] * y + m[5]) * s)
}

Overprint simulation

Print-oriented PDF/X files can use overprint. setOverprint(mode:) sets how later renders treat it: 0 simulates it for PDF/X documents only (the default), 1 always, 2 never.

try doc.setOverprint(mode: 1)
let png = try doc.renderPagePng(pageIndex: 0, dpi: 300)

Memory

Decoded fonts, glyphs and images are cached by the renderer for the whole process, within a size limit, so a font or picture used on many pages is decoded once. doc.memoryUsageBytes() estimates what a document uses, and doc.trimMemory() compacts its buffers when the app receives a memory warning. See Platform notes.

On this page