Skip to Content
NexPDF

Rendering pages

Render PDF pages and thumbnails to PNG with NexPDF for Python, and map PDF coordinates to pixels.

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

render_page_png(page_index, dpi) returns the PNG bytes of a page. At 72 dpi one pixel is one PDF point; 144 dpi is a good default for screens, 300 dpi for print.

import nexpdf

with nexpdf.Document.open("report.pdf") as doc:
    for i in range(doc.page_count()):
        with open(f"page-{i + 1}.png", "wb") as f:
            f.write(doc.render_page_png(i, 144))

Render a thumbnail

render_thumb_png(page_index, max_dim) fits the page into a square of max_dim pixels, keeping the aspect ratio:

thumb = doc.render_thumb_png(0, 256)

Page size and orientation

page_size(i) returns the displayed size in points, with the crop box, /Rotate and /UserUnit applied. page_view_json(i) adds the rotation, the crop box and the matrix from PDF user space to the displayed page:

w, h = doc.page_size(0)
view = nexpdf.loads(doc.page_view_json(0))
print(view["rotation"], 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:

def to_pixels(view, x, y, dpi):
    a, b, c, d, e, f = view["to_display"]
    s = dpi / 72
    return ((a * x + c * y + e) * s, (b * x + d * y + f) * s)

Overprint simulation

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

doc.set_overprint(1)
png = doc.render_page_png(0, 300)

Memory

Rendering caches decoded fonts and images per document. For long-running workers, doc.trim_memory() drops those caches and doc.memory_usage_bytes() reports the current use.

On this page