Skip to Content
NexPDF

Rendering pages

Render PDF pages and thumbnails to PNG with NexPDF for Rust, 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 as a Vec<u8>. At 72 dpi one pixel is one PDF point; 144 dpi is a good default for screens, 300 dpi for print.

use nexpdf_sdk::Document;

fn main() -> nexpdf_sdk::Result<()> {
    let doc = Document::open("report.pdf")?;
    for i in 0..doc.page_count()? as usize {
        std::fs::write(format!("page-{}.png", i + 1), doc.render_page_png(i, 144.0)?)?;
    }
    Ok(())
}

Render a thumbnail

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

let thumb = doc.render_thumb_png(0, 256)?;

Page size and orientation

page_width(i) and page_height(i) return the displayed size in points as f64, 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:

let (w, h) = (doc.page_width(0), doc.page_height(0));
let view = doc.page_view_json_value(0)?;              // `serde` feature
println!("{} {} {}", 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:

fn to_pixels(view: &serde_json::Value, x: f64, y: f64, dpi: f64) -> (f64, f64) {
    let m: Vec<f64> = (0..6).map(|i| view["to_display"][i].as_f64().unwrap_or(0.0)).collect();
    let s = dpi / 72.0;
    ((m[0] * x + m[2] * y + m[4]) * s, (m[1] * x + m[3] * y + m[5]) * 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. It takes &mut self.

doc.set_overprint(1)?;
let png = doc.render_page_png(0, 300.0)?;

Memory

Rendering caches decoded fonts and images per document. For long-running services, doc.trim_memory() drops those caches and doc.memory_usage_bytes() reports the current use; both return a usize.

On this page