Design a PDF Viewer – Frontend System Design

We’ll walk through the frontend system design for a PDF viewer: a document with hundreds of pages that must scroll smoothly, let the user select and copy text, highlight passages, find a phrase, zoom, rotate, and print, without running out of memory. You’ll see why pixels, text, and annotations are three different layers, why the file is parsed in a worker, and why the viewport can only keep a handful of page canvases alive.
This is not “drop pdf.js on a canvas and call render”. A 12-page spec works that way. The interviewer says “assume 500 pages, an 80 MB file, find-in-document, and highlights that survive zoom”, and a canvas-per-page design dies on memory. Chrome uses PDFium natively; a web app typically uses pdf.js or PDFium-in-Wasm. Either way the engine is a worker and the main thread is a viewport.
Problem Statement
Design the frontend for a PDF viewer in the browser.
Requirements:
- Open a local file or an HTTPS URL, including files of 80 MB and 500+ pages
- Smooth scroll, zoom, and rotate, with the current page always readable
- Select and copy text; find a query and jump between matches
- Create highlight, ink, and note annotations that survive zoom and reload
- Print the document at a usable resolution
- Stay within a bounded memory budget on a mid-range laptop
Describe the client architecture, the page model, how text and annotations sit on the raster, and how a large file is parsed and evicted.
Interviewers are checking three things. Do you treat a PDF page as a stack of layers, not one canvas? Do you understand that PDF text is positioned glyphs, not a flowing HTML document? And do you have a memory story that does not keep 500 bitmaps around?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Viewer only, or a full PDF editor? | Viewer plus annotations (highlight, ink, sticky note). Rewriting page content is out of scope. |
| 2 | How large is a large file? | 500+ pages, up to ~100 MB. Some pages are image-only scans. |
| 3 | Where do files come from? | User upload and HTTPS URLs. URLs support HTTP range requests when the server allows them. |
| 4 | Forms, signatures, XFA? | Follow existing links and the outline. Filling AcroForms is a follow-up. |
| 5 | Do annotations write back into the PDF? | Not on day one. Persist them to our API in page user space. Export-to-PDF is a later step. |
| 6 | Which browsers? | Evergreen desktop Chrome, Edge, Firefox, Safari, and iPad Safari. |
Question 2 decides virtualization and the cache budget. Question 3 decides whether a linearized PDF can paint page 1 via Range requests before EOF. Question 5 keeps annotations as your JSON; the PDF bytes stay immutable on day one.
Requirements
Functional
- Open a
Fileor a URL. Show the outline (bookmarks) and a thumbnail strip. - Scroll continuously through pages. Jump to a page number or an outline destination.
- Zoom from about 25% to 400%, toward the cursor or the viewport center. Rotate by 90° steps.
- Select text with the mouse and keyboard, copy it with inferred spaces and line breaks.
- Find is case-insensitive, cycles with next/previous, and highlights every match on the current page.
- Highlight selected text, draw ink, drop a note. Existing PDF link annotations still navigate.
- Print the full document, not only the pages that happen to be mounted.
Non-Functional
- First page on screen in a couple of seconds for a large file, without parsing every page into pixels.
- 60fps while scrolling. A fling through 200 pages must not rasterize them all.
- Memory bounded: page bitmaps, decoded images, and text items have a budget and an eviction policy.
- The main thread does not parse content streams. That work lives in a worker.
- Keyboard access to the chrome, and an accessibility tree for the text of visible pages.
The memory bound shapes everything else. A readable retina page is several megabytes; 500 of them are gigabytes. Keep a small pool of live pages and a cache you are willing to throw away.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| Letter page, 100%, DPR 2 | ~7.8 MB | 612 × 792 user units × 22 × 4 bytes | One page is cheap. Five hundred are not. |
| Same page at 150%, DPR 2 | ~17.4 MB | 612 × 1.5 × 2 by 792 × 1.5 × 2 × 4 | Zoom is a memory multiplier. Cap live canvases. |
| 500 pages kept as canvases | ~3.9 GB at 100% | 500 × 7.8 MB | The tab dies. Virtualize. |
| Viewport + overscan | ~4 pages, ~70 MB at 150% | 1.5 in view + 1 above + 1 below + 1 prefetch | A pool of 6 slots is enough. |
| Text items for 500 pages | ~80 MB if fully kept | 2,000 items × 80 bytes × 500 | Extract on demand. Keep a compact find string per page (~2 KB). |
| Find corpus | ~1.5 M characters | 500 × 3,000 chars | A worker indexOf is fine. Do not scan bitmaps. |
| Thumbnail strip | ~24 MB if all rasterized | 500 × 96 × 124 × 4 | Virtualize thumbs with the same pool idea. |
Architecture
The client has four jobs, and they must not share one thread or one data structure.
| Layer | Owns | Runs on | Talks to |
|---|---|---|---|
| UI Shell | Toolbar, find bar, outline, thumbs, tools | React, main thread | Sends intents, reads derived state |
| Viewer | Viewport, virtualizer, layer hosts, LRU | Main thread | Worker RPC, annotation store |
| PDF Worker | Bytes, xref, page tree, op lists, text, find | Web Worker | Main thread via postMessage |
| Persistence | Annotation JSON | REST | Viewer store |
pdf.js already splits this way: pdf.worker.js parses, the main thread paints. You can wrap it or swap in PDFium-in-Wasm. The senior point is the boundary, not the logo on the worker.
“React renders the chrome. A worker owns the PDF graph. The main thread only mounts the pages in view, each as a canvas plus a text layer plus an annotation layer. Zoom is a viewport matrix, not a restyle of stored pixels.”
React must not re-render on scroll. The virtualizer talks to the scroll container directly. The toolbar subscribes to page number and scale at a few updates a second.
Data Model
A PDF is a graph of objects (catalog, page tree, content streams, fonts, XObjects), not a list of images. The worker keeps that graph. The main thread keeps what the viewport needs.
type Deg = 0 | 90 | 180 | 270;
type Mat2x3 = readonly [a: number, b: number, c: number, d: number, e: number, f: number];
interface Rect { x: number; y: number; w: number; h: number }
interface Size { w: number; h: number }
interface PdfDocument {
readonly id: string;
readonly pageCount: number;
readonly pageSizes: readonly Size[]; // MediaBox per page, user space
readonly outline: readonly OutlineItem[];
readonly linearized: boolean;
readonly fingerprint: string;
}
interface PdfPage {
readonly index: number; // 0-based in our model; pdf.js pages are 1-based
readonly mediaBox: Rect;
readonly cropBox: Rect;
readonly rotate: Deg; // built-in page rotation
textItems?: readonly TextItem[];
readonly annots: Annotation[];
}
interface TextItem {
readonly str: string;
readonly transform: Mat2x3; // PDF text matrix
readonly width: number;
readonly height: number;
readonly fontName: string;
readonly dir: "ltr" | "rtl";
readonly hasEOL: boolean;
}
type AnnotType = "highlight" | "ink" | "note" | "link";
interface Annotation {
readonly id: string;
readonly pageIndex: number;
readonly type: AnnotType;
readonly rect: Rect; // user space
readonly quadPoints?: readonly [number, number][];
readonly color: string;
readonly contents?: string;
}
interface Viewport {
scrollTop: number;
scale: number; // CSS px per user unit
rotation: Deg; // viewer rotation, added to page.rotate
dpr: number;
currentPage: number;
}
Three choices are worth defending.
User space, not screen pixels. PDF page coordinates are in the MediaBox, usually 1/72 inch. A highlight stored as { x: 72, y: 640, w: 200, h: 16 } is still on the same glyphs after zoom, rotate, or a crop. Screen pixels are a projection. If you persist CSS coordinates, the first zoom desyncs every annotation and every find rect.
Text is items, not a string. A PDF content stream places glyphs with a text matrix. There is often no space character. Line breaks are geometry. The worker can also produce a compact per-page string for find, but selection and copy need the items and their boxes.
The worker is the source of page sizes. You need every page’s MediaBox before you can build a 500-page scroll. That is a cheap tree walk. You do not need operator lists or fonts for it. Asking for those up front is how open takes ten seconds.
Worker Parse
Parsing on the main thread will hitch the tab. Content streams are a postfix graphics language; fonts need CMaps; a scanned page may decode a large JPEG. None of that belongs next to input handling.
Transfer the ArrayBuffer so the main thread does not keep a copy. For a URL, let the worker fetch and use range requests when the file is linearized (Fast Web View), so page 1 can paint before EOF.
type WorkerReq =
| { id: number; type: "open"; buffer: ArrayBuffer }
| { id: number; type: "openUrl"; url: string }
| { id: number; type: "getPage"; page: number; scale: number; rotation: Deg; dpr: number }
| { id: number; type: "getText"; page: number }
| { id: number; type: "search"; query: string; caseSensitive: boolean };
type WorkerRes =
| { id: number; type: "opened"; doc: PdfDocument }
| { id: number; type: "page"; page: number; bitmap: ImageBitmap; text: TextItem[] }
| { id: number; type: "text"; page: number; text: TextItem[]; haystack: string }
| { id: number; type: "matches"; matches: FindMatch[] }
| { id: number; type: "error"; message: string; code: "password" | "corrupt" | "range" };
A small document client on the main thread wraps this protocol. Opening a local file reads it into an ArrayBuffer, posts an open request with the buffer in the transfer list, and returns a promise that resolves on the matching opened response or rejects on a typed error. Request ids pair responses with callers, so a late page bitmap for a page that already scrolled away can be dropped by id.
Open is two phases. Phase one reads the header, the xref table (or xref stream), the catalog, and the page tree, then returns pageCount, pageSizes, and the outline. Phase two, driven by the virtualizer, asks for operator lists and text for the pages about to be shown.
With pdf.js this is getDocument, getPage, getViewport, render, and getTextContent. Prefer an OffscreenCanvas in the worker that transfers an ImageBitmap. If the engine can only paint a DOM canvas, still parse and extract in the worker. Password files throw before opened: prompt, retry, never log the password. Corrupt files and failed ranges are typed errors.
Page Virtualization
The scroll container’s height is the sum of every page’s projected height plus a gap. Each page that is not mounted is an empty block with the right height, so the scrollbar is honest. Only the visible range plus a one-page overscan get a slot from the canvas pool.
interface PageSlot {
pageIndex: number;
readonly canvas: HTMLCanvasElement;
readonly textLayer: HTMLDivElement;
readonly annotLayer: SVGSVGElement;
readonly findLayer: HTMLDivElement;
}
The layout model is a prefix-sum array of page tops: entry i is the sum of every earlier page’s height times the scale, plus the gaps. It is rebuilt only when the scale, rotation, or page sizes change. Finding the page at a y offset is a binary search for the last top at or above it. The visible range is the page at scrollTop through the page at scrollTop + viewportHeight, each widened by the overscan and clamped to the document.
Use a prefix-sum plus binary search, not IntersectionObserver, as the source of truth. Observer callbacks are async: a fast flick can skip twenty pages before one entry fires. Observer is a fine hint for thumbnail prefetch, a poor scroll controller.
The pool is a fixed array of slots. When page 11 leaves and page 16 enters, detach slot A, set canvas.width = 0 to drop the backing store, bind it to page 16, and paint. If the LRU still has an ImageBitmap at this scale, skip the worker.
Thumbnails are the same component at ~96 CSS px wide, with their own tiny pool. Rasterizing all 500 on open is how a sidebar steals more memory than the viewport.
Text Layer and Selection
The canvas is a picture of the page. It cannot select, copy, or speak. The text layer is a stack of absolutely positioned <span>s, one per TextItem, transformed so each span sits on the glyphs the canvas already drew. The browser then owns caret, selection, and the accessibility tree.
Each span’s placement comes from one matrix product: the viewport transform (scale and rotation, user space to CSS pixels) times the item’s text matrix. From the product you read the baseline position, the font height (the length of the vertical basis vector), and the font width. The span gets left, a top shifted up by the font height, a font-size, and a horizontal scaleX stretch so the browser’s rendered string matches the item’s measured width.
In production you call the engine’s helper (pdf.js TextLayer). The idea you must explain: the PDF text matrix, composed with the viewport matrix, becomes left, top, font-size, and a horizontal stretch so a condensed run still sits on the raster.
Several PDF facts leak into this layer.
- Spaces are often missing. The copy handler cannot join
item.strvalues with the empty string. If the gap between two items on the same baseline is larger than some fraction of the font size, insert a space. IfhasEOLis set or the next item jumps down a line, insert a newline. - ToUnicode may be absent. Embedded subset fonts without a CMap extract as garbage. Show the glyphs (the canvas is fine) but copy will be wrong. A senior answer mentions this instead of promising perfect extraction.
- Rotation and vertical text. The matrix already encodes it. Do not special-case 90° in the span layout unless you are debugging a specific engine bug.
- Selection across pages. If each page’s text layer is a sibling in one scroll container, native selection can span them. Do not put pages in separate iframes or shadow roots if you want that for free.
The text layer is CSS, not a DPR bitmap. Scale it with the same viewport matrix as annotations, and rebuild spans only when items change (new page or a rotate). Rebuilding on every wheel tick is wasted work.
Annotations
Treat viewer annotations and file-origin annotations as the same type: page index, type, user-space rect, optional quads, color, optional text. File links are read-only. Highlights, ink, and notes are writable and live in your store.
Highlight. Take the current Selection, map each selected span back to its TextItem, and store quadPoints (four corners per line box) in user space. Drawing is an SVG path or a set of <rect>s on the annotation layer, filled with a translucent color. Because the boxes are user space, zoom and rotate only change the viewport transform.
Ink. Record pointer points, convert each from CSS pixels back through the inverse viewport matrix, and store a polyline. Draw it as an SVG polyline with vector-effect: non-scaling-stroke if you want a constant screen width, or in user units if the pen should grow with zoom. Use setPointerCapture so a stroke that leaves the page still ends cleanly.
Note. A point plus contents. The pin is on the annotation layer; the popup is chrome, not a page layer, so it can escape the page clip.
Tool mode decides pointer-events. In Select, the annotation layer is none so the text layer can be selected, except for small hit targets on note pins and link rects. In Highlight, selection still runs; on pointer up you map intersecting text items to user-space quads and clear the native selection. In Ink, the annotation layer captures the pointer and the text layer is inert.
Persist on a debounce after create, edit, or delete. The API is per document so a later export job can write one PDF. Reload hydrates the store and the layer draws on top of the raster. Never bake highlights into the canvas: you would re-raster on every edit and lose hit-testing.
Find in Document
Find cannot look at pixels. OCR is a different product. Here the corpus is the extracted text the worker already has to build the text layer.
Keep a compact haystack per page: the concatenated str values with the same inferred spaces and newlines the copy handler uses, plus a map from character offset to a user-space box. Search in the worker with indexOf (or a regex later). Return matches as { pageIndex, start, length, rects }.
If the user finds before every page is extracted, search what you have, then extract the rest in idle slices and append matches. The find bar shows “12 of 40+” until the index is complete. Do not block open on a full-document extract.
The find layer is a fourth overlay: translucent rects, active match stronger, pointer-events: none. Next/previous sets scrollTop from the prefix-sum so the page mounts, then scrolls the rect into view. Hyphenation across line breaks (“docu- / ment”) is the edge to name: strip hyphens from the haystack or accept misses.
Zoom and Rotate
Scale is CSS pixels per user unit. A 612-wide letter page at 1.25 is 765 CSS px wide. The canvas backing store is that size times devicePixelRatio, or it looks soft on a retina display.
Do not re-rasterize on every wheel or pinch event. During the gesture, CSS-scale the cached bitmaps and overlays (briefly soft). When it ends, or after a 100–150 ms debounce on keyboard zoom, request bitmaps at the settled scale and DPR.
Zoom toward the cursor by keeping the user-space point under the pointer fixed, the same camera trick as a canvas editor.
Zoom is a pure function from the current viewport, the pointer position, and the requested scale to a new viewport. Clamp the scale to about 25% to 400%. Find the page under the pointer and the pointer’s offset inside that page, and convert that offset to user units by dividing by the old scale. Rebuild the prefix sums at the new scale, then set scrollTop so the same user-space point lands under the same pointer y. Horizontal scroll follows the same rule.
Rotation is a viewer increment added to each page’s built-in rotate. 90° and 270° swap projected width and height, so rebuild the prefix-sum and remap scrollTop onto the same page. Quads stay in unrotated user space; the viewport matrix absorbs the rotate. Rebuild the text layer after a rotate. For a pure scale, CSS-scale the existing spans until new bitmaps arrive. A devicePixelRatio change (another monitor) is a zoom commit: same CSS size, new backing store.
Print breaks a naive virtualizer. window.print() on the live viewer prints the chrome and the three mounted pages. That is a bug.
Two honest designs:
| Strategy | Quality | Memory | When to use |
|---|---|---|---|
Iframe the original PDF blob and call print() on it |
Native, vector where the browser supports it | One extra document | Default. Best output. |
| Hidden print document: one image per page at ~150 DPI | Raster, good enough | Must stream; never hold 500 print-DPI bitmaps | Fallback when the blob cannot be printed (some Safari cases, annotated export) |
Propose the iframe first. You already have the bytes; a blob URL plus a hidden iframe lets the browser plugin paginate. Use @media print only for the raster fallback.
If you must rasterize, do it off-screen at ~150 DPI (150/72 ≈ 2.08 scale, no extra DPR), one <img> per page with break-after: page, and revoke object URLs as you go. Do not reuse the screen pool. Tear the print tree down on afterprint.
Viewer annotations are not in the original bytes, so they will not appear in the iframe path. If print must include highlights, use the raster fallback or a server export that merges annotation JSON into a new PDF. Say that trade-off out loud.
Memory of Large Files
Budget the heap the way you budget a GPU renderer. Cap page bitmaps (128 MB is a reasonable laptop number) and evict to it.
- Live slots equal the pool size. Each holds one canvas backing store.
- Bitmap LRU keyed by
(pageIndex, scaleBucket, rotation, dpr). Snap scale to a few buckets so 101% and 104% share a raster. On overflow,bitmap.close()the least recently used one and drop that page’s decoded XObjects in the worker. - Worker: keep xref and the page tree for the document lifetime. Drop operator lists for pages that are neither mounted nor in the LRU. pdf.js exposes
page.cleanup()anddoc.cleanup(). - One copy of the bytes. After transfer, keep the blob only if the print iframe still needs it.
- Text:
TextItem[]for mounted pages; haystack + boxes for find on the rest. The worker can extract again.
Zeroing a canvas matters. A smaller CSS size does not release the GPU backing store. Set width and height to 0, then to the next page. On close: destroy the loading task, terminate the worker, close bitmaps, revoke blob URLs.
Scanned pages are the pathological case. A 300 DPI full-page image can dwarf the vector pages around it. Decode at the current scale, not native, and never hand the main thread a 30 MB bitmap for a thumbnail.
API
// REST, annotations only. The PDF itself is a blob the client already has.
GET /api/docs/:docId/annotations // 200 { data: Annotation[] }
PUT /api/docs/:docId/annotations // replace-all after a local batch
POST /api/docs/:docId/annotations // { data: Annotation } -> 201
PATCH /api/docs/:docId/annotations/:id // color, contents, rect
DELETE /api/docs/:docId/annotations/:id
// Optional: the server already hosts the file
GET /api/docs/:docId/file // application/pdf, Accept-Ranges: bytes
GET /api/docs/:docId // { pageCount?, fingerprint, title }
interface FindMatch {
pageIndex: number;
start: number;
length: number;
rects: Rect[];
}
No WebSocket. One user, occasional writes. Export later is a server job: PDF bytes plus annotation JSON in, a new PDF out. The viewer does not write PDF.
Hosted files need Accept-Ranges so linearized documents can paint page 1 during download. Cross-origin URLs need CORS that exposes Content-Range. A missing Access-Control-Allow-Headers: Range forces a full download; detect that and fall back.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Main-thread parse jank | Worker + transferable buffer | Input stays at 60fps during open |
| Gigabytes of canvases | Pool + prefix-sum virtualizer | A handful of live pages |
| Revisit a nearby page | ImageBitmap LRU by scale bucket | No second raster |
| Zoom hitch | CSS-scale, then re-raster | Soft frames, not dropped ones |
| Find on 500 pages | Worker haystacks, idle extract | First matches early, full index later |
| Slow first paint on a URL | Linearized PDF + range requests | Page 1 before EOF |
| Raster on the main thread | OffscreenCanvas in the worker | Main thread only composites |
| Thumbnails blow the budget | Own tiny pool, downsampled decode | Sidebar stays cheap |
After scrolling the whole document, a heap snapshot should show a sawtooth of bitmaps that does not climb with page number. If JS heap grows with scrollTop, something is retaining op lists, canvases, or text layers.
Handling Edge Cases
- Password. Prompt, retry, do not store it.
- Corrupt xref / truncated download. Typed error, keep painted pages, offer retry.
- Missing ToUnicode. The page looks fine; copy and find are wrong. Say so.
- Image-only scans. Empty text layer. Find misses without OCR (out of scope). Still virtualize: these are the heavy pages.
- Mixed page sizes. Prefix-sum handles it. Do not assume a constant row height.
- Page rotate + viewer rotate. Add modulo 360 and rebuild sizes.
- Worker crash. Recreate it, reopen from the print blob, restore viewport and annotations.
- Safari canvas limits. Huge zoom × DPR can exceed the max dimension. Clamp the backing store and CSS-upscale.
- RTL and vertical CJK. Trust
dirand the text matrix. Do not reorder strings yourself.
Accessibility and Security
Accessibility
- Chrome is real controls: page spinbutton, zoom, find,
role="toolbar". Zoom is not wheel-only. - Visible text lives in the text layer. Announce page changes in
aria-live="polite": “Page 12 of 248”. - The outline is a
role="tree". Thumbnails need alt (“Page 12”). - Find announces “Match 3 of 11”. The active match is not color-only; add an outline.
- Keyboard: page up/down, next/prev match, escape to leave find.
- Respect
prefers-reduced-motion. High contrast must not rely on yellow alone; add a border to fills.
Security
- PDF is untrusted. Parse in the worker, never
evalstreams, never inject extracted strings as HTML.textContentonly. - Link annotations: allowlist
https:and in-document dests. Blockjavascript:. - Cross-origin URLs need CORS. Do not proxy arbitrary URLs (SSRF).
- CSP
worker-src; blob workers needblob:. - Annotation
contentsis user text. Escape it. A note popup is not an HTML sink.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Rendering | One canvas per page | Pool + prefix-sum virtualizer, LRU of ImageBitmaps, scale buckets |
| Text | Draw strings on the canvas | Text layer of positioned spans; copy infers spaces; ToUnicode can fail |
| Annotations | Divs in CSS pixels | User-space rects and quads; viewport transform; pointer-events by tool |
| Find | Ctrl+F on the DOM | Worker haystacks, incremental extract, rects on a find layer |
| Parse | pdf.js on the main thread | Worker, transferable buffer, range requests, cleanup/evict |
window.print() the viewer |
Iframe the PDF blob, or stream print-DPI rasters, never the pool |
For the same virtualization idea in a text editor, see Design VS Code for the Web. For a GPU canvas that also projects a camera onto user-space geometry, see Design Figma.
Conclusion: How to Design a PDF Viewer
Start with the layers. The worker owns the file and walks content streams. The main thread owns a viewport: a prefix-sum of page sizes, a tiny canvas pool, and three overlays that all share one user-space transform. Text is a layer so the browser can select and read. Annotations and find hits are layers so they can change without a re-raster.
Then bound memory. Live canvases equal the viewport plus overscan. Everything else is a placeholder or an evictable bitmap. Zoom CSS-scales first and re-rasters second. Print uses the original bytes, not the three pages on screen. If you can explain why a highlight is stored in the MediaBox and why IntersectionObserver is the wrong scroll controller, you have shown the interviewer you have actually built a document viewport.
