PDF export API
Reference PDF conversion functions, options, results, diagnostics, and errors.
Import functions, error classes, font helpers, and types from @docx-editor.dev/docx-to-pdf. The package uses the EigenPal Pro License.
Convert a document
exportPdf(source, options?) returns Promise<PdfExportResult>. The following example converts bytes and handles expected refusals; docxBytes and savePdf belong to your application:
import {
exportPdf,
PdfDocumentOpenError,
PdfFidelityError,
PdfOutputLimitError,
PdfPageLimitError,
} from '@docx-editor.dev/docx-to-pdf';
try {
const result = await exportPdf(docxBytes, { maxPages: 100 });
await savePdf(result.bytes);
} catch (error) {
if (error instanceof PdfFidelityError) {
console.table(error.diagnostics);
} else if (error instanceof PdfDocumentOpenError) {
console.error(error.code, error.reason);
} else if (error instanceof PdfPageLimitError || error instanceof PdfOutputLimitError) {
console.error(error.code, error.actual, error.limit);
} else {
throw error;
}
}sourceis aUint8ArrayorBuffer, never a path, URL, stream, or live view.- Conversion preserves the source and releases its session after success or failure.
- It needs Node.js
^20.16.0 || >=22.3.0. Browser and Edge runtimes are unsupported. - Never retry a strict refusal automatically with weaker settings.
Set options
| Option | Default | Behavior |
|---|---|---|
fidelityPolicy | 'strict' | Rejects unsupported or approximate content. 'best-effort' returns output with diagnostics. |
displayMode | 'all-markup' | 'proposed', 'original', 'all-markup', or 'simple-markup'. |
comments | true | Native annotations. In 'all-markup', pages also shrink beside a balloon pane. |
revisionMarkup | Omitted | Viewer markup preferences. Set at session creation. |
revisionAuthorSlots | Omitted | Author names mapped to nonnegative safe integer color slots. Omit for document order. |
useSystemFonts | true | Searches installed fonts. Disable for consistent selection across hosts. |
fonts | None | Sources before installed and packaged fonts. |
fallbackFonts | None | Sources after packaged substitutes. |
lastResortFonts | None | Sources after embedded fonts, before generic substitutes. |
fontPolicy | 'best-effort' | 'strict' rejects failed sources or incomplete face coverage. |
onFontResolution | None | Receives font evidence before a strict font refusal. Not awaited. |
glyphFallbacks | Packaged list | Ordered faces for missing glyphs, at most 16. Replaces the default. |
documentLigatures | true | Applies optional document ligatures. |
timeoutMs | 60000 | Cooperative whole-conversion deadline, an integer from 1 to 2147483647 ms. |
fontResolutionTimeoutMs | resourceTimeoutMs, then 60000 | Font resolution deadline in ms. |
resourceTimeoutMs | 60000 | Resource and layout deadline in ms. |
signal | None | AbortSignal, checked between processing batches. |
maxPages | 10000 | An integer from 1 to 10000. Checked after layout, before painting. |
maxOutputBytes | 67108864 | An integer from 1 to 67108864. Checked after encoding. |
imageDecodePort | Bounded built-in decoder | Supplies image metadata through the Core decoder interface. |
convertPreservedImage | Built-in TIFF conversion | Converts a preserved image format, replacing the TIFF conversion. |
fontResolutionTimeoutMsandresourceTimeoutMsmust be positive finite numbers up to2147483647. Other values throwRangeError.timeoutMsalso applies during resource phases.measurer,producer, andreuseAcrossRevisionsare unsupported and throwTypeError.- Host CSS and
revisionStylesnever change PDF colors. RevisionMarkupOptionsandResolvedRevisionMarkuptype partial and complete preferences.
For font sources, see Configure PDF fonts.
Read the result
| Field | Meaning |
|---|---|
bytes | PDF bytes owned by the result. Send with Content-Type: application/pdf. |
pageCount | Number of physical pages. |
layoutRevision | Layout revision of this conversion. Not a document identifier. |
displayMode | Applied revision display mode. |
fontResolution | Requested families, resolved faces, substitutions, and source failures. |
diagnostics | Immutable list of output limitations and notices. |
timings | openMs, layoutMs, paintMs, and saveMs in milliseconds. |
The result is immutable, except the bytes array.
Diagnostics
Each PdfDiagnostic has code, message, and severity. Page diagnostics add zero-based pageIndex and one-based pageNumber; display pageNumber.
| Severity | Strict output | Meaning |
|---|---|---|
information | Allowed | A notice. It never rejects output alone. |
approximation | Rejected | Output changes the requested presentation. |
unsupported | Rejected | The writer cannot reproduce the content. |
| Code | Severity | Meaning |
|---|---|---|
font-origin-failed | information | One font source failed: originIndex, optional originName, guarded cause. Reported even when another source recovers. |
incomplete-font | information | Incomplete coverage or substituted variants in a family. fontPolicy: 'strict' rejects incomplete coverage and required source failures. Substituted variants with complete coverage pass. |
font-substitution | unsupported | A generic substitute that can change pagination. |
missing-glyph | unsupported | No source covers a character. |
drawing | unsupported | A drawing cannot render and is left out, for example Unsupported drawing: chart. A shape group left out because its picture cannot embed reports information. |
metafile-limit, metafile-record | unsupported | An EMF or WMF picture stopped early at a resource bound or a malformed record. |
metafile-image, metafile-text | unsupported | An image or text inside an EMF or WMF picture failed and is left out. |
metafile-font | information | An EMF or WMF picture names an unused font and uses the default font. |
image-effects | unsupported | A color mode, brightness, or contrast change does not render. |
equation-fallback | unsupported | An equation uses fallback text. |
image-clip | unsupported | Image clipping uses a Core fallback. |
core-* | unsupported | Core omitted source content. The suffix is the Core warning code. |
Handle unknown codes by severity, because the set can grow. A chart with a saved fallback exports it with no diagnostic. For unreported effects, see What renders.
Handle errors
| Error | code | Fields |
|---|---|---|
PdfDocumentOpenError | documentOpenFailed | reason, optional detail |
PdfFidelityError | fidelityUnsupported | diagnostics |
PdfPageLimitError | pageLimitExceeded | limit, actual. Extends RangeError. |
PdfOutputLimitError | outputTooLarge | limit, actual. Extends PdfEncodingError. |
PdfWorkLimitError | workLimitExceeded | Content, operation, or diagnostic budget exceeded. |
PdfEncodingError | encodingFailed | Optional cause |
ExportResourceError | aborted, timedOut, nonConvergent, disposed, layoutInvariant, layoutFailed | Optional cause |
TypeError, RangeError | None | Invalid arguments or internal size limits. |
A strict font refusal throws ExportResourceError with code: 'layoutFailed'. Use onFontResolution to keep its evidence. Failure codes use camelCase; diagnostic codes use kebab-case.
Reuse a session
| Function | Behavior |
|---|---|
openDocumentForExport(source, options?) | Takes OpenPdfDocumentForExportOptions, including revisionMarkup and revisionAuthorSlots. Returns OpenPdfDocumentForExportResult: session (PdfExportSession), or reason and detail on refusal. |
exportPdfFrom(session, options?) | Takes PdfProjectionOptions: comments, fidelityPolicy, displayMode, timeoutMs, maxPages, maxOutputBytes, and signal. timings.openMs is 0. |
session.dispose() | Call in finally. Later exports throw ExportResourceError with disposed. |
- You own the session. Export failures, projection cancellation, and projection deadlines never dispose it.
- The open
signalcontrols shared resource work and session lifetime. AnexportPdfFromsignal stops only that export. - An explicit
displayModeuses the cachedlayoutFor(mode)projection. - Sessions without admitted fonts and glyph capabilities are rejected.
For a complete example, see Export both formats from one session.
Limits
| Internal budget | Bound |
|---|---|
| Diagnostics | 10000 |
| Paint operations | Greater of 2000000 or 6000 per page, up to 40000000 |
| Uncompressed content | Greater of 67108864 or 196608 bytes per page, up to 536870912 |
| Shaping font face | 41943040 bytes (40 MiB) unless fontShaping sets another value |
- Deadlines and output limits are in Set options.
maxPagesandmaxOutputBytesdo not limit process memory. - Synchronous parsing, font work, and image work cannot stop mid-call.
- For a hard deadline or memory isolation, convert in a worker with
resourceLimits.maxOldGenerationSizeMband terminate it on timeout. - Core also bounds DOCX parsing, fonts, images, and layout.