@jasy/pdf 1.0.0-alpha.5 → 1.0.0-alpha.7
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/dist/api/content.d.ts +6 -3
- package/dist/api/content.js +12 -3
- package/dist/api/descriptor.js +24 -1
- package/dist/api/dimension.d.ts +20 -0
- package/dist/api/dimension.js +16 -0
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.js +2 -0
- package/dist/api/layout.d.ts +112 -17
- package/dist/api/layout.js +118 -13
- package/dist/api/page-builder.d.ts +32 -0
- package/dist/api/page-builder.js +32 -0
- package/dist/api/structure.d.ts +5 -0
- package/dist/api/structure.js +1 -0
- package/dist/api/text.d.ts +24 -2
- package/dist/api/text.js +46 -4
- package/dist/elements/container-element.d.ts +26 -1
- package/dist/elements/container-element.js +79 -29
- package/dist/elements/image-element.d.ts +19 -1
- package/dist/elements/image-element.js +52 -11
- package/dist/elements/index.d.ts +8 -0
- package/dist/elements/index.js +8 -0
- package/dist/elements/layout/anchor-element.d.ts +23 -0
- package/dist/elements/layout/anchor-element.js +27 -0
- package/dist/elements/layout/bookmark-element.d.ts +27 -0
- package/dist/elements/layout/bookmark-element.js +30 -0
- package/dist/elements/layout/keep-together-element.d.ts +42 -0
- package/dist/elements/layout/keep-together-element.js +85 -0
- package/dist/elements/layout/link-element.d.ts +33 -0
- package/dist/elements/layout/link-element.js +39 -0
- package/dist/elements/layout/padding-element.d.ts +3 -0
- package/dist/elements/layout/padding-element.js +12 -0
- package/dist/elements/layout/page-break-element.d.ts +17 -0
- package/dist/elements/layout/page-break-element.js +24 -0
- package/dist/elements/layout/page-builder-element.d.ts +32 -0
- package/dist/elements/layout/page-builder-element.js +43 -0
- package/dist/elements/layout/positioned-element.d.ts +10 -7
- package/dist/elements/layout/positioned-element.js +21 -9
- package/dist/elements/layout/rotated-box-element.d.ts +35 -0
- package/dist/elements/layout/rotated-box-element.js +54 -0
- package/dist/elements/layout/rotated-element.d.ts +32 -0
- package/dist/elements/layout/rotated-element.js +41 -0
- package/dist/elements/page-element.d.ts +19 -1
- package/dist/elements/page-element.js +54 -17
- package/dist/elements/pdf-element.d.ts +59 -0
- package/dist/elements/pdf-element.js +51 -0
- package/dist/elements/rectangle-element.d.ts +20 -1
- package/dist/elements/rectangle-element.js +75 -18
- package/dist/elements/row-element.d.ts +19 -1
- package/dist/elements/row-element.js +45 -8
- package/dist/elements/text-element.d.ts +34 -4
- package/dist/elements/text-element.js +40 -17
- package/dist/ir/display-list.d.ts +60 -1
- package/dist/layout/box-constraints.d.ts +8 -0
- package/dist/layout/box-constraints.js +14 -0
- package/dist/layout/collect-images.d.ts +9 -0
- package/dist/layout/collect-images.js +34 -0
- package/dist/layout/fragmentation.d.ts +12 -0
- package/dist/layout/fragmentation.js +45 -8
- package/dist/renderer/anchor-renderer.d.ts +6 -0
- package/dist/renderer/anchor-renderer.js +11 -0
- package/dist/renderer/bookmark-renderer.d.ts +6 -0
- package/dist/renderer/bookmark-renderer.js +11 -0
- package/dist/renderer/keep-together-renderer.d.ts +10 -0
- package/dist/renderer/keep-together-renderer.js +12 -0
- package/dist/renderer/link-renderer.d.ts +6 -0
- package/dist/renderer/link-renderer.js +11 -0
- package/dist/renderer/page-break-renderer.d.ts +14 -0
- package/dist/renderer/page-break-renderer.js +15 -0
- package/dist/renderer/page-builder-renderer.d.ts +6 -0
- package/dist/renderer/page-builder-renderer.js +11 -0
- package/dist/renderer/page-renderer.js +37 -2
- package/dist/renderer/pdf-backend.d.ts +17 -0
- package/dist/renderer/pdf-backend.js +117 -7
- package/dist/renderer/pdf-document-class.js +3 -0
- package/dist/renderer/pdf-document-renderer.d.ts +16 -7
- package/dist/renderer/pdf-document-renderer.js +87 -36
- package/dist/renderer/pdf-renderer.js +53 -2
- package/dist/renderer/rotated-renderer.d.ts +7 -0
- package/dist/renderer/rotated-renderer.js +29 -0
- package/dist/renderer/text-renderer.d.ts +1 -1
- package/dist/renderer/text-renderer.js +123 -54
- package/dist/text/advance.d.ts +34 -0
- package/dist/text/advance.js +42 -0
- package/dist/text/line-breaker.d.ts +9 -8
- package/dist/text/line-breaker.js +28 -21
- package/dist/text/line-metrics.d.ts +49 -0
- package/dist/text/line-metrics.js +57 -0
- package/dist/text/text-decoration.d.ts +50 -0
- package/dist/text/text-decoration.js +62 -0
- package/dist/text/text-style.d.ts +13 -3
- package/dist/text/text-style.js +10 -3
- package/dist/utils/afm-parser.d.ts +34 -0
- package/dist/utils/afm-parser.js +73 -4
- package/dist/utils/dest-registry.d.ts +19 -0
- package/dist/utils/dest-registry.js +32 -0
- package/dist/utils/flex-layout.d.ts +10 -3
- package/dist/utils/flex-layout.js +26 -6
- package/dist/utils/font-metrics.d.ts +14 -0
- package/dist/utils/outline.d.ts +21 -0
- package/dist/utils/outline.js +80 -0
- package/dist/utils/pdf-object-manager.d.ts +33 -1
- package/dist/utils/pdf-object-manager.js +0 -0
- package/dist/utils/ttf-parser.d.ts +53 -0
- package/dist/utils/ttf-parser.js +368 -0
- package/package.json +1 -1
|
@@ -22,6 +22,16 @@ export declare class PdfBackend {
|
|
|
22
22
|
* `PageStructContext` is given (accessible tagging on), each drawable node is wrapped in a marked-content
|
|
23
23
|
* sequence (`/Role <</MCID n>> BDC … EMC`, or `/Artifact` when untagged); graphics-state and empty nodes
|
|
24
24
|
* pass through untouched, so untagged output stays byte-identical. */
|
|
25
|
+
/**
|
|
26
|
+
* Every number reaching the backend must be finite. A non-finite coordinate is a layout bug, but
|
|
27
|
+
* silence turns it into a corrupt PDF: `Infinity` is written into the operator stream verbatim, and a
|
|
28
|
+
* viewer then discards everything from that point on - including the footer, which is drawn last. That
|
|
29
|
+
* failure is invisible until somebody opens the file, so we refuse instead.
|
|
30
|
+
*
|
|
31
|
+
* Checks the node's numbers, not the serialized text: a document containing the WORD "Infinity" is
|
|
32
|
+
* perfectly legal and must not trip this.
|
|
33
|
+
*/
|
|
34
|
+
private static assertFinite;
|
|
25
35
|
static serialize(nodes: IRNode[], om: PDFObjectManager, struct?: PageStructContext): string;
|
|
26
36
|
/**
|
|
27
37
|
* Escapes a string for a PDF literal string `( ... )`. The backslash must be doubled
|
|
@@ -29,6 +39,13 @@ export declare class PdfBackend {
|
|
|
29
39
|
* text closes the string early and the remaining characters leak as raw operators.
|
|
30
40
|
*/
|
|
31
41
|
static escapePdfString(text: string): string;
|
|
42
|
+
/**
|
|
43
|
+
* Builds the `[ ... ]` operand of a `TJ` from a run and its per-gap kern adjustments (em/1000, the
|
|
44
|
+
* sign the font declares - negative tightens). A `TJ` number moves the pen LEFT, so it is the
|
|
45
|
+
* NEGATED kern. Consecutive un-kerned glyphs stay in one encoded chunk, so `[(T) 40 (otal)]` rather
|
|
46
|
+
* than one chunk per glyph. `kerns[i]` is the adjustment AFTER code point `i`.
|
|
47
|
+
*/
|
|
48
|
+
static kernedArray(text: string, kerns: number[], encode: (chunk: string) => string): string;
|
|
32
49
|
/**
|
|
33
50
|
* Returns the `/GSx gs` operator that selects a transparency state, or `""` when both
|
|
34
51
|
* alphas are fully opaque. Opaque draws emit nothing here, so output stays
|
|
@@ -62,6 +62,28 @@ export class PdfBackend {
|
|
|
62
62
|
: { ...node.fill, y0: pageHeight - node.fill.y0, y1: pageHeight - node.fill.y1 };
|
|
63
63
|
return { ...node, commands, fill };
|
|
64
64
|
}
|
|
65
|
+
case "link":
|
|
66
|
+
// A link's clickable rect flips around its bottom edge, exactly like a rect.
|
|
67
|
+
return { ...node, y: pageHeight - node.y - node.height };
|
|
68
|
+
case "outline":
|
|
69
|
+
// An outline anchor is a single point (the target's top); flip it like a text baseline.
|
|
70
|
+
return { ...node, y: pageHeight - node.y };
|
|
71
|
+
case "anchor":
|
|
72
|
+
// A named-destination anchor is a single point (the target's top), flipped like a baseline.
|
|
73
|
+
return { ...node, y: pageHeight - node.y };
|
|
74
|
+
case "transform-push": {
|
|
75
|
+
// The child nodes are flipped from top-left to bottom-left by F = [1,0,0,-1,0,H] (F is its
|
|
76
|
+
// own inverse). For a matrix authored in top-left space to act correctly on them, conjugate
|
|
77
|
+
// it by that flip: M_pdf = F · M · F. Worked out for [a,b,c,d,e,f] with H = pageHeight:
|
|
78
|
+
const [a, b, c, d, e, f] = node.matrix;
|
|
79
|
+
const H = pageHeight;
|
|
80
|
+
return {
|
|
81
|
+
...node,
|
|
82
|
+
matrix: [a, -b, -c, d, H * c + e, H - H * d - f],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
case "transform-pop":
|
|
86
|
+
return node; // no coordinates to flip
|
|
65
87
|
default: {
|
|
66
88
|
const unknown = node;
|
|
67
89
|
return unknown;
|
|
@@ -73,11 +95,49 @@ export class PdfBackend {
|
|
|
73
95
|
* `PageStructContext` is given (accessible tagging on), each drawable node is wrapped in a marked-content
|
|
74
96
|
* sequence (`/Role <</MCID n>> BDC … EMC`, or `/Artifact` when untagged); graphics-state and empty nodes
|
|
75
97
|
* pass through untouched, so untagged output stays byte-identical. */
|
|
98
|
+
/**
|
|
99
|
+
* Every number reaching the backend must be finite. A non-finite coordinate is a layout bug, but
|
|
100
|
+
* silence turns it into a corrupt PDF: `Infinity` is written into the operator stream verbatim, and a
|
|
101
|
+
* viewer then discards everything from that point on - including the footer, which is drawn last. That
|
|
102
|
+
* failure is invisible until somebody opens the file, so we refuse instead.
|
|
103
|
+
*
|
|
104
|
+
* Checks the node's numbers, not the serialized text: a document containing the WORD "Infinity" is
|
|
105
|
+
* perfectly legal and must not trip this.
|
|
106
|
+
*/
|
|
107
|
+
static assertFinite(node) {
|
|
108
|
+
const finite = (value) => {
|
|
109
|
+
if (typeof value === "number")
|
|
110
|
+
return Number.isFinite(value);
|
|
111
|
+
if (Array.isArray(value))
|
|
112
|
+
return value.every(finite);
|
|
113
|
+
if (value !== null && typeof value === "object")
|
|
114
|
+
return Object.values(value).every(finite);
|
|
115
|
+
return true;
|
|
116
|
+
};
|
|
117
|
+
if (!finite(node)) {
|
|
118
|
+
throw new Error(`Layout produced a non-finite number on a "${node.type}" node, refusing to emit a corrupt ` +
|
|
119
|
+
`content stream. This is a bug in an element's calculateLayout (a size resolved to Infinity ` +
|
|
120
|
+
`or NaN), not in your document.`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
76
123
|
static serialize(nodes, om, struct) {
|
|
77
124
|
return nodes
|
|
78
125
|
.map((node) => {
|
|
126
|
+
PdfBackend.assertFinite(node);
|
|
79
127
|
const ops = PdfBackend.serializeNode(node, om);
|
|
80
|
-
|
|
128
|
+
// Two kinds of node skip the marked-content wrapper, both because they carry no tag and never
|
|
129
|
+
// draw: GRAPHICS-STATE nodes (clip / transform push+pop) only save/restore state around the
|
|
130
|
+
// drawables they enclose, and SIDE-CHANNEL nodes (link, outline, anchor) become annotations /
|
|
131
|
+
// catalog entries instead of content-stream operators.
|
|
132
|
+
if (!struct ||
|
|
133
|
+
node.type === "clip-push" ||
|
|
134
|
+
node.type === "clip-pop" ||
|
|
135
|
+
node.type === "transform-push" ||
|
|
136
|
+
node.type === "transform-pop" ||
|
|
137
|
+
node.type === "link" ||
|
|
138
|
+
node.type === "outline" ||
|
|
139
|
+
node.type === "anchor" ||
|
|
140
|
+
ops === "")
|
|
81
141
|
return ops;
|
|
82
142
|
const { open, close } = struct.mark(node.tag);
|
|
83
143
|
return open + ops + close;
|
|
@@ -92,6 +152,27 @@ export class PdfBackend {
|
|
|
92
152
|
static escapePdfString(text) {
|
|
93
153
|
return text.replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)");
|
|
94
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Builds the `[ ... ]` operand of a `TJ` from a run and its per-gap kern adjustments (em/1000, the
|
|
157
|
+
* sign the font declares - negative tightens). A `TJ` number moves the pen LEFT, so it is the
|
|
158
|
+
* NEGATED kern. Consecutive un-kerned glyphs stay in one encoded chunk, so `[(T) 40 (otal)]` rather
|
|
159
|
+
* than one chunk per glyph. `kerns[i]` is the adjustment AFTER code point `i`.
|
|
160
|
+
*/
|
|
161
|
+
static kernedArray(text, kerns, encode) {
|
|
162
|
+
const chars = [...text];
|
|
163
|
+
let out = "";
|
|
164
|
+
let chunk = chars[0] ?? "";
|
|
165
|
+
for (let i = 0; i < kerns.length; i++) {
|
|
166
|
+
if (kerns[i] === 0) {
|
|
167
|
+
chunk += chars[i + 1];
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
out += encode(chunk) + ` ${-kerns[i]} `;
|
|
171
|
+
chunk = chars[i + 1];
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return `[${out}${encode(chunk)}]`;
|
|
175
|
+
}
|
|
95
176
|
/**
|
|
96
177
|
* Returns the `/GSx gs` operator that selects a transparency state, or `""` when both
|
|
97
178
|
* alphas are fully opaque. Opaque draws emit nothing here, so output stays
|
|
@@ -182,18 +263,31 @@ export class PdfBackend {
|
|
|
182
263
|
const font = isCustom
|
|
183
264
|
? om.getCustomFontResource(node.fontFamily, node.fontStyle)
|
|
184
265
|
: om.registerFont(node.fontFamily, node.fontStyle);
|
|
185
|
-
const
|
|
186
|
-
? `<${om.encodeCustomText(node.fontFamily,
|
|
187
|
-
: `(${PdfBackend.escapePdfString(
|
|
266
|
+
const encode = (t) => isCustom
|
|
267
|
+
? `<${om.encodeCustomText(node.fontFamily, t, node.fontStyle)}>`
|
|
268
|
+
: `(${PdfBackend.escapePdfString(t)})`;
|
|
269
|
+
// Kerning (if the document has it on): a `TJ` array with the font's per-pair adjustments
|
|
270
|
+
// between glyph chunks, measured into the layout by the SAME numbers (runAdvance). A plain
|
|
271
|
+
// `Tj` when the run has no kerning, byte-identical.
|
|
272
|
+
const kerns = om.kerningEnabled
|
|
273
|
+
? om.getKernPairs(node.text, node.fontFamily, node.fontStyle)
|
|
274
|
+
: [];
|
|
275
|
+
const showOp = kerns.some((k) => k !== 0)
|
|
276
|
+
? `${PdfBackend.kernedArray(node.text, kerns, encode)} TJ`
|
|
277
|
+
: `${encode(node.text)} Tj`;
|
|
278
|
+
// letterSpacing is the `Tc` operator: extra advance after EVERY glyph (an embedded
|
|
279
|
+
// Identity-H font too - that is `Tw`, word spacing, which only touches single-byte code 32).
|
|
280
|
+
const spacing = node.letterSpacing ? `${node.letterSpacing.toFixed(3)} Tc\n` : "";
|
|
188
281
|
const block = `BT\n` +
|
|
189
282
|
`${node.color.toPDFColorString()} rg ` +
|
|
190
283
|
`/F${font.fontIndex} ${node.fontSize} Tf ` +
|
|
191
284
|
`${node.x.toFixed(3)} ${node.y.toFixed(3)} Td ` +
|
|
192
|
-
`${
|
|
285
|
+
`${showOp}\n` +
|
|
193
286
|
`ET\n`;
|
|
194
|
-
// Transparent text gets an isolating q/Q + gs; opaque text is byte-identical.
|
|
195
287
|
const gs = PdfBackend.alphaPrefix(om, node.color.getAlpha(), 1);
|
|
196
|
-
|
|
288
|
+
// `Tc` is graphics state and would leak into the next run, so isolate it in q/Q - the same
|
|
289
|
+
// reason transparent text is isolated. A run with neither stays byte-identical.
|
|
290
|
+
return gs || spacing ? `q\n${gs}${spacing}${block}Q\n` : block;
|
|
197
291
|
}
|
|
198
292
|
case "image": {
|
|
199
293
|
// The backend owns PDF resource creation: register the XObject (using the
|
|
@@ -247,6 +341,22 @@ export class PdfBackend {
|
|
|
247
341
|
}
|
|
248
342
|
case "clip-pop":
|
|
249
343
|
return `Q\n`;
|
|
344
|
+
case "transform-push": {
|
|
345
|
+
// Save the graphics state, then apply the affine; everything until transform-pop paints through it.
|
|
346
|
+
const f = (n) => n.toFixed(3);
|
|
347
|
+
return `q\n${node.matrix.map(f).join(" ")} cm\n`;
|
|
348
|
+
}
|
|
349
|
+
case "transform-pop":
|
|
350
|
+
return `Q\n`;
|
|
351
|
+
case "link":
|
|
352
|
+
// A link draws nothing in the content stream - it becomes a page /Annot (built in PageRenderer).
|
|
353
|
+
return "";
|
|
354
|
+
case "outline":
|
|
355
|
+
// An outline anchor draws nothing - it becomes a /Outlines entry (built in PageRenderer/PDFRenderer).
|
|
356
|
+
return "";
|
|
357
|
+
case "anchor":
|
|
358
|
+
// A named destination draws nothing - it becomes a /Names /Dests entry (built in PageRenderer/PDFRenderer).
|
|
359
|
+
return "";
|
|
250
360
|
default: {
|
|
251
361
|
// Exhaustiveness guard: if a new IRNode variant is added, this fails to compile.
|
|
252
362
|
const unknown = node;
|
|
@@ -88,6 +88,9 @@ export class PDFDocument {
|
|
|
88
88
|
}
|
|
89
89
|
if (config)
|
|
90
90
|
this._objectManager.changePDFConfig(config);
|
|
91
|
+
// Kerning is on by default at the document level (the `renderToBytes` path sets the same). A
|
|
92
|
+
// bare `PDFObjectManager` still defaults OFF, so unit tests keep predictable un-kerned metrics.
|
|
93
|
+
this._objectManager.setKerning(true);
|
|
91
94
|
}
|
|
92
95
|
get objectManager() {
|
|
93
96
|
return this._objectManager;
|
|
@@ -4,16 +4,25 @@ import { PDFObjectManager } from "../utils/pdf-object-manager.js";
|
|
|
4
4
|
export declare class PDFDocumentRenderer {
|
|
5
5
|
static render(document: PDFDocumentElement, objectManager: PDFObjectManager, ctx: LayoutContext): Promise<number>;
|
|
6
6
|
/**
|
|
7
|
-
*
|
|
7
|
+
* The page geometry a physical page will use. `PageElement.calculateLayout` has already folded the
|
|
8
|
+
* document defaults into every page's config by the time we get here (`PDFRenderer` lays the document
|
|
9
|
+
* out before it calls us, and it is our only caller). Merging again is therefore a no-op today - it is
|
|
10
|
+
* here so this stays correct BY CONSTRUCTION rather than by call order: were that order ever changed,
|
|
11
|
+
* an unmerged config would otherwise make `resolvePageSize` fall back to A4 and quietly report the
|
|
12
|
+
* wrong page size.
|
|
13
|
+
*/
|
|
14
|
+
private static configOf;
|
|
15
|
+
/**
|
|
16
|
+
* Splits one logical page into the physical pages it will occupy, without rendering.
|
|
8
17
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
18
|
+
* Only the common shape auto-paginates - a page whose single child is a fragmentation context
|
|
19
|
+
* (a Container). Anything else stays a single page on the unchanged path, so non-overflowing
|
|
20
|
+
* documents keep producing byte-identical output.
|
|
12
21
|
*/
|
|
13
|
-
private static
|
|
22
|
+
private static paginateLogicalPage;
|
|
14
23
|
/**
|
|
15
|
-
* Lays out one fragment
|
|
16
|
-
* header/footer are attached to every physical page so they repeat
|
|
24
|
+
* Lays out one physical page and renders it. A fragment gets a fresh `PageElement` of the same
|
|
25
|
+
* geometry; the header/footer are attached to every physical page so they repeat, and `PageElement`
|
|
17
26
|
* re-places them and the body in the band between.
|
|
18
27
|
*/
|
|
19
28
|
private static renderPhysicalPage;
|
|
@@ -1,21 +1,36 @@
|
|
|
1
|
-
import { layoutPageBands, PageElement } from "../elements/page-element.js";
|
|
1
|
+
import { layoutPageBands, pageFrame, PageElement, resolvePageSize, } from "../elements/page-element.js";
|
|
2
2
|
import { BoxConstraints } from "../layout/box-constraints.js";
|
|
3
|
-
import { isFragmentable } from "../layout/fragmentation.js";
|
|
3
|
+
import { isFragmentable, reportOverflow } from "../layout/fragmentation.js";
|
|
4
4
|
import { PageRenderer } from "./page-renderer.js";
|
|
5
5
|
export class PDFDocumentRenderer {
|
|
6
6
|
static async render(document, objectManager, ctx) {
|
|
7
|
-
const pageNumbers = [];
|
|
8
7
|
// Add the pages object first... we need its object number (resources). The count is
|
|
9
8
|
// a placeholder; it is replaced below with the real (post-pagination) page count.
|
|
10
9
|
const pagesObject = `<< /Type /Pages /Kids [] /Count ${document.getProps().children.length} >>`;
|
|
11
10
|
const pagesObjectNumber = objectManager.addObject(pagesObject);
|
|
12
11
|
// Now set the given object number all its childs
|
|
13
12
|
objectManager.setParentObjectNumber(pagesObjectNumber);
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
// Pass A - paginate the whole document WITHOUT drawing anything. Fragmentation is synchronous and
|
|
14
|
+
// pure (`{ fitted, remainder }`), so the full list of physical pages can be settled up front. Only
|
|
15
|
+
// then is the total page count known, which is what page numbers in a header/footer need.
|
|
16
|
+
const physicalPages = [];
|
|
17
|
+
for (const page of document.getProps().children) {
|
|
18
|
+
physicalPages.push(...PDFDocumentRenderer.paginateLogicalPage(page, ctx));
|
|
19
|
+
}
|
|
20
|
+
// Pass B - draw them, in order, so the emitted page objects keep their previous numbering. Each page
|
|
21
|
+
// is laid out again with its own PageInfo, which is how a `PageBuilder` anywhere in the tree (header,
|
|
22
|
+
// footer or body) learns its final page number and the now-known document total.
|
|
23
|
+
const pageNumbers = [];
|
|
24
|
+
for (const [index, physical] of physicalPages.entries()) {
|
|
25
|
+
const pageInfo = {
|
|
26
|
+
pageNumber: index + 1,
|
|
27
|
+
pageCount: physicalPages.length,
|
|
28
|
+
pageSize: resolvePageSize(PDFDocumentRenderer.configOf(physical, ctx)),
|
|
29
|
+
};
|
|
30
|
+
pageNumbers.push(await PDFDocumentRenderer.renderPhysicalPage(physical, objectManager, {
|
|
31
|
+
...ctx,
|
|
32
|
+
pageInfo,
|
|
33
|
+
}));
|
|
19
34
|
}
|
|
20
35
|
// We must update the pages object with the real physical page numbers and count.
|
|
21
36
|
const updatedPagesObject = `<< /Type /Pages /Kids [${pageNumbers
|
|
@@ -26,65 +41,101 @@ export class PDFDocumentRenderer {
|
|
|
26
41
|
return pagesObjectNumber;
|
|
27
42
|
}
|
|
28
43
|
/**
|
|
29
|
-
*
|
|
44
|
+
* The page geometry a physical page will use. `PageElement.calculateLayout` has already folded the
|
|
45
|
+
* document defaults into every page's config by the time we get here (`PDFRenderer` lays the document
|
|
46
|
+
* out before it calls us, and it is our only caller). Merging again is therefore a no-op today - it is
|
|
47
|
+
* here so this stays correct BY CONSTRUCTION rather than by call order: were that order ever changed,
|
|
48
|
+
* an unmerged config would otherwise make `resolvePageSize` fall back to A4 and quietly report the
|
|
49
|
+
* wrong page size.
|
|
50
|
+
*/
|
|
51
|
+
static configOf(physical, ctx) {
|
|
52
|
+
const config = physical.kind === "whole" ? physical.page.getProps().config : physical.config;
|
|
53
|
+
return { ...ctx.pageConfig, ...config };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Splits one logical page into the physical pages it will occupy, without rendering.
|
|
30
57
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
58
|
+
* Only the common shape auto-paginates - a page whose single child is a fragmentation context
|
|
59
|
+
* (a Container). Anything else stays a single page on the unchanged path, so non-overflowing
|
|
60
|
+
* documents keep producing byte-identical output.
|
|
34
61
|
*/
|
|
35
|
-
static
|
|
62
|
+
static paginateLogicalPage(page, ctx) {
|
|
36
63
|
const { children, config, header, footer } = page.getProps();
|
|
37
64
|
if (children.length !== 1 || !isFragmentable(children[0])) {
|
|
38
|
-
return [
|
|
65
|
+
return [{ kind: "whole", page }];
|
|
39
66
|
}
|
|
40
67
|
// Header/footer repeat on every physical page, so the body only ever flows into the
|
|
41
68
|
// band between them. Resolve that band once (config is already merged by pass 1).
|
|
69
|
+
// The frame is a throwaway: this pass only wants the band HEIGHTS, and an out-of-flow child
|
|
70
|
+
// contributes none. It exists because a `Positioned` in a band demands one; pass 2 builds the
|
|
71
|
+
// real frame (in `PageElement`) and drains it.
|
|
42
72
|
const pageCtx = {
|
|
43
73
|
metrics: ctx.metrics,
|
|
44
74
|
pageConfig: config,
|
|
45
75
|
textStyle: ctx.textStyle,
|
|
46
76
|
onOverflow: ctx.onOverflow,
|
|
77
|
+
frame: pageFrame(config),
|
|
47
78
|
};
|
|
48
79
|
const { bodyWidth: width, bodyHeight: height } = layoutPageBands(config, header, footer, pageCtx);
|
|
49
|
-
|
|
80
|
+
// A `keepTogether` group compares its height against a FULL fresh page (this band), so thread it in.
|
|
81
|
+
pageCtx.pageBodyHeight = height;
|
|
82
|
+
const pages = [];
|
|
50
83
|
let region = children[0];
|
|
51
84
|
let isFirstRegion = true;
|
|
52
85
|
while (region) {
|
|
53
86
|
if (!isFragmentable(region)) {
|
|
54
87
|
// A non-fragmentable remainder is placed whole on its own page.
|
|
55
|
-
|
|
88
|
+
pages.push({ kind: "fragment", config, content: region, header, footer });
|
|
56
89
|
break;
|
|
57
90
|
}
|
|
58
|
-
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
91
|
+
// pageCtx, not the document ctx: a descendant that reads `pageConfig` while being measured (a
|
|
92
|
+
// `PageBuilder` sizing its provisional build) must see THIS page's geometry, not the document default.
|
|
93
|
+
const { fitted, remainder, forceBreak } = region.fragment(height, width, pageCtx);
|
|
94
|
+
// Everything fits on one page: keep the ORIGINAL page so output is unchanged. Measuring inside
|
|
95
|
+
// fragment() left its children at the measuring origin; pass B lays the page out again, which
|
|
96
|
+
// restores their real positions (layout is deterministic). A consumed trailing `PageBreak`
|
|
97
|
+
// (forceBreak with no remainder) is the exception: render the packed `fitted` instead, which no
|
|
98
|
+
// longer holds the break marker, so the original with the break does not leak into the render pass.
|
|
99
|
+
if (isFirstRegion && remainder === null && !forceBreak) {
|
|
100
|
+
pages.push({ kind: "whole", page });
|
|
65
101
|
break;
|
|
66
102
|
}
|
|
67
|
-
|
|
68
|
-
|
|
103
|
+
// TERMINATION GUARANTEE. Every page here has the full body height, so `fitted === null` means
|
|
104
|
+
// nothing fit even on a whole page - the region did not get smaller. Advancing to the
|
|
105
|
+
// (identical) remainder would loop forever. So we stop: place the region whole (clipped to the
|
|
106
|
+
// page) and surface it per the overflow policy. A step that shrinks nothing ends the loop, for
|
|
107
|
+
// ANY region - an oversized unbreakable block, a future keep-together group, or an engine bug.
|
|
108
|
+
if (fitted === null) {
|
|
109
|
+
// Measure the region's true height for the message (rare path, so the extra pass is free);
|
|
110
|
+
// pass B lays it out again, so this mutation does not leak.
|
|
111
|
+
const needed = region.calculateLayout(BoxConstraints.loose(width, Infinity), { x: 0, y: 0 }, pageCtx).height;
|
|
112
|
+
reportOverflow(region, needed, height, pageCtx.onOverflow ?? "ignore");
|
|
113
|
+
pages.push({ kind: "fragment", config, content: region, header, footer });
|
|
114
|
+
break;
|
|
69
115
|
}
|
|
116
|
+
pages.push({ kind: "fragment", config, content: fitted, header, footer });
|
|
70
117
|
region = remainder;
|
|
71
118
|
isFirstRegion = false;
|
|
72
119
|
}
|
|
73
|
-
return
|
|
120
|
+
return pages;
|
|
74
121
|
}
|
|
75
122
|
/**
|
|
76
|
-
* Lays out one fragment
|
|
77
|
-
* header/footer are attached to every physical page so they repeat
|
|
123
|
+
* Lays out one physical page and renders it. A fragment gets a fresh `PageElement` of the same
|
|
124
|
+
* geometry; the header/footer are attached to every physical page so they repeat, and `PageElement`
|
|
78
125
|
* re-places them and the body in the band between.
|
|
79
126
|
*/
|
|
80
|
-
static async renderPhysicalPage(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
127
|
+
static async renderPhysicalPage(physical, objectManager, ctx) {
|
|
128
|
+
if (physical.kind === "whole") {
|
|
129
|
+
physical.page.calculateLayout(new BoxConstraints(), { x: 0, y: 0 }, ctx);
|
|
130
|
+
return PageRenderer.render(physical.page, objectManager);
|
|
131
|
+
}
|
|
132
|
+
const page = new PageElement({
|
|
133
|
+
config: physical.config,
|
|
134
|
+
header: physical.header,
|
|
135
|
+
footer: physical.footer,
|
|
136
|
+
children: [physical.content],
|
|
86
137
|
});
|
|
87
|
-
|
|
88
|
-
return PageRenderer.render(
|
|
138
|
+
page.calculateLayout(new BoxConstraints(), { x: 0, y: 0 }, ctx);
|
|
139
|
+
return PageRenderer.render(page, objectManager);
|
|
89
140
|
}
|
|
90
141
|
}
|
|
@@ -21,7 +21,24 @@ import { PositionedElement } from "../elements/layout/positioned-element.js";
|
|
|
21
21
|
import { PositionedRenderer } from "./positioned-renderer.js";
|
|
22
22
|
import { StructGroup } from "../elements/layout/struct-group.js";
|
|
23
23
|
import { StructGroupRenderer } from "./struct-group-renderer.js";
|
|
24
|
+
import { LinkElement } from "../elements/layout/link-element.js";
|
|
25
|
+
import { LinkRenderer } from "./link-renderer.js";
|
|
26
|
+
import { BookmarkElement } from "../elements/layout/bookmark-element.js";
|
|
27
|
+
import { BookmarkRenderer } from "./bookmark-renderer.js";
|
|
28
|
+
import { AnchorElement } from "../elements/layout/anchor-element.js";
|
|
29
|
+
import { PageBreakElement } from "../elements/layout/page-break-element.js";
|
|
30
|
+
import { AnchorRenderer } from "./anchor-renderer.js";
|
|
31
|
+
import { PageBreakRenderer } from "./page-break-renderer.js";
|
|
32
|
+
import { KeepTogetherElement } from "../elements/layout/keep-together-element.js";
|
|
33
|
+
import { KeepTogetherRenderer } from "./keep-together-renderer.js";
|
|
34
|
+
import { PageBuilderElement } from "../elements/layout/page-builder-element.js";
|
|
35
|
+
import { PageBuilderRenderer } from "./page-builder-renderer.js";
|
|
36
|
+
import { RotatedElement } from "../elements/layout/rotated-element.js";
|
|
37
|
+
import { RotatedBoxElement } from "../elements/layout/rotated-box-element.js";
|
|
38
|
+
import { RotatedRenderer } from "./rotated-renderer.js";
|
|
39
|
+
import { PdfBackend } from "./pdf-backend.js";
|
|
24
40
|
import { BoxConstraints } from "../layout/box-constraints.js";
|
|
41
|
+
import { collectImageElements } from "../layout/collect-images.js";
|
|
25
42
|
import { DEFAULT_TEXT_STYLE, mergeTextStyle } from "../text/text-style.js";
|
|
26
43
|
export class PDFRenderer {
|
|
27
44
|
static async render(document, objectManager) {
|
|
@@ -32,6 +49,8 @@ export class PDFRenderer {
|
|
|
32
49
|
RendererRegistry.register(RectangleElement, RectangleRenderer.render);
|
|
33
50
|
RendererRegistry.register(ExpandedElement, ExpandedRenderer.render);
|
|
34
51
|
RendererRegistry.register(PaddingElement, PaddingRenderer.render);
|
|
52
|
+
RendererRegistry.register(PageBreakElement, PageBreakRenderer.render);
|
|
53
|
+
RendererRegistry.register(KeepTogetherElement, KeepTogetherRenderer.render);
|
|
35
54
|
RendererRegistry.register(DefaultTextStyleElement, DefaultTextStyleRenderer.render);
|
|
36
55
|
RendererRegistry.register(ImageElement, ImageRenderer.render);
|
|
37
56
|
RendererRegistry.register(LineElement, LineRenderer.render);
|
|
@@ -39,6 +58,12 @@ export class PDFRenderer {
|
|
|
39
58
|
RendererRegistry.register(DeferredElement, DeferredRenderer.render);
|
|
40
59
|
RendererRegistry.register(PositionedElement, PositionedRenderer.render);
|
|
41
60
|
RendererRegistry.register(StructGroup, StructGroupRenderer.render);
|
|
61
|
+
RendererRegistry.register(LinkElement, LinkRenderer.render);
|
|
62
|
+
RendererRegistry.register(BookmarkElement, BookmarkRenderer.render);
|
|
63
|
+
RendererRegistry.register(AnchorElement, AnchorRenderer.render);
|
|
64
|
+
RendererRegistry.register(PageBuilderElement, PageBuilderRenderer.render);
|
|
65
|
+
RendererRegistry.register(RotatedElement, RotatedRenderer.render);
|
|
66
|
+
RendererRegistry.register(RotatedBoxElement, RotatedRenderer.render);
|
|
42
67
|
let pdfContent = "";
|
|
43
68
|
// Header: version line + the PDF/A binary marker (the object manager owns it so its length
|
|
44
69
|
// matches the xref offset calculation).
|
|
@@ -51,6 +76,11 @@ export class PDFRenderer {
|
|
|
51
76
|
textStyle: mergeTextStyle(DEFAULT_TEXT_STYLE, document.getDefaultTextStyle()),
|
|
52
77
|
onOverflow: objectManager.getOverflowPolicy(),
|
|
53
78
|
};
|
|
79
|
+
// Pre-layout: resolve every image's intrinsic pixel size (async), so the synchronous layout can
|
|
80
|
+
// give a width-only image a proportional height. init() is idempotent, so the renderer reuses it.
|
|
81
|
+
const images = collectImageElements(document);
|
|
82
|
+
if (images.length > 0)
|
|
83
|
+
await Promise.all(images.map((img) => img.resolveIntrinsicSize()));
|
|
54
84
|
document.calculateLayout(new BoxConstraints(), { x: 0, y: 0 }, ctx);
|
|
55
85
|
// Render pages and contents (the driver paginates overflowing pages).
|
|
56
86
|
await PDFDocumentRenderer.render(document, objectManager, ctx);
|
|
@@ -66,11 +96,20 @@ export class PDFRenderer {
|
|
|
66
96
|
if (outputIntent) {
|
|
67
97
|
catalogParts.push(`/OutputIntents [${outputIntent} 0 R]`);
|
|
68
98
|
}
|
|
99
|
+
// The catalog has exactly one /Names dict; embedded files and named destinations are two entries in
|
|
100
|
+
// it, so collect both and emit the /Names once (below).
|
|
101
|
+
const namesParts = [];
|
|
69
102
|
const attachments = objectManager.getAttachments();
|
|
70
103
|
if (attachments.length > 0) {
|
|
71
|
-
|
|
104
|
+
// The name-tree key is a PDF literal string, so it needs the same escaping the /Filespec's /F and
|
|
105
|
+
// /UF get in attachFile(). Unescaped, a ")" or "\" in a file name closes the string early and the
|
|
106
|
+
// rest of it leaks out as raw operators.
|
|
107
|
+
const names = attachments
|
|
108
|
+
.map((a) => `(${PdfBackend.escapePdfString(a.name)}) ${a.filespec} 0 R`)
|
|
109
|
+
.join(" ");
|
|
72
110
|
const af = attachments.map((a) => `${a.filespec} 0 R`).join(" ");
|
|
73
|
-
catalogParts.push(`/AF [${af}]
|
|
111
|
+
catalogParts.push(`/AF [${af}]`);
|
|
112
|
+
namesParts.push(`/EmbeddedFiles << /Names [${names}] >>`);
|
|
74
113
|
}
|
|
75
114
|
// Accessible tagging: finalize the structure tree (emits StructTreeRoot + StructElems + ParentTree) and
|
|
76
115
|
// fold /MarkInfo + /StructTreeRoot + /Lang into the catalog. Returns "" (no-op) when tagging is off.
|
|
@@ -80,6 +119,18 @@ export class PDFRenderer {
|
|
|
80
119
|
// PDF/UA requires the viewer to show the document title (not the file name).
|
|
81
120
|
catalogParts.push("/ViewerPreferences << /DisplayDocTitle true >>");
|
|
82
121
|
}
|
|
122
|
+
// Document outline (bookmarks): emit the /Outlines tree collected during page rendering. Returns
|
|
123
|
+
// "" (no-op) when no Bookmark was placed, so a plain document's catalog is unchanged.
|
|
124
|
+
const outlineCatalog = objectManager.outline.finalize(objectManager);
|
|
125
|
+
if (outlineCatalog)
|
|
126
|
+
catalogParts.push(outlineCatalog);
|
|
127
|
+
// Named destinations (internal-link targets): a /Dests entry in the shared /Names dict.
|
|
128
|
+
const destsNames = objectManager.dests.finalize();
|
|
129
|
+
if (destsNames)
|
|
130
|
+
namesParts.push(destsNames);
|
|
131
|
+
// Emit the single /Names dict if either embedded files or destinations contributed to it.
|
|
132
|
+
if (namesParts.length > 0)
|
|
133
|
+
catalogParts.push(`/Names << ${namesParts.join(" ")} >>`);
|
|
83
134
|
const catalogObject = `<< ${catalogParts.join(" ")} >>`;
|
|
84
135
|
objectManager.addObject(catalogObject);
|
|
85
136
|
// Now that the render pass has revealed which glyphs each embedded font uses, fill the reserved
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { PDFObjectManager } from "../utils/pdf-object-manager.js";
|
|
2
|
+
import { RotatedElement } from "../elements/layout/rotated-element.js";
|
|
3
|
+
import { RotatedBoxElement } from "../elements/layout/rotated-box-element.js";
|
|
4
|
+
import { IRNode } from "../ir/display-list.js";
|
|
5
|
+
export declare class RotatedRenderer {
|
|
6
|
+
static render(element: RotatedElement | RotatedBoxElement, objectManager: PDFObjectManager): Promise<IRNode[]>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { RendererRegistry } from "../utils/renderer-registry.js";
|
|
2
|
+
export class RotatedRenderer {
|
|
3
|
+
// Both `Rotated` (paint-only) and `RotatedBox` (layout-aware quarter-turns) expose the same
|
|
4
|
+
// `{ angle, child, x, y, width, height }` and rotate the child around the box center - shared here.
|
|
5
|
+
static async render(element, objectManager) {
|
|
6
|
+
const { angle, child, x, y, width, height } = element.getProps();
|
|
7
|
+
// Rotate around the box CENTER, in the engine's top-left coordinates (the IR->backend seam flips
|
|
8
|
+
// the matrix to PDF space per page). A positive angle reads clockwise on the page.
|
|
9
|
+
const cx = x + width / 2;
|
|
10
|
+
const cy = y + height / 2;
|
|
11
|
+
const theta = (angle * Math.PI) / 180;
|
|
12
|
+
const cos = Math.cos(theta);
|
|
13
|
+
const sin = Math.sin(theta);
|
|
14
|
+
// M = T(cx,cy) · R(theta) · T(-cx,-cy) as a PDF cm [a,b,c,d,e,f]: the linear part is the rotation,
|
|
15
|
+
// the translation keeps the center fixed.
|
|
16
|
+
const matrix = [
|
|
17
|
+
cos,
|
|
18
|
+
sin,
|
|
19
|
+
-sin,
|
|
20
|
+
cos,
|
|
21
|
+
cx - cos * cx + sin * cy,
|
|
22
|
+
cy - sin * cx - cos * cy,
|
|
23
|
+
];
|
|
24
|
+
const renderer = RendererRegistry.getRenderer(child);
|
|
25
|
+
const childNodes = renderer ? await renderer(child, objectManager) : [];
|
|
26
|
+
// Wrap the child's drawing between a push (apply the matrix) and a pop (restore).
|
|
27
|
+
return [{ type: "transform-push", matrix }, ...childNodes, { type: "transform-pop" }];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -4,7 +4,7 @@ import type { FontMetrics } from "../utils/font-metrics.js";
|
|
|
4
4
|
import { IRNode } from "../ir/display-list.js";
|
|
5
5
|
import { TextOverflow } from "../text/line-breaker.js";
|
|
6
6
|
export declare class TextRenderer {
|
|
7
|
-
static calculateTextHeight(content: string | TextSegment[], fontSize: number, fontFamily: string, fontStyle: FontStyle, objectManager: FontMetrics, maxWidth: number, maxLines?: number, overflow?: TextOverflow, lineHeight?: number): number;
|
|
7
|
+
static calculateTextHeight(content: string | TextSegment[], fontSize: number, fontFamily: string, fontStyle: FontStyle, objectManager: FontMetrics, maxWidth: number, maxLines?: number, overflow?: TextOverflow, lineHeight?: number, letterSpacing?: number): number;
|
|
8
8
|
static render(textElement: TextElement, objectManager: PDFObjectManager): Promise<IRNode[]>;
|
|
9
9
|
private static _expandColorGlyphs;
|
|
10
10
|
private static _glyphToPath;
|