PerformancePDF
How the PDF viewer keeps large documents responsive, where rendering runs, the options that trade sharpness for memory, and how to measure your own documents.
The viewer is built so that the cost of showing a document depends on what is on screen, not on how many pages it has.
How rendering works#
- Virtualized pages. Only the visible pages and two rows of neighbours on each side have elements in the DOM. Pages that scroll out of that window are destroyed and their canvases released.
- A prioritised queue. Page rendering goes through one queue, ordered by distance from the centre of the viewport: visible pages first, then neighbours, then thumbnails, then placeholders. A render is cancelled when its page leaves the window.
- Device pixel ratio. Pages are rendered at the device pixel ratio, placed on whole device pixels and shown at exactly the size of their bitmap, so text is sharp on high-density screens and at fractional zoom levels.
- A canvas size limit. A page canvas never exceeds
maxCanvasPixels(16.7 megapixels by default). Above that, at high zoom, the page is rendered at the highest resolution that fits and the visible region is rendered again on top as a sharp detail tile. - A budget for neighbours. Pages outside the viewport share what is left of
maxRenderPixels(64 megapixels by default) and are rendered at a lower resolution when the budget is tight. - Placeholders. Low-resolution previews of the next rows are prepared in the background, so fast scrolling shows a blurred page rather than a blank one. They share a cache of at most 12 megapixels with the thumbnails.
- Text layers are built for visible pages only.
- Zoom gestures. While you pinch or Ctrl+wheel, existing canvases are scaled and rendering waits until the gesture has stopped.
- A render worker. Pages are parsed and rasterised in a worker by default, where the browser has
WorkerandOffscreenCanvas. Otherwise, or withworker: false, the same engine runs on the main thread in short time slices and yields to the event loop between them. - Thumbnail refreshes. A change to annotations, form values or redactions marks the thumbnails of the pages it touches. They are redrawn at most once every 150 ms, also while changes keep arriving, and only the thumbnails in view; the others catch up when they scroll into view or when the Pages panel is shown again. No timer runs while the panel is hidden. One pass reads the form once, and the sidebar keeps at most 24 megapixels of rendered thumbnails.
- Lazy loading. The rendering engine is imported the first time a document is opened, the substitute fonts and CJK CMap tables when a page needs them, and thumbnails are rendered when the Pages panel shows them.
Measured figures#
The browser tests e2e/tests/pdf-perf.spec.ts and e2e/tests/pdf-render-perf.spec.ts measure loading, scrolling, long tasks and memory on generated reports of 200 and 2,000 pages. Figures from those runs depend on the machine, the browser and the documents; run the tests, or the snippets below, on your own documents and devices.
As an indication, one run of those tests in Chrome at 1440 × 900 on a shared development laptop (load average about 2.9):
| Document | Path | First page after createPdfViewer |
Median frame while scrolling 24 pages | Long tasks while scrolling |
|---|---|---|---|---|
| 200 pages, 0.92 MB | worker | 182 ms | 16.7 ms | none |
| 200 pages, 0.92 MB | main thread | 173 ms | 16.7 ms | none |
| 2,000 pages, 9.23 MB | worker | 284 ms | 16.7 ms | none |
| 2,000 pages, 9.23 MB | main thread | 272 ms | 16.7 ms | none |
The engine on its own opened the 200-page report in 9 ms on the main thread and 23 ms through the worker, and the 2,000-page report in 44 ms and 42 ms; a page took a median of 4 ms to draw on the main thread and 6 to 8 ms through the worker, which includes handing the bitmap back. Over a simulated 30 ms, 8 MB/s connection the 2,000-page report showed its first page after 0.25 s with range loading and after 1.44 s as one download. Your documents and devices will differ.
Large files#
With a URL or a rangeLoader the first page is shown before the whole file has arrived, for linearised files and for files that are not linearised. The time until editing is possible does not change, because editing needs the whole file. See Progressive loading.
Main-thread blocking#
In worker mode parsing and rasterising do not run on the main thread. What stays there is the viewer itself: layout, the text and annotation layers, and copying finished bitmaps to the page canvases. On the main thread the engine works in slices and opening a document walks the page tree in slices of about 8 ms, so a long document does not open in one long task. A page with heavy vector art takes longer to appear in either mode.
Options#
| Option | Default | Use it to |
|---|---|---|
maxCanvasPixels |
16777216 |
Lower the memory per page on phones (for example 5_000_000), at the cost of relying on the detail tile earlier |
maxRenderPixels |
64000000 |
Limit the total canvas memory of off-screen neighbour pages |
pixelRatio |
devicePixelRatio |
Render at 1 on a high-density screen to save memory and time, with softer text |
placeholders |
true |
Turn off the background previews when memory matters more than fast scrolling |
zoom, maxZoom |
'auto', 16 |
Keep users from zooming to levels your documents do not need |
sidebar, isSidebarOpen |
'thumbnails', true |
Start with the sidebar closed, so no thumbnails are rendered until it is opened |
printResolution |
150 |
Image printing renders every printed page as an image; 300 dpi takes about four times the memory and time of 150. Vector printing writes one PDF copy instead and ignores the resolution |
Measuring your own documents#
getRenderStats() returns what the viewer holds at this moment:
const stats = viewer.getRenderStats();
console.table({
pageViews: stats.views,
rendered: stats.renderedViews,
megapixels: (stats.canvasPixels / 1e6).toFixed(1),
queued: stats.queued,
thumbnails: stats.thumbnails,
thumbnailMegapixels: (stats.thumbnailPixels / 1e6).toFixed(1),
renderMode: stats.renderMode,
});const started = performance.now();
const viewer = createPdfViewer(container, { document: bytes });
await viewer.ready;
console.info(`ready after ${Math.round(performance.now() - started)} ms`);viewer.ready resolves when the document is parsed and the first page is laid out; the first paint follows as soon as the page has been rendered. renderMode is 'worker' or 'main', so you can see whether the worker started.
Saving, searching and the headless API#
- Search extracts the text of each page once and keeps the index for the session, so the first search in a long document takes longest.
- Saving runs on the main thread, like comparing and redacting: the document engine is not moved to the worker. An incremental save writes only the changed objects and is fast whatever the size of the file; a full rewrite copies every object in use.
- Headless work on large batches belongs in a worker or on a server.
openPdfDocumentneeds no DOM, so the same code runs there unchanged. - Colour. There is no full colour management module and no overprint preview; see What the renderer does not do.
- Memory. The viewer's document engine keeps the bytes of the open document, and the render worker keeps its own copy. Call
viewer.destroy()when the viewer is removed; it cancels rendering, releases the canvases and the open document, and terminates the worker the viewer created.
How output is checked#
Besides unit tests, the package has a validation run that opens its output with independent tools: qpdf --check for file structure, poppler for rendering, text and attachments, pdfsig and OpenSSL for signatures, and LibreOffice. Files saved with annotations pass qpdf --check, and a document signed through the viewer is reported by pdfsig as validly signed, with a signature that covers the whole document.