SavingPDF
How Birch UI PDF writes incremental updates and full rewrites, what forces a full rewrite, and the compress, flatten and optimize options.
Birch UI PDF has its own PDF parser and writer, and its own renderer for drawing pages in the viewer. Nothing is uploaded: save() gives you bytes and you decide where they go.
const { bytes, mode } = await viewer.save();
await fetch('/api/contracts/4471/file', {
method: 'PUT',
body: new Blob([bytes], { type: 'application/pdf' }),
});
viewer.on('save', ({ mode, fileName }) => console.info(`${fileName} saved (${mode})`));SaveOptions |
Default | Meaning |
|---|---|---|
mode |
'auto' |
'auto' writes an incremental update when possible, 'incremental' insists on one and throws PdfWriteError when it is not possible, 'full' always rewrites |
compress |
true |
Deflate new and rewritten streams larger than 64 bytes |
flatten |
'annotations', 'forms' or 'all'; see Flattening |
The result has the bytes, the mode that was used and, after a full rewrite with applied redactions, one redactions report per redacted page.
viewer.download(fileName?) saves and hands the file to the browser as a download, which is also what the download button and Ctrl+S do. viewer.isModified() tells you whether there is anything to save. When nothing changed, viewer.save() returns the bytes that were opened.
Incremental updates#
An incremental save returns the original bytes unchanged, followed by an update section with the new and changed objects, a cross-reference section and a trailer whose /Prev points at the previous one. If the original file uses a cross-reference stream, the update uses one too.
- Each annotation gets a proper entry in its page's
/Annotsarray and an/APappearance stream, so Acrobat, Preview, Chrome and other viewers all draw it the same way. - Text, choice, checkbox and radio fields get new
/V,/ASand appearance streams./Vkeeps the raw value; the appearance stream shows the formatted one, so other viewers draw the same text as the screen. When a form is written, fields that came without an appearance get one too and/NeedAppearancesis removed, because it would make viewers redraw every field from its raw value. It stays set only when a value has characters that neither the built-in fonts nor the supplied fonts can draw. A signed document keeps its flag and its untouched fields as they are. - A password-protected file stays protected: the update is encrypted with the key of the file.
Because the original bytes stay intact, an existing digital signature still verifies after an incremental save. Whether the signature also permits the change is a separate question; see Changes after signing.
What a save rewrites in a form#
A save writes the fields whose value, options or properties changed, and the fields a calculation changed. When a field was edited, the viewer also gives an appearance to fields of the same form that had none, so every reader shows formatted values without NeedAppearances. A save after a change that is not a form change (a page content edit, an annotation, a bookmark) leaves every other field exactly as the file has it: appearance streams are not regenerated, missing appearances stay missing and NeedAppearances keeps its value.
In a signed document a page content edit is saved as an incremental update, so the bytes the signature covers do not change and the signature still verifies; a verifier reports that the document was changed after signing. Edits that need a full rewrite (page changes, merging, applied redactions) invalidate signatures, and the viewer asks before each of them.
Full rewrites#
These changes cannot be appended and produce a new file that holds only the objects still in use:
| Change | Why |
|---|---|
| Moving, deleting or inserting pages, merging another document | The page tree is rebuilt, and deleted pages must not stay in the file |
| Applied redactions | The removed content must not survive in an earlier revision |
| Adding, changing or removing password protection | Every string and stream is re-encrypted |
| A damaged file whose cross-reference table had to be rebuilt on opening | There is no reliable structure to append to |
mode: 'full', and Rewrite the whole file in the optimize dialog |
You asked for it |
Everything else is appended: annotations, form values and new fields, page rotation, crop boxes, watermarks, headers and footers, Bates numbers, bookmarks, metadata, attachments, page labels, content edits and flattening.
Bookmarks, named destinations, links, metadata and the structure tree of the original are carried over into a rewritten file.
import { openPdfDocument } from '@birchui/pdf/engine';
const pdf = openPdfDocument(signedContractBytes);
pdf.addAnnotation({ type: 'stamp', pageIndex: 0, rect: [400, 720, 560, 772], stamp: 'Received' });
if (pdf.hasSignatures && !pdf.canSaveIncrementally()) {
throw new Error('This change would break the existing signatures');
}
const { bytes } = await pdf.save({ mode: 'incremental' });Compression#
New streams are compressed with CompressionStream where the platform has it (current browsers, workers and Node 18 or later). Without it they are stored uncompressed, which is valid but larger. compress: false skips compression, which is useful when you want to read the output while debugging.
Flattening#
Flattening draws appearances into the page content and removes the interactive objects.
flatten |
Effect |
|---|---|
'annotations' |
Annotations become page content. Comment popups, replies and hidden annotations are removed; annotations that have nothing to draw, such as links, are kept. |
'forms' |
Field appearances become page content and the fields are removed. Signature fields are kept. |
'all' |
Both |
const { bytes: finalCopy } = await viewer.save({ flatten: 'all', mode: 'full' });save({ flatten }) does not change the open document: you can keep editing and save again without flattening. Flatten annotations and Flatten form in the menu, viewer.flatten(mode) and the headless pdf.flatten(mode) are different: they flatten the open document itself. The menu commands ask for confirmation first. The step can be undone, which brings the annotations and fields back; once the flattened document is saved and reopened it cannot.
Flattened text is still selectable text in most cases, because annotation and field appearances are drawn with fonts, not as images.
Optimizing#
optimizePdf rewrites a file as compactly as it can:
import { optimizePdf } from '@birchui/pdf/engine';
const { bytes, report } = await optimizePdf(exportedReportBytes);
console.info(`${report.before} → ${report.after} bytes, ${report.duplicatesMerged} duplicate streams merged`);OptimizeOptions |
Default | Effect |
|---|---|---|
objectStreams |
true |
Pack objects into compressed object streams behind a cross-reference stream |
dedupe |
true |
Merge streams with identical content, such as a logo embedded on every page |
removeUnused |
true |
Drop objects nothing refers to, including earlier revisions |
recompress |
true |
Compress streams that are stored uncompressed |
images |
none | { maxDpi, jpegQuality? }: downsample images that are drawn at more than maxDpi |
fonts |
false |
Subset embedded fonts to the glyphs the document uses |
import { optimizePdf } from '@birchui/pdf/engine';
declare const scannedContractBytes: Uint8Array;
const { bytes: smaller, report: images } = await optimizePdf(scannedContractBytes, {
images: { maxDpi: 150, jpegQuality: 75 },
});
console.info(smaller.length, images.imagesDownsampled, images.imagesKept);With images, every image the package can decode is measured at the size it is drawn on the page. One that exceeds maxDpi by more than a fifth is averaged down to maxDpi; a JPEG is written as a JPEG again with jpegQuality (75 by default), anything else as lossless RGB or grey. Images with a mask or soft mask, stencil masks, JPEG 2000, JBIG2 and CCITT data, and images in Lab, Separation or DeviceN colour are left as they are and counted in imagesKept. Colour profiles of resampled images are not carried over. optimizePdf throws PdfWriteError for an encrypted file (decrypt it first) and for a file with digital signatures (the rewrite would invalidate them).
Subsetting fonts#
import { optimizePdf } from '@birchui/pdf/engine';
declare const brochureBytes: Uint8Array;
const { bytes: lighter, report: fonts } = await optimizePdf(brochureBytes, { fonts: true });
console.info(fonts.fontsSubset, fonts.fontsKept, fonts.fontBytesBefore, fonts.fontBytesAfter, lighter.length);With fonts: true the content of every page, form XObject, tiling pattern, Type 3 glyph and annotation appearance is read to find the character codes each font is used with, and embedded font programs are cut down to those glyphs:
- TrueType programs (
FontFile2) of composite fonts with anIdentity-HorIdentity-Vencoding, and of simple fonts that are symbolic or useWinAnsiEncodingwithout differences. Glyph numbers stay as they are, so widths and character maps keep working; the outlines of unused glyphs are emptied and layout-only tables (GSUB,GPOS,kernand similar) are dropped. - CFF programs (
FontFile3with theCIDFontType0Csubtype) of composite fonts. The character ids of a CID-keyed font are kept. - Left alone and counted in
fontsKept: Type 1 programs, simple fonts with a CFF program, fonts with an encoding the package does not map, fonts whose subset would not be smaller, and every font named in the form's default resources (/DR), because a form field can still draw new text with it. If any content stream cannot be read, no font is touched.
A font that was subset gets the usual six-letter tag in front of its name. The tests render a document before and after with poppler and require identical pixels and identical extracted text.
Optimize and save in the viewer menu saves the open document with the chosen options and downloads it.
Fast web view#
save({ linearize: true }) and linearizePdf(bytes) write a linearised file: the first page and everything it needs come first, followed by a hint stream that tells a reader where every other page starts, so a viewer that loads over HTTP range requests can show page one before the rest has arrived.
import { linearizePdf, openPdfDocument } from '@birchui/pdf/engine';
declare const catalogueBytes: Uint8Array;
const forTheWeb = await linearizePdf(catalogueBytes);
const { bytes: saved } = await openPdfDocument(catalogueBytes).save({ linearize: true });
console.info(forTheWeb.length, saved.length);The output has the linearisation dictionary, a first-page cross-reference section, page offset, shared object and outline hint tables, and inherited page attributes moved onto the pages. It is checked with qpdf --check-linearization for one-page and 300-page documents, forms, bookmarks and files written by LibreOffice. A linearised file is always a full rewrite with a classic cross-reference table and no object streams, so it is larger than the default output; it cannot be combined with mode: 'incremental', and encrypted or signed input is refused. An incremental save made later appends to the file, after which it is no longer linearised.
Layout of a full rewrite#
A full rewrite packs objects into compressed object streams behind a cross-reference stream (PDF 1.5), which is what makes the file small. Pass objectStreams: false to save() for a classic cross-reference table that PDF 1.4 readers understand; compress: false and password-protected output use the classic table too. An incremental save always appends in the style of the file it extends.
On a 2,000-page text document (0.73 MB) on a loaded development machine, a full rewrite took 4 to 25 seconds before this layout and now takes 0.1 to 0.4 seconds and writes 0.43 MB; an incremental save of one added note takes 2 to 20 ms and adds 1.1 KB. In Node the compression uses the built-in zlib; in browsers it uses CompressionStream. An object that was not changed and refers to no other object, which is the case for most content, image and font streams, is copied byte for byte from the source file, including its original dictionary; objects that hold references are written again because their numbers change. Nothing is copied from or into an encrypted file, and a stream whose declared length is wrong is rewritten with the right one.
Errors#
| Error | When |
|---|---|
PdfWriteError |
mode: 'incremental' is not possible, or a tool refuses the file |
PdfPasswordError |
The document is still locked; see Encryption and passwords |
PdfSyntaxError |
The bytes are not a PDF, or are damaged beyond repair |