RecipesPDF
Complete, type-checked examples for common jobs with Birch UI PDF: a review workflow, redact and sign, fill and flatten, merge and Bates-number, opening attachments and embedded files in the PDF, spreadsheet and document components, and headless processing on a Node server.
Each recipe is a complete piece of code that compiles against the published types. The browser recipes use @birchui/pdf; the server recipes use @birchui/pdf/engine, which contains the document engine without the viewer.
Review workflow#
Two reviewers comment on a contract, the author sees their comments arrive, and the result is exported as a comment summary and as XFDF for the record.
import { createPdfViewer, type PresenceMessage, type SyncOperation } from '@birchui/pdf';
declare const contractBytes: Uint8Array;
declare const room: {
publish(topic: 'operations' | 'presence', data: SyncOperation[] | PresenceMessage): void;
subscribe<T>(topic: 'operations' | 'presence', handler: (data: T) => void): () => void;
};
const viewer = createPdfViewer(document.querySelector<HTMLElement>('#review')!, {
document: contractBytes,
fileName: 'services-agreement-fabrikam-2026.pdf',
currentUser: { name: 'Priya Natarajan', id: 'u-1042' },
toolGroup: 'comment',
sidebar: 'annotations',
annotationSync: {
send: (operations) => room.publish('operations', operations),
onRemote: (receive) => room.subscribe<SyncOperation[]>('operations', receive),
sendPresence: (message) => room.publish('presence', message),
onRemotePresence: (receive) => room.subscribe<PresenceMessage>('presence', receive),
},
});
await viewer.ready;
const note = viewer.addTextMarkup('highlight', 2, [[72, 512, 380, 526]], {
contents: 'Liability cap: confirm with legal',
});
viewer.addReply(note.id, { contents: 'Legal confirms 12 months of fees.' });
viewer.updateAnnotation(note.id, { status: 'accepted' });
const summaryPdf = viewer.exportCommentSummary({ format: 'pdf' });
const exchange = viewer.exportXfdf();
const { bytes: reviewed } = await viewer.save();A reviewer changes only their own comments unless currentUser.isAdmin is set or you pass canEdit. See Authors and permissions and Real-time sync.
Redact and sign#
Remove personal data from a scanned statement, then sign the result with a key store so nobody can change it unnoticed.
import { loadPdfDocument, signPdf, verifyPdfSignatures } from '@birchui/pdf/engine';
declare const statementBytes: Uint8Array;
declare const keyStoreBytes: Uint8Array;
const pdf = await loadPdfDocument(statementBytes);
pdf.markRedactions({ preset: 'iban' }, { overlayText: 'REDACTED' });
pdf.markRedactions({ text: 'Marta Kowalczyk', matchCase: true });
pdf.addAnnotation({ type: 'redaction', pageIndex: 0, rect: [72, 640, 300, 700] });
pdf.applyRedactions();
const { bytes: redacted } = await pdf.save({ mode: 'full' });
const signed = await signPdf(redacted, {
pkcs12: keyStoreBytes,
pkcs12Password: 'correct horse battery',
reason: 'Released after redaction',
certify: 'no-changes',
});
const [check] = await verifyPdfSignatures(signed);
if (!check.isValid) throw new Error('The signature did not verify');Save with mode: 'full' after applying redactions, so the removed content is not left in an earlier revision of the file. Images in JPEG 2000, JBIG2 or CCITT format need a decodeImage callback outside the viewer; see Redaction.
Fill and flatten#
Fill an order form from your own data, check it, and flatten it so the values become ordinary page content.
import { openPdfDocument } from '@birchui/pdf/engine';
declare const orderFormBytes: Uint8Array;
const pdf = openPdfDocument(orderFormBytes, { author: 'Order desk' });
pdf.setFormValues({
'customer.name': 'Fabrikam Logistics GmbH',
'customer.vatId': 'DE811907980',
'item.1.quantity': '20',
'item.1.unitPrice': '74.95',
});
const problems = pdf.validateForm();
if (problems.length > 0) {
throw new Error(problems.map((problem) => `${problem.name}: ${problem.code}`).join('\n'));
}
pdf.flatten('forms');
const { bytes: flattened } = await pdf.save({ mode: 'full' });Calculated fields such as an order total are recalculated by setFormValues when their scripts are in the supported set; pdf.describeFieldScripts(name) tells you whether a script runs. See Forms.
Merge and Bates-number#
Combine exhibits into one production set, number every page, and add a matching bookmark for each exhibit.
import { openPdfDocument, type OutlineItem } from '@birchui/pdf/engine';
declare const exhibits: { title: string; bytes: Uint8Array }[];
const [first, ...others] = exhibits;
const pdf = openPdfDocument(first.bytes);
const outline: OutlineItem[] = [{ title: first.title, pageIndex: 0, children: [] }];
for (const exhibit of others) {
const firstPage = pdf.pageCount;
pdf.mergeDocument(exhibit.bytes);
outline.push({ title: exhibit.title, pageIndex: firstPage, children: [] });
}
pdf.setOutline(outline);
pdf.addBatesNumbers({ prefix: 'FAB-', digits: 6, start: 1 });
pdf.setMetadata({ title: 'Fabrikam v. Northwind: production set 3' });
const { bytes: production } = await pdf.save();A merge changes the page tree, so the save is a full rewrite and signatures in the source files do not survive. See Page tools and Document tools.
Combine, reorder and number a set of PDFs#
A month-end pack arrives as separate files: a cover letter, the statements and scanned receipts. Put them into one document in a fixed order, move the summary to the front, drop the blank backs of the scans and number every page.
In the viewer: open the cover letter, choose Pages, then Merge files…. Add the other files, drag the rows into order, tick Add a bookmark for each file and choose Merge. Select the summary page in the thumbnails panel, choose Move to… and type 2. Choose More, Delete blank pages, then Page numbers…, pick Page 1 of N and Add numbers. Download the result.
The same without a viewer:
import { mergePdfs, openPdfDocument } from '@birchui/pdf/engine';
declare const pack: { name: string; bytes: Uint8Array }[];
declare const summaryPageIndex: number;
const combined = await mergePdfs(
pack.map((file) => ({ data: file.bytes, name: file.name })),
{ bookmarkPerFile: true, keepFormFields: false },
);
const pdf = openPdfDocument(combined);
pdf.movePages([summaryPageIndex], 1);
const blank = pdf.deleteBlankPages();
const numbered = pdf.addPageNumbers({ format: 'Page {page} of {pages}', position: 'bottom-right', fontSize: 9 });
console.info(`${blank.length} blank pages removed, ${numbered} pages numbered`);
const { bytes: monthEndPack } = await pdf.save();mergePdfs takes PDF and image files alike and names each bookmark after its file. movePages counts target in the order before the move, and bookmarks, links, annotations and form fields follow their pages. removePageNumbers() takes the numbers off again, also after the file was saved, so the pack can be renumbered when a file is added later. See Page tools.
Open files from other components#
A PDF can carry a workbook as an attachment, a workbook can carry a PDF or an Outlook message as an embedded file, and a Word document can carry either. Each component hands such a file to your application through an event instead of opening it itself: attachmentOpen on the PDF viewer, and embeddedObjectOpen on Birch UI Spreadsheet and Birch UI Document. The packages do not import one another; this page of host code is what connects them.
The router below sends every opened file to the component that understands it: PDFs and email messages to a new viewer tab (the viewer converts .msg and .eml on the way in), workbooks to the spreadsheet, Word documents to the editor. Anything else is offered as a download.
import { createPdfViewer } from '@birchui/pdf';
import { createSpreadsheet } from '@birchui/spreadsheet';
interface OpenedFile {
fileName: string;
mimeType: string;
data: Uint8Array;
}
interface WordEditor {
importDocx(input: Uint8Array): Promise<void>;
on(event: 'embeddedObjectOpen', listener: (file: OpenedFile) => void): () => void;
}
declare const editor: WordEditor;
declare function showPanel(name: 'pdf' | 'sheet' | 'document'): void;
const viewer = createPdfViewer(document.querySelector<HTMLElement>('#pdf')!, {});
const sheet = createSpreadsheet(document.querySelector<HTMLElement>('#sheet')!);
function download(file: OpenedFile): void {
const url = URL.createObjectURL(new Blob([file.data as BlobPart], { type: file.mimeType }));
const link = Object.assign(document.createElement('a'), { href: url, download: file.fileName });
link.click();
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
async function openFile(file: OpenedFile): Promise<void> {
const extension = file.fileName.slice(file.fileName.lastIndexOf('.') + 1).toLowerCase();
if (extension === 'pdf' || extension === 'msg' || extension === 'eml') {
await viewer.openTab(file.data, { fileName: file.fileName });
showPanel('pdf');
} else if (extension === 'xlsx' || extension === 'xlsm') {
await sheet.importXlsx(file.data);
showPanel('sheet');
} else if (extension === 'csv') {
sheet.importCsv(file.data);
showPanel('sheet');
} else if (extension === 'docx') {
await editor.importDocx(file.data);
showPanel('document');
} else {
download(file);
}
}
const report = (error: unknown) => console.error('Could not open the file', error);
const stop = [
viewer.on('attachmentOpen', ({ name, mimeType, data }) => {
openFile({ fileName: name, mimeType, data }).catch(report);
}),
sheet.on('embeddedObjectOpen', (file) => {
openFile(file).catch(report);
}),
editor.on('embeddedObjectOpen', (file) => {
openFile(file).catch(report);
}),
];
export function disconnect(): void {
for (const off of stop) off();
}The events carry copies of the bytes, so the file that was opened is not changed by what the other component does with it. Loading a workbook or a document replaces what that component held; keep the previous content with toJSON() first if the user may want to go back.
The same bytes move the other way with two calls. This attaches the open workbook to the open PDF as its source data, and embeds the PDF in the workbook next to the active cell:
import type { PdfViewerApi } from '@birchui/pdf';
import type { SpreadsheetApi } from '@birchui/spreadsheet';
export async function linkBoth(viewer: PdfViewerApi, sheet: SpreadsheetApi): Promise<void> {
await viewer.addAttachment({
name: 'Budget FY27.xlsx',
data: await sheet.exportXlsx(),
description: 'The workbook this report was printed from',
relationship: 'Source',
});
const { bytes } = await viewer.save();
sheet.insertEmbeddedObject({ data: bytes, fileName: 'Budget FY27 report.pdf' });
}An Outlook message found in a workbook can also be archived as a PDF without showing it, with parseMsg() and mailToPdf() from @birchui/pdf/engine:
import { mailToPdf, parseMsg } from '@birchui/pdf/engine';
import type { SpreadsheetApi } from '@birchui/spreadsheet';
export async function archiveMessages(sheet: SpreadsheetApi): Promise<Map<string, Uint8Array>> {
const archived = new Map<string, Uint8Array>();
for (const item of sheet.getEmbeddedObjects()) {
if (!item.fileName.toLowerCase().endsWith('.msg')) continue;
const bytes = sheet.getEmbeddedObjectData(item.id);
if (!bytes) continue;
const { bytes: pdf } = await mailToPdf(parseMsg(bytes));
archived.set(item.fileName.replace(/\.msg$/i, '.pdf'), pdf);
}
return archived;
}Server-side headless in Node#
The engine entry has no DOM code, so it runs in Node 20 or later, in workers and in edge runtimes. This handler stamps an invoice as approved, protects it and returns the bytes.
import { readFile, writeFile } from 'node:fs/promises';
import { loadPdfDocument, PdfPasswordError } from '@birchui/pdf/engine';
export async function approveInvoice(path: string, approver: string): Promise<Uint8Array> {
const source = await readFile(path);
const pdf = await loadPdfDocument(source, { author: approver }).catch((error: unknown) => {
if (error instanceof PdfPasswordError) throw new Error(`${path} is password-protected`);
throw error;
});
pdf.addAnnotation({ type: 'stamp', pageIndex: 0, rect: [400, 720, 560, 772], stamp: 'Approved' });
pdf.setFormValue('approval.by', approver);
pdf.addHeaderFooter({ footer: { center: `Approved by ${approver} on {date}`, right: 'Page {page} of {pages}' } });
pdf.encrypt({ userPassword: '', ownerPassword: 'ledger-archive-2026', permissions: { modify: false } });
const { bytes } = await pdf.save();
await writeFile(path.replace(/\.pdf$/, '-approved.pdf'), bytes);
return bytes;
}Saving, redacting and comparing large files are CPU work on the calling thread; run them in a worker thread when the server must stay responsive. The package makes no network requests: timestamps and revocation data for signatures come through the callbacks you pass.