Skip to Content
NexPDF

Rendering pages

Render PDF pages and thumbnails to PNG in the browser with NexPDF for the web, and map PDF coordinates to screen pixels on rotated and cropped pages.

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

render(page, { dpi }) returns the PNG bytes of a page and renderUrl(page, { dpi }) an object URL you can put in an img. At 72 dpi one pixel is one PDF point; the default is 110 dpi. Multiply by devicePixelRatio for sharp pages on high-density screens.

import { loadNexPdf } from '@nexdevit/nexpdf-web/engine';

const nex = await loadNexPdf();
const doc = await nex.PdfDocument.fromUrl('/report.pdf');

const img = document.querySelector('img')!;
img.src = doc.renderUrl(0, { dpi: 110 * devicePixelRatio });
img.onload = () => URL.revokeObjectURL(img.src);

To draw on a canvas, decode the bytes into a bitmap:

const png = doc.render(0, { dpi: 144 });
const bitmap = await createImageBitmap(new Blob([png], { type: 'image/png' }));
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext('2d')!.drawImage(bitmap, 0, 0);

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 coordinates

pageSize(page) returns the displayed size in points, with the crop box, /Rotate and /UserUnit applied. pageView(page) returns a PageView that maps between PDF points and the displayed page, whose origin is the top-left corner with y pointing down:

const view = doc.pageView(0);
console.log(view.width, view.height, view.rotation, view.crop);

const scale = 144 / 72;                                   // pixels per point at 144 dpi
const box = view.rectToView([72, 700, 300, 716], scale);  // { left, top, width, height } in pixels
const [x, y] = view.toPdf(event.offsetX, event.offsetY, scale);   // a click, in PDF points
MethodConverts
toView(x, y, scale)A PDF point to display pixels
toPdf(vx, vy, scale)Display pixels (a click or tap) to a PDF point
deltaToPdf(dx, dy, scale)A drag on screen to a displacement in PDF space
rectToView(rect, scale)A PDF rectangle to { left, top, width, height }
rectToPdf(x1, y1, x2, y2, scale)Two screen corners to a PDF rectangle

Use it to draw search hits or annotation rectangles over a rendered page, and to turn a selection the user draws into the rectangle a call needs.

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.

On this page