PDF Merge — TypeScript source
Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-merge — the exemplar lib of the PDF trio (FEAT-035). Statically imports
// pdf-lib: only the islands' dynamic import keeps it out of the eager
// ToolRouter chunk (BUG-007 pattern; the perf budget's jsBytes line depends
// on it). Error types live in pdf-errors.ts (pdf-lib-free) so islands never
// need a static path into this module.
import { PDFDocument } from 'pdf-lib';
import { mapError, PdfToolError } from './pdf-errors';
export { PdfToolError, classifyLoadError, mapError } from './pdf-errors';
export type MergeResult = { bytes: Uint8Array; pageCount: number };
export async function mergePdfs(docs: Uint8Array[]): Promise<MergeResult> {
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 island's only other pdf-lib need. */
export async function countPages(bytes: Uint8Array): Promise<number> {
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 →