Skip to content

PDF Merge — JavaScript source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// pdf-merge — merge many PDFs into one with pdf-lib (npm), the plain-JS
// twin of src/lib/pdf-merge.ts. Same contract: empty input rejected,
// encrypted vs invalid classified from the raw load-error message, page
// count returned for UI display.
import { PDFDocument } from 'pdf-lib';

/** Load failure kind: 'encrypted' (password-protected) or 'invalid' (unparseable). */
export class PdfToolError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
  }
}

/** Pure classifier — encrypted vs invalid, from the raw error message. */
export function classifyLoadError(msg) {
  return msg && /encrypt|password/i.test(msg) ? 'encrypted' : 'invalid';
}

/** Map a thrown load/parse error to a user-facing PdfToolError. */
function mapError(e) {
  const msg = e instanceof Error ? e.message : String(e);
  const kind = classifyLoadError(msg);
  throw new PdfToolError(
    kind,
    kind === 'encrypted'
      ? 'This PDF is password-protected. Unlock it first.'
      : 'Not a readable PDF file.',
  );
}

/** Copy every page of every input, in order, into one fresh PDFDocument. */
export async function mergePdfs(docs) {
  if (docs.length === 0) throw new PdfToolError('invalid', 'Nothing to merge.');
  try {
    const out = await PDFDocument.create();
    for (const bytes of docs) {
      const src = await PDFDocument.load(bytes, { ignoreEncryption: false });
      const pages = await out.copyPages(src, src.getPageIndices());
      pages.forEach((p) => out.addPage(p));
    }
    const saved = await out.save({ useObjectStreams: true });
    return { bytes: saved, pageCount: out.getPageCount() };
  } catch (e) {
    mapError(e);
  }
}

/** Page count for UI display — the tool's only other pdf-lib need. */
export async function countPages(bytes) {
  try {
    const doc = await PDFDocument.load(bytes, { ignoreEncryption: false });
    return doc.getPageCount();
  } catch (e) {
    mapError(e);
  }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →