Reading and Writing PDFs in JavaScript: pdf-lib vs PDF.js
How pdf-lib and PDF.js divide the work of reading and writing PDFs in JavaScript, why a PDF is a graph of objects rather than a stack of pages, and what each kind of compression really does.
If you only know one thing about PDFs in JavaScript, make it this: there are two major libraries, they do almost completely different jobs, and you will usually want both. PDF.js (published on npm as pdfjs-dist) reads a PDF. It can parse the page tree, pull text out, render a page onto a canvas, and walk the operator list to recover embedded images. pdf-lib edits the document model. It can copy pages between documents, reorder them, rotate them, embed an image, draw text and set the crop box, all without ever turning a page into pixels.
The confusion comes from the fact that both libraries can "open a PDF", but what they do after opening is opposite. PDF.js gives you a read-oriented view built for display and extraction. pdf-lib gives you a mutable object graph that it can serialize back into a valid PDF file. PDF.js cannot save your edits back to a PDF; pdf-lib cannot render a page to a bitmap. Once you internalize that split, the right tool for any task becomes obvious.
This post covers how each library models a PDF, why operations like merge and split preserve content while "compress by rasterizing" throws information away, and where the page tree fits into all of it. The code samples are short, standalone sketches, and everything in them runs in the browser.
A PDF is a graph of objects, not a stream of pages
A PDF file is a collection of numbered objects: dictionaries, arrays, strings, numbers, and streams (compressed blobs of content). Those objects reference each other by number. At the top sits the catalog, the catalog points at a Pages node, and that node is the root of the page tree: a tree of Pages (intermediate) and Page (leaf) nodes. Each leaf Page carries its size (the MediaBox), its rotation, references to the fonts and images it uses, and a content stream of drawing operators.
The important consequence: a "page" is a node that references shared resources (fonts, color spaces, embedded images) that other pages may use too, rather than a self-contained chunk of bytes you can slice out. Any tool that moves pages around has to chase those references and copy what is needed. This is exactly what pdf-lib's copyPages does under the hood, and it is why merging is more subtle than concatenating files.
When you load a document with pdf-lib, you get a live representation of that object graph that you can mutate and re-serialize:
import { PDFDocument } from 'pdf-lib';
const doc = await PDFDocument.load(bytes);
const count = doc.getPageCount();
const indices = doc.getPageIndices(); // [0, 1, 2, ...]
PDF.js loads the same file but hands you a document proxy whose API is shaped around reading: getPage(n), page.getViewport(), page.getTextContent(), page.render(), pdf.getMetadata(). There is no addPage and no save. That asymmetry explains everything that follows.
pdf-lib: editing the document model
Merge and split preserve content
Merging is the cleanest demonstration of working at the object level. Create an empty document, then for each input, copy its pages into the new document and append them:
import { PDFDocument } from 'pdf-lib';
async function merge(inputs: ArrayBuffer[]): Promise<Uint8Array> {
const out = await PDFDocument.create();
for (const bytes of inputs) {
const src = await PDFDocument.load(bytes);
const pages = await out.copyPages(src, src.getPageIndices());
for (const page of pages) out.addPage(page);
}
return out.save();
}
copyPages does the heavy lifting. It deep-copies each page node and every object it transitively references (fonts, image XObjects, content streams) into the destination document, renumbering objects so nothing collides. The text stays text, vector graphics stay vectors, fonts stay embedded fonts. Nothing is rasterized, so the result is lossless: a merged page carries the same drawing instructions as the source, just living in a new file with renumbered objects.
Splitting is the mirror image. Create one new document per page, copy that single page in, and save:
async function splitIntoPages(bytes: ArrayBuffer): Promise<Uint8Array[]> {
const src = await PDFDocument.load(bytes);
const results: Uint8Array[] = [];
for (const index of src.getPageIndices()) {
const doc = await PDFDocument.create();
const [page] = await doc.copyPages(src, [index]);
doc.addPage(page);
results.push(await doc.save());
}
return results;
}
Each output file carries every resource its page references, which is why the pieces of a split often add up to more than the original: a font shared by all the pages gets its own copy in every file.
Extract, remove and reorder are all variations on the same pattern: decide which indices to keep and in what order, then copyPages them in that order. Reordering, for example, is just a permuted list of indices. Because the unit of work is the page node, "reorder" and "extract" need no special machinery; they are different argument lists to the same copy primitive.
Rotation flips a number, it does not redraw
Rotating a page is a good example of editing metadata rather than content. The page's rotation is a single entry in its dictionary (/Rotate), constrained to multiples of 90. pdf-lib exposes it directly:
import { degrees } from 'pdf-lib';
const page = doc.getPage(0); // pdf-lib counts pages from 0
const current = page.getRotation().angle;
page.setRotation(degrees((current + 90) % 360));
setRotation replaces the existing value rather than adding to it, which is why the sketch reads the current angle first. No pixels move. The viewer reads the rotation flag and turns the page when it displays it. The content stream is untouched, so this is lossless and essentially free, however complex the page is.
Drawing new content: watermarks, headers, footers
pdf-lib can also append to a page's content stream. To watermark a document, embed a font, then draw text on top of every page:
import { PDFDocument, StandardFonts, degrees, rgb } from 'pdf-lib';
async function watermark(bytes: ArrayBuffer, text: string): Promise<Uint8Array> {
const doc = await PDFDocument.load(bytes);
const font = await doc.embedFont(StandardFonts.HelveticaBold);
const size = 48;
for (const page of doc.getPages()) {
const { width, height } = page.getSize();
page.drawText(text, {
x: (width - font.widthOfTextAtSize(text, size)) / 2,
y: height / 2,
size,
font,
color: rgb(0.8, 0.1, 0.1),
opacity: 0.25,
rotate: degrees(45),
});
}
return doc.save();
}
A few details matter here. First, pdf-lib's coordinate origin is the bottom-left corner and y increases upward, which is the PDF convention, unlike the top-left, y-down convention you know from the DOM and canvas. A footer therefore goes at a small y value, and a header at the page height minus a margin. Rotation also pivots on the text's starting point, so a diagonal watermark needs a small offset to look truly centered.
Second, the standard 14 fonts (Helvetica, Times, Courier and a few others) are not embedded as font files. Every PDF viewer is expected to supply them, so StandardFonts.HelveticaBold adds almost nothing to the file size. The catch is that they only cover the WinAnsi character set, so text in Cyrillic or Chinese, for example, needs a real font. pdf-lib embeds custom fonts with the help of the fontkit package, and the font bytes then travel inside the file.
Cropping is similarly model-level. page.setCropBox(x, y, width, height) changes the visible rectangle without removing any drawing operators:
const { width, height } = page.getSize();
const inset = 36; // PDF units are points: 72 to the inch
page.setCropBox(inset, inset, width - inset * 2, height - inset * 2);
The cropped-out content still exists in the file; it is just not displayed. Keep that in mind if you are cropping to hide something, because anyone with a PDF editor can reset the crop box and see it again.
PDF.js: rendering and parsing
PDF.js is what you reach for when you need to see or read the content rather than restructure it. Run it with a worker so the heavy parsing happens off the main thread:
import * as pdfjsLib from 'pdfjs-dist';
// Point PDF.js at the worker script that ships with pdfjs-dist.
// How you reference the file depends on your bundler.
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
const pdf = await pdfjsLib.getDocument({ data: bytes.slice(0) }).promise;
The slice(0) is deliberate. PDF.js generally transfers the typed array you give it to its worker thread, which leaves your original buffer detached and empty. If you plan to hand the same bytes to pdf-lib afterwards, give PDF.js a copy.
Reading page dimensions and metadata
For a page-info panel, ask PDF.js for the viewport of each page and read the document's info dictionary:
const sizes = [];
for (let n = 1; n <= pdf.numPages; n++) {
const page = await pdf.getPage(n); // PDF.js counts pages from 1
const { width, height } = page.getViewport({ scale: 1 });
sizes.push({ page: n, width, height }); // in points
}
const { info } = await pdf.getMetadata();
const { Title, Author } = info as { Title?: string; Author?: string };
Note the off-by-one trap between the two libraries: PDF.js numbers pages from 1, pdf-lib indexes them from 0. The sizes differ in a subtler way too. A PDF.js viewport already accounts for the page's /Rotate value, so a page rotated by 90 degrees reports its width and height swapped, while pdf-lib's page.getSize() returns the unrotated MediaBox. PDF.js was also built to display whatever real-world files throw at it, so its parser tends to be more forgiving of damaged or unusual documents, which makes it a good choice for read-only inspection.
Extracting text is reconstruction, not retrieval
A PDF does not store paragraphs. It stores instructions like "set font F1 at 11pt, move to (72, 700), show these glyphs." Text extraction means collecting every such fragment with its position and reassembling reading order yourself. PDF.js gives you the fragments via getTextContent(), each with a transform matrix whose entries at index 4 and 5 are the x and y position:
const { items } = await page.getTextContent();
let text = '';
let prevY: number | null = null;
let prevEndX: number | null = null;
for (const item of items) {
if (!('str' in item) || !item.str) continue;
const x = item.transform[4];
const y = item.transform[5];
if (prevY !== null && Math.abs(y - prevY) > 5) {
text += '\n'; // a vertical jump: new line
} else if (prevEndX !== null && x - prevEndX > 10) {
text += ' '; // a horizontal gap: new word
}
text += item.str;
prevY = y;
prevEndX = x + item.width;
}
The thresholds in this sketch (a jump of more than 5 units starts a new line, a gap of more than 10 inserts a space) are arbitrary choices, not something the library provides. Recent versions of PDF.js also mark fragments that end a line with a hasEOL flag, which helps, but the fragments arrive in content-stream order, and on a multi-column page that is not always reading order. Turning positioned glyph runs back into lines and words is an inherently lossy guess. It is also why text extraction fails entirely on scanned PDFs: there are no text fragments, only an image, and you would need OCR.
Rendering and recovering embedded images
To rasterize a page, size a canvas to the viewport and call render:
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 2 });
const canvas = document.createElement('canvas');
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
// Older releases take canvasContext: canvas.getContext('2d') instead of canvas
await page.render({ canvas, viewport }).promise;
The scale is the lever. At scale 1, one canvas pixel is one PDF point (72 per inch), so scale 2 gives 144 dpi: sharper, but four times as many pixels and roughly four times the memory. This is the entry point for PDF-to-image export.
PDF.js can also recover the images that are embedded inside a PDF (the original photos and logos, not a render of the page). You walk the page's operator list looking for OPS.paintImageXObject operations, then pull the named image object out of page.objs. Depending on the source, that object either exposes a bitmap (an ImageBitmap) that you can drawImage directly, or raw pixel data tagged with a kind that says how it is packed: 1 bit per pixel black and white, 24-bit RGB, or 32-bit RGBA. In the raw case you unpack the data into an ImageData yourself. Either way you get decoded pixels, so saving them means re-encoding. When an image is stored as a JPEG (the DCTDecode filter), the stream bytes are already a complete JPEG file, and reading them straight out of the object graph gives you the original without re-encoding. That operator-list walk is firmly read-side work: it parses content, it does not change it.
Why compression is the awkward middle case
Here is where the two libraries meet, and where it pays to understand the trade-offs. "Make this PDF smaller" has no single correct answer, because a PDF's size comes from different places: embedded fonts, high-resolution images, redundant objects, streams stored uncompressed. There are three broad levers, from safest to most destructive.
Lossless: repack what is there
pdf-lib can pack many small objects into compressed object streams when it saves. It does this by default; the option is spelled out here for clarity:
const smaller = await doc.save({ useObjectStreams: true });
A thorough lossless pass also deflates any streams the file stores uncompressed. None of this changes a pixel or a character. It can shrink a bloated file noticeably, but it does little for a PDF whose bulk is a few large photos, which is the common case for brochures and scanned documents.
Resample the pictures
The middle option goes after the images directly. Find each image XObject, decode it, scale it down to a target resolution (150 dpi is plenty for an office printer), re-encode it as JPEG, and swap the new stream in for the old one. Text, fonts and vector drawings are untouched, so the document stays searchable; only the photos lose detail. pdf-lib has no single call for this, so it means working with its lower-level object API, but for a report or brochure where pictures make up most of the file, it gives the best result for the least damage.
Rasterize the pages
The bluntest option renders each page to a canvas with PDF.js, encodes the canvas as a JPEG at reduced quality, and builds a fresh PDF in which each page is a single image, using pdf-lib's embedJpg:
// page: a PDF.js page from the source; out: a new pdf-lib PDFDocument
const viewport = page.getViewport({ scale: 150 / 72 }); // 150 dpi
const canvas = document.createElement('canvas');
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
await page.render({ canvas, viewport }).promise;
const jpeg = await new Promise<Blob>((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/jpeg', 0.7),
);
const image = await out.embedJpg(await jpeg.arrayBuffer());
// Keep the original paper size; only the number of pixels changes
const { width, height } = page.getViewport({ scale: 1 });
const newPage = out.addPage([width, height]);
newPage.drawImage(image, { x: 0, y: 0, width, height });
This is lossy, and irreversibly so. The moment you render to a canvas, you have flattened everything into pixels:
| Property | Before (vector PDF) | After rasterize + JPEG |
|---|---|---|
| Selectable / searchable text | Yes | No (it is now an image) |
| Sharpness when zoomed | Resolution-independent | Fixed at the render resolution |
| File size on text-heavy pages | Smaller | Often larger |
| File size on photo-heavy pages | Larger | Smaller |
| Reversible | n/a | No |
That table is why compression deserves caution. Rasterizing a crisp text document to JPEG usually makes the file bigger and destroys text search, while rasterizing a high-resolution scanned brochure can shrink it dramatically. The technique is right for one input and wrong for the other, and it is fundamentally different from merge or split. Merge and split move real objects, so they preserve everything; compress-by-rasterize manufactures new pixel-based objects and discards the originals.
Rasterizing also needs a canvas. In the browser that comes built in; in Node, PDF.js needs a canvas package installed before it can render anything. pdf-lib's page-model operations have no such dependency and run anywhere JavaScript does.
Choosing between them
| Task | Library | Lossless? |
|---|---|---|
| Merge, split, extract, reorder, remove pages | pdf-lib (copyPages) | Yes |
| Rotate pages | pdf-lib (setRotation) | Yes |
| Watermark, headers/footers, crop | pdf-lib (drawText, setCropBox) | Yes (adds content) |
| Re-save smaller without quality loss | pdf-lib (useObjectStreams) | Yes |
| Read page sizes and document metadata | PDF.js (getViewport, getMetadata) | Read-only |
| Extract text | PDF.js (getTextContent) | Read-only, heuristic |
| Render page to image / PDF-to-image | PDF.js (render) | Lossy (rasterizes) |
| Pull out embedded images | PDF.js (operator list + page.objs) | Read-only |
| Shrink a photo-heavy PDF, keep the text | pdf-lib low-level objects + image re-encoding | Lossy for images only |
| Shrink a scanned PDF | PDF.js render + pdf-lib embedJpg | Lossy |
A simple rule keeps you out of trouble. If the task restructures or annotates the document while keeping its content as content, it belongs to pdf-lib and it can be lossless. If the task needs to interpret content (read text, draw pixels, see what a page looks like), it belongs to PDF.js. The operations that need both are the ones that deliberately convert content into pixels, and those are exactly the operations where you should expect to lose something. (Booklet imposition shows how far the object model can go: pdf-lib's embedPdf and drawPage can place two real source pages side by side on each sheet, scaled and positioned like images but still made of text and vectors, so nothing is rasterized.)
Try it in the browser
Loopaloo's PDF tools run entirely in your browser, with no upload. The PDF Merger and PDF Splitter work at the page-object level, so text, fonts and vector graphics come through untouched. The PDF Compressor offers all three levers described above as separate modes (Lossless, Resample pictures and Rasterise pages), and before you rasterize, it tells you how many pages carry real text that would be turned into pictures. If your PDF is mostly searchable text, start with Lossless; if it is a heavy scan, rasterizing is where the savings are.
Related Tools
PDF Merger
Combine PDFs into one document in the order you choose. Bookmarks and links are kept, with an optional bookmark for each file.
PDF Splitter
Split a PDF into one file per page, equal batches, ranges you type, or a single file of picked pages.
PDF Compressor
Make a PDF smaller: lossless compression, smaller photos with sharp text, or flattened pages for scans. Shows the size before and after.