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;
  }
}
  • source is a Uint8Array or Buffer, 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

OptionDefaultBehavior
fidelityPolicy'strict'Rejects unsupported or approximate content. 'best-effort' returns output with diagnostics.
displayMode'all-markup''proposed', 'original', 'all-markup', or 'simple-markup'.
commentstrueNative annotations. In 'all-markup', pages also shrink beside a balloon pane.
revisionMarkupOmittedViewer markup preferences. Set at session creation.
revisionAuthorSlotsOmittedAuthor names mapped to nonnegative safe integer color slots. Omit for document order.
useSystemFontstrueSearches installed fonts. Disable for consistent selection across hosts.
fontsNoneSources before installed and packaged fonts.
fallbackFontsNoneSources after packaged substitutes.
lastResortFontsNoneSources after embedded fonts, before generic substitutes.
fontPolicy'best-effort''strict' rejects failed sources or incomplete face coverage.
onFontResolutionNoneReceives font evidence before a strict font refusal. Not awaited.
glyphFallbacksPackaged listOrdered faces for missing glyphs, at most 16. Replaces the default.
documentLigaturestrueApplies optional document ligatures.
timeoutMs60000Cooperative whole-conversion deadline, an integer from 1 to 2147483647 ms.
fontResolutionTimeoutMsresourceTimeoutMs, then 60000Font resolution deadline in ms.
resourceTimeoutMs60000Resource and layout deadline in ms.
signalNoneAbortSignal, checked between processing batches.
maxPages10000An integer from 1 to 10000. Checked after layout, before painting.
maxOutputBytes67108864An integer from 1 to 67108864. Checked after encoding.
imageDecodePortBounded built-in decoderSupplies image metadata through the Core decoder interface.
convertPreservedImageBuilt-in TIFF conversionConverts a preserved image format, replacing the TIFF conversion.
  • fontResolutionTimeoutMs and resourceTimeoutMs must be positive finite numbers up to 2147483647. Other values throw RangeError. timeoutMs also applies during resource phases.
  • measurer, producer, and reuseAcrossRevisions are unsupported and throw TypeError.
  • Host CSS and revisionStyles never change PDF colors.
  • RevisionMarkupOptions and ResolvedRevisionMarkup type partial and complete preferences.

For font sources, see Configure PDF fonts.

Read the result

FieldMeaning
bytesPDF bytes owned by the result. Send with Content-Type: application/pdf.
pageCountNumber of physical pages.
layoutRevisionLayout revision of this conversion. Not a document identifier.
displayModeApplied revision display mode.
fontResolutionRequested families, resolved faces, substitutions, and source failures.
diagnosticsImmutable list of output limitations and notices.
timingsopenMs, 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.

SeverityStrict outputMeaning
informationAllowedA notice. It never rejects output alone.
approximationRejectedOutput changes the requested presentation.
unsupportedRejectedThe writer cannot reproduce the content.
CodeSeverityMeaning
font-origin-failedinformationOne font source failed: originIndex, optional originName, guarded cause. Reported even when another source recovers.
incomplete-fontinformationIncomplete coverage or substituted variants in a family. fontPolicy: 'strict' rejects incomplete coverage and required source failures. Substituted variants with complete coverage pass.
font-substitutionunsupportedA generic substitute that can change pagination.
missing-glyphunsupportedNo source covers a character.
drawingunsupportedA 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-recordunsupportedAn EMF or WMF picture stopped early at a resource bound or a malformed record.
metafile-image, metafile-textunsupportedAn image or text inside an EMF or WMF picture failed and is left out.
metafile-fontinformationAn EMF or WMF picture names an unused font and uses the default font.
image-effectsunsupportedA color mode, brightness, or contrast change does not render.
equation-fallbackunsupportedAn equation uses fallback text.
image-clipunsupportedImage clipping uses a Core fallback.
core-*unsupportedCore 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

ErrorcodeFields
PdfDocumentOpenErrordocumentOpenFailedreason, optional detail
PdfFidelityErrorfidelityUnsupporteddiagnostics
PdfPageLimitErrorpageLimitExceededlimit, actual. Extends RangeError.
PdfOutputLimitErroroutputTooLargelimit, actual. Extends PdfEncodingError.
PdfWorkLimitErrorworkLimitExceededContent, operation, or diagnostic budget exceeded.
PdfEncodingErrorencodingFailedOptional cause
ExportResourceErroraborted, timedOut, nonConvergent, disposed, layoutInvariant, layoutFailedOptional cause
TypeError, RangeErrorNoneInvalid 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

FunctionBehavior
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 signal controls shared resource work and session lifetime. An exportPdfFrom signal stops only that export.
  • An explicit displayMode uses the cached layoutFor(mode) projection.
  • Sessions without admitted fonts and glyph capabilities are rejected.

For a complete example, see Export both formats from one session.

Limits

Internal budgetBound
Diagnostics10000
Paint operationsGreater of 2000000 or 6000 per page, up to 40000000
Uncompressed contentGreater of 67108864 or 196608 bytes per page, up to 536870912
Shaping font face41943040 bytes (40 MiB) unless fontShaping sets another value
  • Deadlines and output limits are in Set options. maxPages and maxOutputBytes do 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.maxOldGenerationSizeMb and terminate it on timeout.
  • Core also bounds DOCX parsing, fonts, images, and layout.

Next steps