Rendering pages
Render PDF pages and thumbnails to PNG with NexPDF for Node.js, and map PDF coordinates to pixels.
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, { dpi }) returns the PNG bytes of a page. At 72 dpi one pixel is one PDF point; the
default is 150 dpi, 144 dpi is a good choice for screens and 300 dpi for print.
import { writeFile } from 'node:fs/promises';
import { PdfDocument } from '@nexdevit/nexpdf-node';
const doc = await PdfDocument.open('report.pdf');
for (let i = 0; i < doc.pageCount; i++) {
await writeFile(`page-${i + 1}.png`, doc.render(i, { dpi: 144 }));
}
doc.close();Render a thumbnail
doc.raw.renderThumbPng(page, maxDim) fits the page into a square of maxDim pixels, keeping the
aspect ratio:
const thumb = doc.raw.renderThumbPng(0, 256);Page size and orientation
pageSize(page) returns the displayed size in points, with the crop box, /Rotate and /UserUnit
applied. doc.raw.pageViewJson(page) adds the rotation, the crop box and the matrix from PDF user
space to the displayed page:
const { width, height } = doc.pageSize(0);
const view = JSON.parse(doc.raw.pageViewJson(0));
console.log(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:
function toPixels(view, x, y, dpi) {
const [a, b, c, d, e, f] = view.to_display;
const 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. doc.raw.setOverprint(mode) sets how later renders
treat it: 0 simulates it for PDF/X documents only (the default), 1 always, 2 never.
doc.raw.setOverprint(1);
const png = doc.render(0, { dpi: 300 });Memory
Each open document lives in WebAssembly memory. doc.raw.memoryUsageBytes() reports the current
use, and doc.close() frees it. Close documents in long-running services as soon as a request is
done.