@docx-editor.dev/docx-to-pdf 0.0.1 → 2.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +121 -0
- package/README.md +127 -3
- package/THIRD_PARTY_NOTICES.md +32 -0
- package/assets/NotoEmoji-Regular.ttf +0 -0
- package/assets/NotoSansArabic-Regular.ttf +0 -0
- package/assets/NotoSansMath-Regular.ttf +0 -0
- package/assets/NotoSansSymbols2-Regular.ttf +0 -0
- package/assets/README.md +7 -0
- package/assets/TwemojiMozilla.ttf +0 -0
- package/assets/sources.json +60 -0
- package/dist/index.cjs +3299 -0
- package/dist/index.d.cts +146 -0
- package/dist/index.d.ts +146 -0
- package/dist/index.js +3270 -0
- package/docs/api.md +127 -0
- package/docs/fonts.md +151 -0
- package/docs/integrations.md +107 -0
- package/docs/markdown-contract.md +111 -0
- package/licenses/NotoEmoji-OFL.txt +93 -0
- package/licenses/NotoSansArabic-OFL.txt +93 -0
- package/licenses/NotoSansMath-OFL.txt +93 -0
- package/licenses/NotoSansSymbols2-OFL.txt +93 -0
- package/licenses/TwemojiMozilla-LICENSE.md +35 -0
- package/package.json +81 -5
package/docs/api.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# PDF export API
|
|
2
|
+
|
|
3
|
+
Import conversion functions, error classes, font helpers, and result types from `@docx-editor.dev/docx-to-pdf`.
|
|
4
|
+
|
|
5
|
+
## Convert a document
|
|
6
|
+
|
|
7
|
+
`exportPdf(source, options?)` returns `Promise<PdfExportResult>`. Pass DOCX bytes as a `Uint8Array` or Node.js `Buffer`. Read files before conversion; the function does not accept paths, URLs, streams, or live editor views. The function preserves the source and releases its document session after success or failure.
|
|
8
|
+
|
|
9
|
+
Use Node.js 20.16.0 or later in the 20.x release line, or Node.js 22.3.0 or later. The converter needs WebAssembly and access to its packaged font files. Browser and Edge runtimes are not supported.
|
|
10
|
+
|
|
11
|
+
## Reusable sessions
|
|
12
|
+
|
|
13
|
+
`openDocumentForExport(source, options?)` returns `Promise<OpenPdfDocumentForExportResult>`. It accepts immutable DOCX bytes and font/layout options. Its result has the same success/refusal shape as Markdown's open function. On success, `result.session` provides the font-backed capabilities required by PDF output. On refusal, inspect `reason` and optional `detail`. Font policy and resource failures still throw typed errors.
|
|
14
|
+
|
|
15
|
+
`exportPdfFrom(session, options?)` returns `Promise<PdfExportResult>` without reopening the document. It accepts `PdfProjectionOptions`: `comments`, `fidelityPolicy`, `displayMode`, `timeoutMs`, `maxPages`, `maxOutputBytes`, and `signal`. Omit `displayMode` to use the session's default projection. An explicit mode uses the session's cached `layoutFor(mode)` projection. Result `timings.openMs` is `0` because this call does not open the document.
|
|
16
|
+
|
|
17
|
+
Use `OpenPdfDocumentForExportOptions` for font and layout settings when opening. Use `PdfExportSession` when you need to name the session type. An ordinary Core session with approximate measurement cannot produce PDF output. `exportPdfFrom` rejects a session that lacks admitted fonts and glyph capabilities.
|
|
18
|
+
|
|
19
|
+
The caller owns the session and must call `dispose()` in `finally`. An export failure, projection cancellation, or projection deadline does not dispose a caller-owned session. The signal supplied when opening controls shared resource work and the session lifetime. A signal supplied to `exportPdfFrom` stops only that export's wait and encoding work. Shared resource work can continue until settlement, its resource deadline, or session disposal. After disposal, later exports reject with `ExportResourceError` and `code: 'disposed'`.
|
|
20
|
+
|
|
21
|
+
For both formats from one layout, see [Compare PDF and Markdown conversion](markdown-contract.md#reuse-one-session).
|
|
22
|
+
|
|
23
|
+
## Options
|
|
24
|
+
|
|
25
|
+
| Option | Default | Behavior |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `fidelityPolicy` | `'strict'` | Reject unsupported or approximate PDF content. `'best-effort'` returns available output with diagnostics. |
|
|
28
|
+
| `displayMode` | `'proposed'` | Choose `'proposed'`, `'original'`, or `'all-markup'` for tracked changes. |
|
|
29
|
+
| `comments` | `true` | Include native PDF annotations. |
|
|
30
|
+
| `useSystemFonts` | `true` | Search supported installed font files. Disable for consistent font selection across hosts. |
|
|
31
|
+
| `fonts` | — | Resolve these font sources before installed and packaged sources. |
|
|
32
|
+
| `fallbackFonts` | — | Resolve missing faces after packaged substitutes. |
|
|
33
|
+
| `lastResortFonts` | — | Resolve missing faces after embedded fonts and before generic substitutes. |
|
|
34
|
+
| `fontPolicy` | `'best-effort'` | `'strict'` rejects failed sources or incomplete face coverage. Substitutes can satisfy coverage. |
|
|
35
|
+
| `onFontResolution` | — | Receive font evidence before a strict font refusal. Callback promises do not delay export. |
|
|
36
|
+
| `glyphFallbacks` | Packaged fallback list | Ordered faces for missing glyphs; at most 16 entries. |
|
|
37
|
+
| `documentLigatures` | `true` | Apply optional document ligatures during measurement and PDF output. |
|
|
38
|
+
| `timeoutMs` | `60000` | Cooperative conversion deadline. Integer from `1` to `2147483647`. |
|
|
39
|
+
| `fontResolutionTimeoutMs` | `resourceTimeoutMs`, then `60000` | Font resolution deadline in milliseconds. |
|
|
40
|
+
| `resourceTimeoutMs` | `60000` | Resource and layout deadline in milliseconds. |
|
|
41
|
+
| `signal` | — | Cancel through an `AbortSignal`. |
|
|
42
|
+
| `maxPages` | `10000` | Maximum pages; integer from `1` to `10000`. Checked after layout, before PDF painting. |
|
|
43
|
+
| `maxOutputBytes` | `67108864` | Maximum encoded bytes; integer from `1` to `67108864`. Checked after encoding. |
|
|
44
|
+
| `imageDecodePort` | Bounded built-in decoder | Supply image metadata through Core's decoder interface. |
|
|
45
|
+
| `convertPreservedImage` | — | Convert a preserved image format through Core's converter interface. |
|
|
46
|
+
|
|
47
|
+
Resource and font deadlines must be positive, finite numbers no greater than `2147483647`. The conversion deadline also applies during those phases. `measurer`, `producer`, and `reuseAcrossRevisions` are unsupported and cause `TypeError`. PDF conversion requires the fonts used during layout to encode the positioned glyphs.
|
|
48
|
+
|
|
49
|
+
See [Configure PDF fonts](fonts.md) for font sources and policy details.
|
|
50
|
+
|
|
51
|
+
## Result
|
|
52
|
+
|
|
53
|
+
| Field | Meaning |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `bytes` | PDF bytes owned by this result. Save them or send them with `Content-Type: application/pdf`. |
|
|
56
|
+
| `pageCount` | Number of physical PDF pages. |
|
|
57
|
+
| `layoutRevision` | Revision of this conversion's layout. This value is not a document identifier. |
|
|
58
|
+
| `displayMode` | Applied revision display mode. |
|
|
59
|
+
| `fontResolution` | Requested families, resolved faces, substitutions, and source failures. |
|
|
60
|
+
| `diagnostics` | Immutable list of output limitations and informational notices. |
|
|
61
|
+
| `timings` | `openMs`, `layoutMs`, `paintMs`, and `saveMs`, measured in milliseconds. |
|
|
62
|
+
|
|
63
|
+
The result object and timing fields are immutable. The byte array remains mutable; changing it does not change later exports. Store the input hash, package versions, font configuration, and display mode when you need reproducible exports.
|
|
64
|
+
|
|
65
|
+
## Diagnostics
|
|
66
|
+
|
|
67
|
+
Each `PdfDiagnostic` includes `code`, `message`, and `severity`. Page diagnostics include zero-based `pageIndex` and one-based `pageNumber`. Use `pageNumber` for display, as with Markdown warnings. An absent page field means the diagnostic applies to the document or has no specific page.
|
|
68
|
+
|
|
69
|
+
| Severity | Strict output | Meaning |
|
|
70
|
+
| --------------- | ------------- | ------------------------------------------------------------- |
|
|
71
|
+
| `information` | Allowed | Inspect the report; this notice alone does not reject output. |
|
|
72
|
+
| `approximation` | Rejected | Output changes the requested presentation. |
|
|
73
|
+
| `unsupported` | Rejected | The writer cannot reproduce the content. |
|
|
74
|
+
|
|
75
|
+
Each `font-origin-failed` diagnostic identifies one failed source through `originIndex`, optional `originName`, and a guarded cause message. It appears even when another source supplies the font. `incomplete-font` identifies incomplete coverage or substituted face variants within a family. It has `information` severity; `fontPolicy: 'strict'` independently rejects the font failure. `font-substitution` reports generic substitutes that can change pagination. Other codes identify limitations such as `equation-fallback`, `image-clip`, or `core-*` source omissions. Handle unknown diagnostic codes by severity; the set can grow. Use messages for display, not program control.
|
|
76
|
+
|
|
77
|
+
## Errors
|
|
78
|
+
|
|
79
|
+
| Error | Stable `code` | Useful fields |
|
|
80
|
+
| --- | --- | --- |
|
|
81
|
+
| `PdfDocumentOpenError` | `documentOpenFailed` | Typed `reason` and optional `detail`. |
|
|
82
|
+
| `PdfFidelityError` | `fidelityUnsupported` | `diagnostics` for the refused output. |
|
|
83
|
+
| `PdfPageLimitError` | `pageLimitExceeded` | `limit` and `actual` page counts. Extends `RangeError`. |
|
|
84
|
+
| `PdfOutputLimitError` | `outputTooLarge` | `limit` and `actual` byte counts. Extends `PdfEncodingError`. |
|
|
85
|
+
| `PdfWorkLimitError` | `workLimitExceeded` | Content, operation, or diagnostic budget exceeded. |
|
|
86
|
+
| `PdfEncodingError` | `encodingFailed` | Optional underlying `cause`. |
|
|
87
|
+
| `ExportResourceError` | Core resource code | Optional underlying `cause`. |
|
|
88
|
+
| `TypeError`, `RangeError` | — | Invalid arguments or other internal size limits. |
|
|
89
|
+
|
|
90
|
+
PDF failure codes use Core's camelCase convention. Content diagnostic codes use kebab-case, as Markdown warnings do. Limit errors retain their previous base classes so existing `RangeError` and `PdfEncodingError` handlers still catch them.
|
|
91
|
+
|
|
92
|
+
Core resource codes include `aborted`, `timedOut`, `nonConvergent`, `disposed`, `layoutInvariant`, and `layoutFailed`. A strict font refusal uses `ExportResourceError` with `code: 'layoutFailed'`. Use `onFontResolution` to retain its font evidence.
|
|
93
|
+
|
|
94
|
+
Handle expected refusals and rethrow unexpected failures:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import {
|
|
98
|
+
exportPdf,
|
|
99
|
+
PdfDocumentOpenError,
|
|
100
|
+
PdfFidelityError,
|
|
101
|
+
PdfOutputLimitError,
|
|
102
|
+
PdfPageLimitError,
|
|
103
|
+
} from '@docx-editor.dev/docx-to-pdf';
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const result = await exportPdf(docxBytes, { maxPages: 100 });
|
|
107
|
+
await savePdf(result.bytes);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof PdfFidelityError) {
|
|
110
|
+
console.table(error.diagnostics);
|
|
111
|
+
} else if (error instanceof PdfDocumentOpenError) {
|
|
112
|
+
console.error(error.code, error.reason);
|
|
113
|
+
} else if (error instanceof PdfPageLimitError || error instanceof PdfOutputLimitError) {
|
|
114
|
+
console.error(error.code, error.actual, error.limit);
|
|
115
|
+
} else {
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Here, `docxBytes` contains the input and `savePdf` is your storage function. Choose best-effort output explicitly after reviewing your application's fidelity requirements. Do not automatically retry a strict refusal with weaker settings.
|
|
122
|
+
|
|
123
|
+
## Resource boundaries
|
|
124
|
+
|
|
125
|
+
The writer limits operations to `2000000`, diagnostics to `10000`, and uncompressed content to `67108864` bytes. Core also bounds DOCX parsing, fonts, images, and layout. `maxPages` and `maxOutputBytes` do not impose a process memory limit. They check completed layout and completed encoding, respectively.
|
|
126
|
+
|
|
127
|
+
Cancellation checks occur between batches. Synchronous parsing, font work, and image work cannot stop during a call. For hard deadlines, terminate a worker after your deadline. For memory isolation, configure the worker's `resourceLimits.maxOldGenerationSizeMb`. Bound concurrent conversions; each active document retains layout and font data.
|
package/docs/fonts.md
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Configure PDF fonts
|
|
2
|
+
|
|
3
|
+
Fonts determine line breaks, page counts, and the glyphs embedded in PDF output. The converter uses installed fonts and packaged substitutes by default.
|
|
4
|
+
|
|
5
|
+
## Choose a source
|
|
6
|
+
|
|
7
|
+
| Need | Configuration |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| Use default font sources | Omit font options. |
|
|
10
|
+
| Keep font selection consistent across hosts | Set `useSystemFonts: false` and pin package versions. |
|
|
11
|
+
| Override an installed or packaged face | Supply `fonts`. |
|
|
12
|
+
| Supply faces absent from packaged sources | Supply `fallbackFonts`. |
|
|
13
|
+
| Keep embedded faces before your final fallback | Supply `lastResortFonts`. |
|
|
14
|
+
|
|
15
|
+
Sources resolve in this order:
|
|
16
|
+
|
|
17
|
+
1. Your `fonts` sources.
|
|
18
|
+
2. Installed fonts, unless `useSystemFonts` is `false`.
|
|
19
|
+
3. Packaged substitutes.
|
|
20
|
+
4. Your `fallbackFonts` sources.
|
|
21
|
+
5. Supplemental packaged faces, including `@docx-editor.dev/fonts-cjk` when it is installed.
|
|
22
|
+
6. Document-embedded fonts.
|
|
23
|
+
7. Your `lastResortFonts` sources.
|
|
24
|
+
8. Generic substitutes for unresolved families.
|
|
25
|
+
|
|
26
|
+
Earlier sources take priority. Each option accepts one source or an ordered array of sources. Use `defineFontResolver` for a resolver that reads the document's requested families. The `PdfFontOrigin` and `PdfFontsSource` types describe these inputs.
|
|
27
|
+
|
|
28
|
+
The default sources need no network access. A resolver that you supply can make network requests.
|
|
29
|
+
|
|
30
|
+
## Add Chinese, Japanese, and Korean text
|
|
31
|
+
|
|
32
|
+
The converter package does not include a Chinese, Japanese, or Korean (CJK) font. If your server has no suitable font, install the optional package:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
npm install @docx-editor.dev/fonts-cjk
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The converter declares this package as an optional peer dependency. Install a version that satisfies its peer dependency range. The converter finds the package at runtime and needs no configuration. Its Noto Sans CJK JP font supplies CJK characters that earlier sources do not cover. It also substitutes for unavailable families such as SimSun, MS Mincho, and Malgun Gothic.
|
|
39
|
+
|
|
40
|
+
If you previously relied on bundled CJK coverage, add this package to your production dependencies. Keep the package external to your server bundle. Retain its `dist/` and `assets/` directories in their package locations. Include its license files when distributing the package.
|
|
41
|
+
|
|
42
|
+
You can omit the package when installed fonts or your supplied fonts cover every required character. An installed package with missing or unreadable assets reports `font-origin-failed`. Inspect `result.fontResolution.originFailures` for the cause.
|
|
43
|
+
|
|
44
|
+
When `useSystemFonts` is `true`, suitable installed fonts take priority. Setting `useSystemFonts: false` still permits the optional package and fonts that you supply.
|
|
45
|
+
|
|
46
|
+
If no source covers a CJK character, export reports `missing-glyph`, and strict export fails. When the optional package is absent, the diagnostic names it. An unavailable CJK family uses a generic substitute and reports `font-substitution`.
|
|
47
|
+
|
|
48
|
+
### CJK package API
|
|
49
|
+
|
|
50
|
+
`@docx-editor.dev/fonts-cjk` runs on Node.js `^20.16.0 || >=22.3.0`. It exports the font family and its local file URL:
|
|
51
|
+
|
|
52
|
+
| Export | Type | Value |
|
|
53
|
+
| --- | --- | --- |
|
|
54
|
+
| `NOTO_SANS_CJK_JP_FAMILY` | String literal | `'Noto Sans CJK JP'` |
|
|
55
|
+
| `NOTO_SANS_CJK_JP_URL` | `URL` | A `file:` URL for `assets/NotoSansCJKjp-Regular.otf`. |
|
|
56
|
+
|
|
57
|
+
Use the URL to read the font directly:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { readFile } from 'node:fs/promises';
|
|
61
|
+
import {
|
|
62
|
+
NOTO_SANS_CJK_JP_FAMILY,
|
|
63
|
+
NOTO_SANS_CJK_JP_URL,
|
|
64
|
+
} from '@docx-editor.dev/fonts-cjk';
|
|
65
|
+
|
|
66
|
+
const fontBytes = new Uint8Array(await readFile(NOTO_SANS_CJK_JP_URL));
|
|
67
|
+
console.log(NOTO_SANS_CJK_JP_FAMILY, fontBytes.byteLength);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Automatic PDF fallback needs no direct import. If you supply `glyphFallbacks`, your list replaces the defaults. For this fallback, add an entry with `family: NOTO_SANS_CJK_JP_FAMILY`, `weight: 400`, and `style: 'normal'`.
|
|
71
|
+
|
|
72
|
+
### CJK font coverage and licensing
|
|
73
|
+
|
|
74
|
+
The package supplies Noto Sans CJK JP Regular as an OpenType font with CFF outlines. It contains one weight (`400`) and one style (`'normal'`). PDF export can synthesize bold and italic from the regular face.
|
|
75
|
+
|
|
76
|
+
The package contains the Japanese regional face, without separate Chinese or Korean regional faces. Substitution can change glyph forms, line breaks, and page counts. Supply your own font through `fonts` when you need a specific regional face or designed style.
|
|
77
|
+
|
|
78
|
+
The package reads its font from disk without network access. It does not bundle the font into JavaScript or install a browser font.
|
|
79
|
+
|
|
80
|
+
The package code uses the Apache License 2.0. The font uses the SIL Open Font License, Version 1.1. The PDF converter uses the separate EigenPal Pro License.
|
|
81
|
+
|
|
82
|
+
## Export Arabic and Hebrew text
|
|
83
|
+
|
|
84
|
+
Default fallback fonts cover Arabic and Hebrew. Arabic fallback selection requires a font with Arabic shaping support. Arabic joining continues across formatting runs, including changes in text color. The PDF text layer preserves logical word order for Arabic, Persian, and Hebrew text extraction.
|
|
85
|
+
|
|
86
|
+
When a selected face lacks bold or italic variants, the writer can draw synthetic styles. It preserves text extraction and glyph positions. To use your own designed variants, supply separate regular, bold, italic, and bold-italic font files.
|
|
87
|
+
|
|
88
|
+
## Supply a font file
|
|
89
|
+
|
|
90
|
+
Use `createFontSource` from the converter package to validate your font bytes. This example expects your licensed regular font file and a document that requests `Application Sans`:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
94
|
+
import { createFontSource, exportPdf } from '@docx-editor.dev/docx-to-pdf';
|
|
95
|
+
|
|
96
|
+
const fontBytes = new Uint8Array(await readFile('ApplicationSans.ttf'));
|
|
97
|
+
const admitted = createFontSource(fontBytes, {
|
|
98
|
+
family: 'Application Sans',
|
|
99
|
+
weight: 400,
|
|
100
|
+
style: 'normal',
|
|
101
|
+
});
|
|
102
|
+
if ('failure' in admitted) {
|
|
103
|
+
throw new Error(admitted.failure.diagnostic ?? admitted.failure.reason);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const source = await readFile('document.docx');
|
|
107
|
+
const result = await exportPdf(source, {
|
|
108
|
+
useSystemFonts: false,
|
|
109
|
+
fonts: { sources: [admitted.source] },
|
|
110
|
+
});
|
|
111
|
+
await writeFile('document.pdf', result.bytes);
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Register bold, italic, and bold-italic files separately when the document needs those faces. Use weights `400` and `700`, with styles `'normal'` and `'italic'`. Check your font license before embedding its bytes. The writer rejects prohibited embedding, prohibited subsetting, variable fonts, and unsupported font containers.
|
|
115
|
+
|
|
116
|
+
## Separate font policy from PDF policy
|
|
117
|
+
|
|
118
|
+
`fontPolicy: 'strict'` rejects failed sources and incomplete face coverage. It can reject an export when another source recovers from a source failure. Complete coverage can include substitutions; it does not prove original font selection.
|
|
119
|
+
|
|
120
|
+
`fidelityPolicy: 'strict'` rejects unsupported or approximate PDF output. It permits the packaged metric substitutes but rejects generic substitutions that can change page breaks. It does not automatically enable strict font policy.
|
|
121
|
+
|
|
122
|
+
To require both checks, set both policies:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const result = await exportPdf(source, {
|
|
126
|
+
fontPolicy: 'strict',
|
|
127
|
+
fidelityPolicy: 'strict',
|
|
128
|
+
useSystemFonts: false,
|
|
129
|
+
onFontResolution(report) {
|
|
130
|
+
console.table(report.families);
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The callback runs before a strict font refusal. Returned callback promises do not delay conversion.
|
|
136
|
+
|
|
137
|
+
## Inspect font evidence
|
|
138
|
+
|
|
139
|
+
`result.fontResolution.families` records each family's coverage and selected faces. Inspect each face's `sourceFamily`, `via`, and `substitution` fields. `originFailures` retains source failures and their causes. `droppedEmbeddedFonts` identifies embedded faces rejected during font admission.
|
|
140
|
+
|
|
141
|
+
Each `font-origin-failed` diagnostic provides the source index, optional source name, and a guarded cause message. The `incomplete-font` diagnostic reports partial coverage and substituted variants within a family. It remains informational when `fontPolicy` permits recovery.
|
|
142
|
+
|
|
143
|
+
| Symptom | Action |
|
|
144
|
+
| --- | --- |
|
|
145
|
+
| Pages differ across hosts | Disable system fonts and use identical font bytes and package versions. |
|
|
146
|
+
| `font-substitution` diagnostic | Supply the requested family through `fonts` or review best-effort output. |
|
|
147
|
+
| Strict font policy rejects conversion | Inspect the callback report for failed sources and missing face variants. |
|
|
148
|
+
| Missing font assets after bundling | Keep converter packages external and copy their assets with deployment output. |
|
|
149
|
+
| Missing glyphs | Supply a face that contains the requested characters. For CJK text, install `@docx-editor.dev/fonts-cjk`. |
|
|
150
|
+
|
|
151
|
+
For server setup, see [Integrate PDF conversion](integrations.md).
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Integrate PDF conversion
|
|
2
|
+
|
|
3
|
+
The converter runs on Node.js and returns PDF bytes. Keep conversion on the server for browser applications. The package uses the EigenPal Pro License. Install the converter and its engine peer before using these examples:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @docx-editor.dev/docx-to-pdf @docx-editor.dev/core
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Return a PDF response
|
|
10
|
+
|
|
11
|
+
A Node.js route can return the bytes in a web `Response`. This handler accepts raw DOCX bytes, not multipart form data:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import {
|
|
15
|
+
exportPdf,
|
|
16
|
+
ExportResourceError,
|
|
17
|
+
PdfDocumentOpenError,
|
|
18
|
+
PdfFidelityError,
|
|
19
|
+
PdfOutputLimitError,
|
|
20
|
+
PdfPageLimitError,
|
|
21
|
+
} from '@docx-editor.dev/docx-to-pdf';
|
|
22
|
+
|
|
23
|
+
export async function POST(request: Request): Promise<Response> {
|
|
24
|
+
try {
|
|
25
|
+
const source = new Uint8Array(await request.arrayBuffer());
|
|
26
|
+
const result = await exportPdf(source, {
|
|
27
|
+
signal: request.signal,
|
|
28
|
+
timeoutMs: 30_000,
|
|
29
|
+
maxPages: 100,
|
|
30
|
+
maxOutputBytes: 16 * 1024 * 1024,
|
|
31
|
+
useSystemFonts: false,
|
|
32
|
+
});
|
|
33
|
+
return new Response(new Uint8Array(result.bytes), {
|
|
34
|
+
headers: {
|
|
35
|
+
'Content-Type': 'application/pdf',
|
|
36
|
+
'Content-Disposition': 'attachment; filename="document.pdf"',
|
|
37
|
+
'Cache-Control': 'no-store',
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error instanceof PdfDocumentOpenError) {
|
|
42
|
+
return Response.json({ error: error.code }, { status: 422 });
|
|
43
|
+
}
|
|
44
|
+
if (error instanceof PdfFidelityError) {
|
|
45
|
+
return Response.json({ error: error.code }, { status: 422 });
|
|
46
|
+
}
|
|
47
|
+
if (error instanceof PdfPageLimitError || error instanceof PdfOutputLimitError) {
|
|
48
|
+
return Response.json({ error: error.code }, { status: 413 });
|
|
49
|
+
}
|
|
50
|
+
if (error instanceof ExportResourceError && error.code === 'timedOut') {
|
|
51
|
+
return Response.json({ error: error.code }, { status: 504 });
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Configure your server's request size limit before `request.arrayBuffer()` reads the body. The output byte limit does not limit uploaded bytes. Set a concurrency limit appropriate for your available memory.
|
|
59
|
+
|
|
60
|
+
## Next.js
|
|
61
|
+
|
|
62
|
+
Use `export const runtime = 'nodejs'` in the route file. Place the handler in `app/api/convert/route.ts`.
|
|
63
|
+
|
|
64
|
+
Keep packages external so Node.js resolves their font and WebAssembly assets:
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
// next.config.mjs
|
|
68
|
+
export default {
|
|
69
|
+
serverExternalPackages: [
|
|
70
|
+
'@docx-editor.dev/docx-to-pdf',
|
|
71
|
+
'@docx-editor.dev/core',
|
|
72
|
+
'@docx-editor.dev/fonts',
|
|
73
|
+
'@docx-editor.dev/fonts-cjk',
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
For a standalone deployment, include the `assets/` directories from the converter and `@docx-editor.dev/fonts`. If you install `@docx-editor.dev/fonts-cjk`, include its `assets/` directory too. Keep the package directory structure intact. Test the deployment artifact with a real conversion before release.
|
|
79
|
+
|
|
80
|
+
## Convert a batch
|
|
81
|
+
|
|
82
|
+
Process a batch sequentially when memory use matters more than throughput:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
86
|
+
import { exportPdf } from '@docx-editor.dev/docx-to-pdf';
|
|
87
|
+
|
|
88
|
+
for (const name of ['first', 'second']) {
|
|
89
|
+
const source = await readFile(`${name}.docx`);
|
|
90
|
+
const result = await exportPdf(source, { useSystemFonts: false });
|
|
91
|
+
await writeFile(`${name}.pdf`, result.bytes);
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The exporter disposes its document session after each call, including failed calls. For repeated exports or both formats from one layout, use [a reusable PDF session](markdown-contract.md#reuse-one-session).
|
|
96
|
+
|
|
97
|
+
## Runtime checks
|
|
98
|
+
|
|
99
|
+
From this repository, validate packed Node.js consumers with:
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
bun run build:pdf
|
|
103
|
+
bun run --filter '@docx-editor.dev/docx-to-markdown' build
|
|
104
|
+
bun run --filter '@docx-editor.dev/docx-to-pdf' check:consumer
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The check installs local tarballs in a temporary directory outside the workspace. It compiles TypeScript consumers and runs conversion through the built package. This check needs registry access for external dependencies.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Compare PDF and Markdown conversion
|
|
2
|
+
|
|
3
|
+
Use `exportPdf(source, options)` and `exportMarkdown(source, options)` for one-shot conversion. Both functions accept DOCX bytes, preserve the source, and dispose their document session after success or failure. PDF and Markdown share font-source types, font helpers, font reports, and resource-error codes.
|
|
4
|
+
|
|
5
|
+
## Share conversion settings
|
|
6
|
+
|
|
7
|
+
Set `displayMode` explicitly when your application produces both formats. Markdown defaults to `'all-markup'`; PDF defaults to `'proposed'`. Without an explicit setting, the outputs can contain different text.
|
|
8
|
+
|
|
9
|
+
Share your font sources and disable PDF system-font discovery for consistent font selection across hosts. Use `documentLigatures: false` on PDF to align with Markdown's default shaping policy. PDF otherwise honors optional document ligatures by default.
|
|
10
|
+
|
|
11
|
+
This function uses the same input and common settings for both formats:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { exportMarkdown, type MarkdownExportOptions } from '@docx-editor.dev/docx-to-markdown';
|
|
15
|
+
import {
|
|
16
|
+
exportPdf,
|
|
17
|
+
type PdfExportOptions,
|
|
18
|
+
type PdfFontsSource,
|
|
19
|
+
} from '@docx-editor.dev/docx-to-pdf';
|
|
20
|
+
|
|
21
|
+
export async function convertBoth(source: Uint8Array, fonts: PdfFontsSource, signal?: AbortSignal) {
|
|
22
|
+
const common = {
|
|
23
|
+
displayMode: 'proposed',
|
|
24
|
+
fonts,
|
|
25
|
+
fontPolicy: 'best-effort',
|
|
26
|
+
resourceTimeoutMs: 15_000,
|
|
27
|
+
signal,
|
|
28
|
+
} satisfies MarkdownExportOptions & PdfExportOptions;
|
|
29
|
+
|
|
30
|
+
const markdown = await exportMarkdown(source, common);
|
|
31
|
+
const pdf = await exportPdf(source, {
|
|
32
|
+
...common,
|
|
33
|
+
useSystemFonts: false,
|
|
34
|
+
documentLigatures: false,
|
|
35
|
+
});
|
|
36
|
+
return { markdown, pdf };
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Both packages export the same `createFontSource` and `defineFontResolver` helpers. For font registration, see [Configure PDF fonts](fonts.md). These settings align common controls; they do not guarantee identical pagination for every document. Missing glyphs, fallback faces, and unsupported features can still affect output.
|
|
41
|
+
|
|
42
|
+
## Shared controls
|
|
43
|
+
|
|
44
|
+
| Member | Shared meaning |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `fonts` | Caller sources take priority over packaged substitutes. |
|
|
47
|
+
| `fallbackFonts` | Supply faces absent from earlier sources. |
|
|
48
|
+
| `fontPolicy` | Strict mode rejects failed origins and incomplete face coverage. |
|
|
49
|
+
| `onFontResolution` | Receive font evidence before a strict font refusal. |
|
|
50
|
+
| `displayMode` | Select proposed content, original content, or all markup. |
|
|
51
|
+
| `signal` | Cancel resource waits and subsequent work. |
|
|
52
|
+
| `resourceTimeoutMs` | Bound resource and layout work. |
|
|
53
|
+
| `fontResolution` | Inspect requested families, selected faces, substitutions, and failed sources. |
|
|
54
|
+
| `ExportResourceError` | Handle shared codes such as `aborted` and `timedOut`. |
|
|
55
|
+
|
|
56
|
+
Strict font policy checks coverage and source failures. It does not prove that the selected faces are the document author's fonts.
|
|
57
|
+
|
|
58
|
+
## Intentional differences
|
|
59
|
+
|
|
60
|
+
| Area | Markdown | PDF |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| Source | DOCX bytes or supported live views | DOCX bytes only |
|
|
63
|
+
| Primary output | `result.markdown` | `result.bytes` |
|
|
64
|
+
| Page data | `result.pages` | `result.pageCount` |
|
|
65
|
+
| Page metadata | `result.pagination.layoutRevision` and `.displayMode` | `result.layoutRevision` and `.displayMode` |
|
|
66
|
+
| Content notices | `result.warnings` | `result.diagnostics`, including severity |
|
|
67
|
+
| Notice page location | Optional one-based `pageNumber` | Optional one-based `pageNumber`, plus zero-based `pageIndex` |
|
|
68
|
+
| Open refusal | `DocumentOpenError` | `PdfDocumentOpenError` |
|
|
69
|
+
| Default revisions | `'all-markup'` | `'proposed'` |
|
|
70
|
+
| Default font discovery | Packaged and embedded sources | Installed, packaged, and embedded sources |
|
|
71
|
+
| Optional ligatures | Disabled | Enabled unless `documentLigatures` is `false` |
|
|
72
|
+
| Unsupported content | Warnings for omissions | Strict refusal by default; optional best-effort output |
|
|
73
|
+
| Comments | Structured review data | Native PDF annotations, unless `comments` is `false` |
|
|
74
|
+
| Reuse | Public export sessions and detached layouts | Public font-backed export sessions |
|
|
75
|
+
| Result delivery | Markdown text, JSON projection, or media bundles | PDF bytes for storage or an HTTP response |
|
|
76
|
+
|
|
77
|
+
PDF also exposes encoding limits, `fidelityPolicy`, and a whole-conversion `timeoutMs`. It needs the admitted font bytes that produced the layout to encode searchable text. It accepts font-backed sessions and rejects arbitrary sessions or detached layouts.
|
|
78
|
+
|
|
79
|
+
Handle notices using each format's public fields. Do not treat a PDF `pageIndex` as a Markdown `pageNumber` without adding one. Store the input version with page references; layout revisions are not persistent document identifiers.
|
|
80
|
+
|
|
81
|
+
## Reuse one session
|
|
82
|
+
|
|
83
|
+
Open through PDF when you need both formats from one font-backed layout. Markdown-opened sessions use different font and ligature settings. PDF accepts these sessions, but strict conversion can refuse missing font identities or unshaped text.
|
|
84
|
+
|
|
85
|
+
This example uses the PDF opener for both outputs:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { readFile } from 'node:fs/promises';
|
|
89
|
+
import { openDocumentForExport, exportPdfFrom } from '@docx-editor.dev/docx-to-pdf';
|
|
90
|
+
import { exportMarkdownFrom } from '@docx-editor.dev/docx-to-markdown';
|
|
91
|
+
|
|
92
|
+
const opened = await openDocumentForExport(await readFile('document.docx'), {
|
|
93
|
+
displayMode: 'proposed',
|
|
94
|
+
useSystemFonts: false,
|
|
95
|
+
});
|
|
96
|
+
if (!opened.ok) throw new Error(opened.reason);
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const markdown = await exportMarkdownFrom(opened.session);
|
|
100
|
+
const pdf = await exportPdfFrom(opened.session);
|
|
101
|
+
console.log(markdown.pages.length, pdf.pageCount);
|
|
102
|
+
} finally {
|
|
103
|
+
opened.session.dispose();
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Both exporters consume the same cached layout and font evidence. `exportPdfFrom` also accepts `displayMode` to encode another cached revision projection. The default session mode does not change when you request another projection. This workflow retains PDF's font and shaping policy for both outputs.
|
|
108
|
+
|
|
109
|
+
## Contract verification
|
|
110
|
+
|
|
111
|
+
`test/markdown-contract.test.ts` converts a synthetic revision document through both exporters. It checks visible text, selected font identity, page metadata, and cancellation with common options. The PDF consumer check compiles packed ESM and CommonJS consumers outside the workspace.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2013 Google LLC
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
https://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|