Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Your PDF merger doesn't need a server. Here are 15 lines that prove it

Try this the next time you merge two PDFs online. Open DevTools, switch to the Network tab, and drop your files onto the site. On most of them you'll watch your contract, bank statement or medical report upload to a ser

Try this the next time you merge two PDFs online.

Open DevTools, switch to the Network tab, and drop your files onto the site. On most of them you'll watch your contract, bank statement or medical report upload to a server you know nothing about. The site merges it there and sends it back.

For combining two files, that round trip isn't needed. The browser you're already using can do the entire job on your own device, in about 15 lines of JavaScript.

Here's the proof, and it's running live:
πŸ‘‰ Merge PDFs in your browser, with no upload

Open the Network tab on that page too. Nothing leaves your machine. By the end of this post you'll have built the same thing yourself.

1. One script tag, no build step

All the heavy lifting is done by pdf-lib, a pure-JavaScript PDF library. Pin the version so a future release can't break your page:

<script src="https://unpkg.com/[email protected]/dist/pdf-lib.min.js"></script>

This exposes a global PDFLib object. In a bundled app you'd npm install pdf-lib and import { PDFDocument } from 'pdf-lib' instead.

The UI is just as small:

<input id="files" type="file" accept="application/pdf" multiple>
<button id="merge">Merge and download</button>
<p id="status"></p>

The multiple attribute is what lets the user pick several PDFs at once.

That's the whole setup. Next comes the part that does the merging.

2. The merge: 15 lines

const { PDFDocument } = PDFLib;

async function mergePdfs(files) {
  const merged = await PDFDocument.create();

  for (const file of files) {
    // Read locally: File -> ArrayBuffer. No network request.
    const bytes = await file.arrayBuffer();
    const source = await PDFDocument.load(bytes);

    const pages = await merged.copyPages(source, source.getPageIndices());
    pages.forEach((page) => merged.addPage(page));
  }

  return merged.save(); // Uint8Array
}

Read each file, load it, copy its pages into a new document, save. That's all there is to it.

But there's one line here that almost everyone gets wrong the first time.

The copyPages trap

A natural first attempt looks like this:

// ❌ Throws: the page belongs to a different document
source.getPages().forEach((page) => merged.addPage(page));

It fails because a PDF page isn't a standalone object. It points to fonts, images and other resources that live inside its own document. copyPages must be called on the target document. It deep-copies each page together with everything the page depends on, and only then can the copies be added.

Once you get past that, the last step is handing the file back to the user.

3. Download without a server

function download(bytes, name) {
  const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
  const a = document.createElement('a');
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 10000);
}

document.getElementById('merge').addEventListener('click', async () => {
  const input = document.getElementById('files');
  const status = document.getElementById('status');
  try {
    status.textContent = 'Merging…';
    download(await mergePdfs(input.files), 'merged.pdf');
    status.textContent = 'Done.';
  } catch (err) {
    status.textContent = `Could not merge: ${err.message}`;
  }
});

A Blob URL points to bytes that already sit in the browser's memory, so the "download" never touches the network. Revoking it afterwards frees that memory, and the short delay gives the browser time to start saving first.

And that's it: a working, private PDF merger. Before you ship it to real users, though, there are four things that will bite you.

4. Four gotchas that show up with real users

πŸ”’ Password-protected PDFs throw.
PDFDocument.load rejects encrypted files with an EncryptedPDFError. You can pass { ignoreEncryption: true }, but pdf-lib can't decrypt, so the output is often blank or broken. Catch the error and tell the user plainly.

πŸ“± Phones run out of memory.
Every source file and the output all sit in RAM at the same time. A few hundred MB is fine on a laptop. A pile of phone-camera scans can crash a mobile tab. For big jobs, move mergePdfs into a Web Worker so the page stays responsive.

πŸ“ Form fields can clash.
If two PDFs both contain a field called name, the merged copies can conflict. If the forms don't need to stay editable, call source.getForm().flatten() before copying.

πŸ”€ File order is unpredictable.
input.files follows whatever order the OS file dialog returns, and that differs between systems. Real apps show a list the user can drag to reorder.

The takeaway

Here's what this tiny demo shows: for a whole category of file tools, the server is optional. Merging, splitting, rotating, reordering pages, compressing images and trimming audio can all run on the user's device with the File API, a library and a Blob.

It's faster because there's no upload, cheaper because you have no server bill, and private by default, since you can't leak a file you never received.

πŸ“¦ Full code (about 100 lines, MIT licence): github.com/Gulzar3861/quickfiletools
πŸ› οΈ The production version, with page previews, drag-to-reorder and password handling, runs on QuickFileTools Merge PDFs.

Your turn: try the Network-tab test on whatever PDF site you use now. Did your files get uploaded? Tell me in the comments πŸ‘‡

Next up: compressing images in the browser with nothing but Canvas, and the quality setting that cuts most photos by more than half. Follow so you don't miss it.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.