@nextgensoftwares/folio-export-pdf
PDF export drawn from Folio layout: exact pages, HarfBuzz-shaped glyphs, embedded subset fonts. Guide: Exporters.
in progressexportPdf
function exportPdf(layout: DocumentLayout, opts: PdfExportOptions): Promise<Uint8Array>;
interface PdfExportOptions {
fonts: (font: FontSpec) => MaybePromise<FontBytes | null | undefined>; // bytes of one face (single family name)
shaper?: FontEngine; // the engine the layout was measured with (recommended)
fallback?: string[]; // when building an engine (default ['Noto Sans Arabic'])
images?: (src: string) => MaybePromise<PdfImageData | null | undefined>; // default: data: URLs (png/jpeg)
rasterizeSvg?: (svg: string, width: number, height: number) => MaybePromise<Uint8Array | null | undefined>;
math?: (latex: string, display: boolean, size: number, column?: number) => MaybePromise<PdfMathResult | null | undefined>; // column: a numbered equation (\tag), typeset as a block that wide
painters?: Record<string, PdfPainter>; // custom fragments, inline atoms and media:<type>, by key
resolveSrc?: (src: string) => string | Promise<string>; // stored srcs (e.g. idb:…) → fetchable URLs, sync or async
mediaLink?: (attrs: Attrs, kind: PdfMediaKind) => MaybePromise<string | null | undefined>; // a media card's printed link (below)
mediaQr?: boolean; // QR codes on media cards (default false)
onProgress?: (done: number, total: number) => void; // (0, total) before fonts load, then after each page
yieldEvery?: number; // default 25 pages
title?: string;
author?: string;
creator?: string; // the PDF's Creator (default "Folio"; the Producer always names Folio)
credit?: boolean | { href?: string; label?: string }; // deprecated, ignored: exported files carry no credit
lang?: string; // catalog /Lang (BCP 47); an Arabic one gives media cards in Arabic
document?: FolioDocument; // headings → bookmarks + named destinations (h<index>, heading id); `#name` links jump there
outline?: boolean; // write bookmarks when `document` is given (default true)
colors?: { text?; code?; link?; marker?; codeMark?; highlight? };
onWarning?: (warnings: string[]) => void;
signal?: { aborted: boolean };
}
type FontBytes = Uint8Array | ArrayBuffer;
interface PdfImageData { data: Uint8Array | ArrayBuffer; type: 'png' | 'jpeg' | 'jpg' | 'svg' | (string & {}) }
interface PdfMathResult { vector?: PdfMathDrawing; png?: Uint8Array; jpeg?: Uint8Array; svg?: string } // vector preferred
interface PdfMathDrawing { width: number; height: number; depth: number; items: PdfMathItem[]; fonts: Record<string, Uint8Array> }
type PdfMathItem = // px, relative to the equation's left edge and baseline (y down)
| { kind: 'glyphs'; font: string; size: number; color?: string; y: number; chars: { c: string; x: number }[] }
| { kind: 'rect'; x: number; y: number; width: number; height: number; color?: string }
| { kind: 'path'; d: string; m: [number, number, number, number, number, number]; fill?: string; stroke?: string; strokeWidth?: number; clip?: { x; y; width; height } };
interface PrintFallback { image?: string; title: string; detail: string; link?: string; qr?: string | true }
type PdfMediaKind = 'video' | 'audio' | 'file' | 'embed';
type PdfPainter = (
attrs: Attrs,
ctx: PdfPaintContext & { fragment: CustomFragment | MediaFragment },
) => MaybePromise<void | PrintFallback | null | undefined>; // draw, return a card, or null = default
interface PdfPaintContext {
page: PageLayout;
ops(raw: string): void;
rect(r: { x: number; y: number; width: number; height: number; fill?: string; stroke?: string; strokeWidth?: number; radius?: number }): void;
text(text: string, at: { x: number; y: number; font: FontSpec; color?: string; rtl?: boolean }): Promise<void>;
// adjust: picture corrections applied to the decoded pixels (PNG, JPEG) as the CSS filter screens use
image(src: string, box: { x: number; y: number; width: number; height: number }, opts?: { adjust?: PdfImageAdjust }): Promise<void>;
opacity?(alpha: number): void;
softMask?(ops: string, bbox: [number, number, number, number]): void;
// the standard media card for a media object a painter drew (a slide's video over its poster)
mediaCard?(kind: PdfMediaKind, attrs: Attrs, box: { x: number; y: number; width: number; height: number }): Promise<void>;
}opacity(alpha) sets the fill and stroke opacity until the enclosing Q (a shared ExtGState). softMask(ops, bbox) masks what follows until the enclosing Q with a luminosity soft mask: ops paint it in grey levels (the opacity; 0 outside them) in the current space, bounded by bbox ([x0, y0, x1, y1]); each distinct mask is one transparency-group form and ExtGState shared by every page. Drawings use it for soft edges and reflections.
| Type | Description |
|---|---|
PdfExportOptions, FontBytes, PdfImageData, PdfMathResult | options and host-provided data |
PdfPainter, PdfPaintContext | plugin mappings keyed by custom type or media:<type>: draw through ctx (CSS px, page-relative, y down), return a PrintFallback, or null for the default |
PrintFallback | a card for a static medium: optional image, title, detail line, link, QR code (same shape as plugin-media's) |
qrMatrix(text, { ecc? }), QR_MAX_BYTES, QrOptions, QrEcc | a QR code (ISO/IEC 18004, byte mode, UTF-8) as rows of modules (true = dark), without the 4-module quiet zone: the smallest version that fits, level 'M' by default ('L', 'Q', 'H'). DOM-free; throws a RangeError past what a version 40 code holds (2 953 bytes at L, 2 331 at M). Also on its own at @nextgensoftwares/folio-export-pdf/qr (no pdf-lib) |
CARD_QR_HEIGHT | 76 (px): the card height that holds any printed code with its symbol at 14 mm (what documents lay out audio bars and file cards at) |
PdfImageAdjust, adjustPixels(raster, adjust, blurPx?), gaussianBlur(raster, sigma), Raster | picture corrections on RGBA pixels: brightness(), contrast(), saturate(), grayscale(1) and blur() as the Filter Effects spec defines them, in that order, in sRGB (what the editor's CSS filter draws, within ±2 levels of Chrome). ctx.image(src, box, { adjust }) decodes PNG (UPNG) and JPEG (jpeg-js) on demand, applies them and embeds the pixels (Flate, an alpha soft mask once blurred); undecodable images embed uncorrected |
Media cards and QR codes
Video, audio, embeds and file attachments print as a card in their laid-out box: the poster (video), the title, a detail line ("Video · 12:34", "PDF · 1.2 MB · 12 pages") and a link. A plugin's painter may return the card (PrintFallback; plugin-media's and plugin-player's do). Without one, which is the case when a server exports stored pages, exportPdf draws the same card itself for media:video, media:audio, media:iframe and fileAttachment fragments. Its title is the media's title, else its alt text, else its name, skipping kind words and Office's default names ("video", "Picture 3", "Video 2"); with none left the title is the kind ("Video") and the detail line shows only the duration. A slide's media frame passes its description, else its name. The QR code sits inside the card's border, clear of its corners.
mediaLink(attrs, kind)gives the link a card prints and its QR code encodes, for the node's attrs andkind('video','audio','file'or'embed'): an absolute URL for paper, where a stored/media/<id>means nothing.undefinedkeeps the card's own link (attrs.srcthroughresolveSrc);nullprints neither link nor code. The result is used as given. A throwing hook keeps the default and warns.mediaQr: trueadds a QR code to every media card, encoding its link when that is an absolute URL (else a warning namesmediaLink). A painter's card may ask for one itself:qr: true(its link) orqr: '<text>'.- Links, annotations and codes share one allowlist:
http:,https:,mailto:,tel:,ftp:. A link with another scheme (javascript:,data:,file:…) is dropped with its code and a warning; a painter'sqrtext must pass the same check. A relative link (no scheme) is never encoded. - The code is drawn as vectors (one rectangle per run of dark modules) on white with a 4-module quiet zone, at the card's end and as tall as the card allows (at most 160 px). Its symbol (the dark modules, quiet zone not counted) prints at least 14 mm across; a code that would be smaller, or with modules under about 0.25 mm (a long link), is skipped with a warning: short links scan best. Documents lay out audio bars and file cards 76 px tall (
CARD_QR_HEIGHT), which holds any code at that size: the padding gives way to the code, which takes more than 40% of a narrow card's width when it needs it. Pages laid out before 0.50.2 (54 / 56 px cards) skip their codes until laid out again. - Cards follow the export's language: an Arabic
lang(else a right-to-leftdiror document) lays them out from the right (image right, code left) and names the kinds in Arabic ("فيديو", "صوت", "مرفق", "12 صفحة"); the host's own titles stay as they are. - Slides: a picture that is a media frame (
media: 'video' | 'audio', orembed) prints its poster as PowerPoint does (its default frame without one). WithmediaQrormediaLink, a card band (at least 76 px) runs across the bottom of the frame (the whole frame under 120 px tall; a frame shorter than 76 px, an audio icon, prints a 76 px card centred on it) through the same hook (attrs:mediaType,src= the media or embedded page,title).
Page layers
PdfExportOptions.pageLayers (e.g. composePlugins(...).pageLayers) are drawn under and over each page's content with target 'pdf', and PdfExportOptions.variables fill their {{variables}}. Layer custom fragments use painters[type], with extra context:
| Export | Description |
|---|---|
PdfPageLayer | structural twin of @nextgensoftwares/folio-editor's PageLayer (no editor dependency) |
PdfLayerPaintContext | PdfPaintContext plus fragment, opacity(alpha) (fill/stroke opacity through a shared ExtGState), measure(text, font) (shaped advance, px) and imageSize(src) |
LayerDrawer | draws the layers of one export (used by exportPdf) |
imageHeaderSize(bytes) | intrinsic size from PNG/JPEG headers, or null |
runExport(label, task, { abort? }), exportProgress, ExportTask, ExportControl | the running export or import, shared by every export plugin and @nextgensoftwares/folio-plugin-import (same as in @nextgensoftwares/folio-export-docx): task({ signal, report(stage, done?, total?) }) (total 0 = indeterminate, 1 = done is a fraction); Cancel also aborts abort (an AbortController); resolves undefined when cancelled. exportProgress.get() / .subscribe(fn) for progress UIs (<FolioView> shows one) |
documentLoaded(editor, label), LoadingLike | waits until a progressively loaded document is complete (LoadingLike = { loaded?: PromiseLike }, e.g. a FolioEditor from folio-sync's assembleDocument), so an export never writes only the part loaded so far: resolves true at once when nothing is loading, else the wait runs as its own runExport task (label, "Waiting for the document to finish loading…", with Cancel); false when cancelled, throws when loading failed. The export plugins call it first (same as in @nextgensoftwares/folio-export-docx) |
Page ranges, flattening and protection
See Reader & protection. PdfExportOptions extends PdfProtectionOptions: pages, watermarkMode ('layer' or 'interleaved'), pageVariables(page), permissions, ownerPassword.
| Export | Description |
|---|---|
PdfProtectionOptions | the options above |
PageSelection, selectPages(total, sel), parsePageRange(text, total?), countPages(total, sel) | 1-based selections ([1, [3, 5]], { from, to }) → sorted 0-based indices; "1-3, 7, 10-" parsing |
exportFlattenedPdf(layout, opts), FlattenedPdfOptions | image-only pages from a rasterizer (dpi default 150, pages, permissions, creator): no document fonts or text |
PageRasterizer, PageRaster | (page, { index, scale, totalPages }) => { data, type: 'png' | 'jpeg' } |
drawInterleaved(writer, page, ctx, layers) | the hardened-watermark page drawer |
encryptPdf(doc, opts), PdfPermissions, PdfEncryptOptions | standard security handler (V2/R3, RC4-128, empty user password) with print/copy/modify/annotate/fillForms/accessibility flags. Weak by design |
resolveExportRequest(handler, format, total, sel?), ExportVerdict | runs a policy: veto, narrow (never widen), fail closed |
ExportRequest, ExportDecision, ExportRequestHandler | { pages, format, totalPages } → true | false | { allow?, pages?, reason? } |
maxPagesPolicy(max, message?), indicesToSelection(indices) | demo policy (first max pages); indices → selection |
resolveExportPages(opts, editor, mode), PdfExportPolicyOptions, PdfExportMode | the plugin's flow: ask for a range, run the policy |
Plugin
| Export | Description |
|---|---|
pdfExportPlugin(opts?: PdfExportPluginOptions): ExportPlugin | "Export ▸ PDF" toolbar entry: exports editor.layout and downloads it |
PdfExportPluginOptions | Partial<PdfExportOptions> plus faces?: FaceFile[], pageLayers? and variables? (values or getters read at export time), filename?, exporters?: Record<string, unknown> | (() => Record<string, unknown> | undefined) (other plugins' exporters.pdf, a map or a getter), onDone?(bytes, ms), onError?, and PdfExportPolicyOptions: onExportRequest, askPages, onDenied, pageRange (adds "PDF: pages…", default on), flatten: { rasterize, dpi?, permissions?, label? } (adds "PDF (protected, flattened)…"; rasterize may be a parameterless getter called per export) |
splitExporters(map, painters?, resolveSrc?) | { painters, resolveSrc? }: separates painters from plugin-media's resolveSrc entry |
ExportPlugin, ExportUIItem, ExportEditorLike | structural twins of FolioPlugin / UIItem (no editor dependency); all export plugins share one "Export" submenu |
Browser helpers
| Export | Signature | Description |
|---|---|---|
fontFiles | (faces: readonly FaceFile[]) => (font: FontSpec) => Promise<Uint8Array | null> | a fonts callback over font URLs (each fetched once; nearest weight); re-exported from @nextgensoftwares/folio-fonts |
FaceFile | { family; src; weight?: number | [number, number]; style? } | |
loadImageInBrowser | (src) => Promise<PdfImageData | null> | fetch an image (SVG rasterized) |
rasterizeSvgInBrowser | (svg, width, height) => Promise<Uint8Array | null> | SVG → PNG through a canvas |
decodeDataUrl | (src) => PdfImageData | null | decode a data: URL |
mathFromHtml | (render, options?: HtmlMathOptions) => PdfExportOptions['math'] | browser: typesets HTML math (KaTeX) off-screen into a PdfMathDrawing (embedded glyphs, rules, SVG paths); HtmlMathOptions.fontBytes overrides font lookup |
mathImageFromHtml | (render, options?: HtmlMathOptions & { scale?, color? }) => (latex, display, size, column?) => Promise<{ png, width, height, depth } | null> | browser: the same drawing rasterized on a canvas (default 4×), for DOCX math: 'image' |
PdfMathDrawing, PdfMathItem | vector equation: { width, height, depth, items, fonts }; items are glyphs, rect or path. Drawn with its baseline on the math box's baseline, centred, scaled only when typeset at another size. Glyph chars may carry a pre-shaped gid. Without a DOM (Node, workers): katexMath / katexMathNode from folio-math | |
svgPathToPdf | (d: string, m?: Matrix) => string | SVG path data (all commands, arcs as cubics) → PDF path operators, points mapped by m |
toUnicodeCMap | (map: ReadonlyMap<number, string>) => string | ToUnicode CMap for glyph id → text (searchable text) |
Comment annotations
| Export | Signature | Description |
|---|---|---|
PdfAnnotation, PdfAnnotationEntry | { author, text, date?, kind?: 'highlight' | 'note', rects, color?, replies? }: a highlight over rects (page px) or a sticky note, replies as notes "in reply to" it (IRT) | |
PdfAnnotationSource | (page, index) => readonly PdfAnnotation[] | undefined | PdfExportOptions.annotations (off unless given); pdfExportPlugin({ annotationsFor: (editor) => source }) builds one per export (see the comments plugin) |
annotationRefs | (ctx, page, list, seq) => PDFRef[] | writes a page's annotations (used by exportPdf) |