Merging PDFs in the browser: what actually happens, and where it breaks

2026-12-06来源 dev.toEnglish

Every "free PDF merge" site asks you to upload the file. That is a strange design for documents people would rather not hand to a stranger — contracts, payslips, medical records, client drawings.

The browser can do this work itself. I built a set of 82 PDF tools that never upload anything, and this post is about the parts that were hard, plus the limits I hit. No framework talk; just the pipeline.

The pipeline

  1. The user drops files on a <input type="file"> or a drop zone.
  2. Each file is read with file.arrayBuffer().
  3. pdf-lib loads the bytes, copies pages between documents, writes a new Uint8Array.
  4. A Blob URL is created and handed to an <a download>.

There is no fetch in that list. You can open the network panel and watch it stay empty while a 40 MB merge runs.

import { PDFDocument } from 'pdf-lib'; async function merge(files) { const output = await PDFDocument.create(); for (const file of files) { const source = await PDFDocument.load(await file.arrayBuffer(), { ignoreEncryption: false, }); const pages = await output.copyPages(source, source.getPageIndices()); for (const page of pages) output.addPage(page); } return output.save(); } 

That is the whole merge. The interesting parts are the edges.

Where it breaks

Memory is the ceiling. A browser tab gets a few hundred megabytes before it starts swapping or dies. Decoding a 200 MB PDF into objects costs several times the file size, so the real limit is far below the disk limit. Keep the file count and total bytes bounded: 30 files, 1 GB total, 2,000 pages is what I allow, and the UI refuses earlier rather than crashing later.

Encrypted files are not a detail. PDFDocument.load throws on encrypted documents unless you pass the password. If you silently ignore encryption, you produce a broken output or an empty page; if you prompt for a password, you need a path for wrong passwords. Either way, decide before shipping.

Some PDFs are broken in ways readers forgive and libraries do not. Offsets that point past the end of the file, duplicated objects, xref streams with wrong widths. pdf-lib is strict. For files above a threshold (150 MB in my case) I fall back to qpdf compiled to WebAssembly, which repairs what it can before parsing.

Fonts decide whether the output opens. pdf-lib copies embedded fonts, but a page that relies on a non-embedded font will render differently in the merged file. That is not a bug in your merge; it is a bug in the source PDF that only shows up when the document leaves its original viewer.

Text extraction is a different problem

Merging copies pages. Extraction has to interpret the content stream, and that is where pdfjs-dist earns its place:

const pdf = await pdfjsLib.getDocument({ data: bytes }).promise; const page = await pdf.getPage(1); const content = await page.getTextContent(); 

Two things bite:

  • Right-to-left and CJK text. PDF stores glyph IDs, not characters, and the mapping back to Unicode lives in the font's ToUnicode CMap. When a producer omits it, extraction returns mojibake or nothing. Arabic and Japanese files from older scanners are the usual victims.
  • Layout. getTextContent() gives items with positions, not lines and paragraphs. Rebuilding reading order is your job, and "just sort by y then x" fails on columns, tables and footnotes.

OCR, when there is no text at all

A scanned PDF is an image per page. tesseract.js runs the recognizer in a Web Worker, and the main thread stays responsive. It is slow — seconds per page, not milliseconds — so progress reporting is not cosmetic. The output is text you can put back into an editable document; in my case the tool exports a Word file rather than a searchable PDF.

The small piece worth extracting

Page selection looks trivial until you ship it. Users type 1,3,5, 2-4, 8-, -3, or paste all. Reversed ranges (5-2) show up, and so do stray commas.

I pulled that logic into a tiny package with no dependencies, because every PDF tool needs it and nobody needs a second implementation:

import { parsePageRanges, pageIndicesToRange } from 'pdf-page-ranges'; parsePageRanges('1,3,5-7', 10); // [0, 2, 4, 5, 6] pageIndicesToRange([0, 1, 2, 4]); // '1-3,5' 

It returns zero-based indices, sorted and de-duplicated, and throws a PageRangeError with a stable code so the UI can translate the message without matching English text.

What I would tell someone starting today

  1. Bound the input before you parse: file count, total bytes, page count. A friendly error beats a crashed tab.
  2. Decide what "encrypted" means up front.
  3. Keep a repair path (qpdf) for the PDFs that every desktop viewer silently fixes.
  4. Treat extraction as a separate project from manipulation.
  5. Test with real documents from the wild, not with files your own tool produced.

The privacy claim is the easy part: if the file never leaves the tab, you can say so plainly and let people verify it in the network panel. The engineering is in everything else.

原文:https://www.a8q9.cn/en/article/merging-pdfs-in-the-browser-what-actually-happens-and-where-it-breaks-9aaae7.html

相关文章