pdf-codec 1.3.0 → 1.4.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.
Files changed (198) hide show
  1. package/README.md +38 -0
  2. package/dist/afm-widths-BoeTOK2r.cjs +826 -0
  3. package/dist/afm-widths-Dxucrg7D.js +779 -0
  4. package/dist/afm-widths-DyDq56Ph.d.cts +19 -0
  5. package/dist/afm-widths-DyDq56Ph.d.ts +19 -0
  6. package/dist/afm-widths.cjs +4 -0
  7. package/dist/afm-widths.d.cts +2 -0
  8. package/dist/afm-widths.d.ts +2 -0
  9. package/dist/afm-widths.js +2 -0
  10. package/dist/assets/stix-two-math-font.cjs +5 -0
  11. package/dist/assets/stix-two-math-font.d.cts +4 -0
  12. package/dist/assets/stix-two-math-font.d.ts +4 -0
  13. package/dist/assets/stix-two-math-font.js +4 -0
  14. package/dist/bytes/crc32.cjs +21 -0
  15. package/dist/bytes/crc32.d.cts +4 -0
  16. package/dist/bytes/crc32.d.ts +4 -0
  17. package/dist/bytes/crc32.js +20 -0
  18. package/dist/bytes/flate.cjs +53 -0
  19. package/dist/bytes/flate.d.cts +12 -0
  20. package/dist/bytes/flate.d.ts +12 -0
  21. package/dist/bytes/flate.js +49 -0
  22. package/dist/bytes/reader.cjs +60 -0
  23. package/dist/bytes/reader.d.cts +20 -0
  24. package/dist/bytes/reader.d.ts +20 -0
  25. package/dist/bytes/reader.js +58 -0
  26. package/dist/bytes/writer.cjs +37 -0
  27. package/dist/bytes/writer.d.cts +13 -0
  28. package/dist/bytes/writer.d.ts +13 -0
  29. package/dist/bytes/writer.js +35 -0
  30. package/dist/cmap.cjs +110 -0
  31. package/dist/cmap.d.cts +8 -0
  32. package/dist/cmap.d.ts +8 -0
  33. package/dist/cmap.js +109 -0
  34. package/dist/codec.cjs +34 -0
  35. package/dist/codec.d.cts +167 -0
  36. package/dist/codec.d.ts +167 -0
  37. package/dist/codec.js +32 -0
  38. package/dist/content-read.cjs +126 -0
  39. package/dist/content-read.d.cts +21 -0
  40. package/dist/content-read.d.ts +21 -0
  41. package/dist/content-read.js +125 -0
  42. package/dist/content-write.cjs +138 -0
  43. package/dist/content-write.d.cts +24 -0
  44. package/dist/content-write.d.ts +24 -0
  45. package/dist/content-write.js +137 -0
  46. package/dist/diagnostics.cjs +21 -0
  47. package/dist/diagnostics.d.cts +19 -0
  48. package/dist/diagnostics.d.ts +19 -0
  49. package/dist/diagnostics.js +18 -0
  50. package/dist/document.cjs +162 -0
  51. package/dist/document.d.cts +12 -0
  52. package/dist/document.d.ts +12 -0
  53. package/dist/document.js +161 -0
  54. package/dist/encoding.cjs +5 -0
  55. package/dist/encoding.d.cts +6 -0
  56. package/dist/encoding.d.ts +6 -0
  57. package/dist/encoding.js +2 -0
  58. package/dist/filters.cjs +223 -0
  59. package/dist/filters.d.cts +14 -0
  60. package/dist/filters.d.ts +14 -0
  61. package/dist/filters.js +218 -0
  62. package/dist/font-read.cjs +199 -0
  63. package/dist/font-read.d.cts +23 -0
  64. package/dist/font-read.d.ts +23 -0
  65. package/dist/font-read.js +198 -0
  66. package/dist/font-style.cjs +35 -0
  67. package/dist/font-style.d.cts +14 -0
  68. package/dist/font-style.d.ts +14 -0
  69. package/dist/font-style.js +34 -0
  70. package/dist/fonts.cjs +124 -0
  71. package/dist/fonts.d.cts +15 -0
  72. package/dist/fonts.d.ts +15 -0
  73. package/dist/fonts.js +122 -0
  74. package/dist/formula.cjs +0 -0
  75. package/dist/formula.d.cts +10 -0
  76. package/dist/formula.d.ts +10 -0
  77. package/dist/formula.js +0 -0
  78. package/dist/image/jpeg-info.cjs +71 -0
  79. package/dist/image/jpeg-info.d.cts +12 -0
  80. package/dist/image/jpeg-info.d.ts +12 -0
  81. package/dist/image/jpeg-info.js +70 -0
  82. package/dist/image/png-decode.cjs +181 -0
  83. package/dist/image/png-decode.d.cts +14 -0
  84. package/dist/image/png-decode.d.ts +14 -0
  85. package/dist/image/png-decode.js +180 -0
  86. package/dist/image/png-encode.cjs +64 -0
  87. package/dist/image/png-encode.d.cts +8 -0
  88. package/dist/image/png-encode.d.ts +8 -0
  89. package/dist/image/png-encode.js +63 -0
  90. package/dist/image/png-filter.cjs +95 -0
  91. package/dist/image/png-filter.d.cts +6 -0
  92. package/dist/image/png-filter.d.ts +6 -0
  93. package/dist/image/png-filter.js +93 -0
  94. package/dist/images-read.cjs +250 -0
  95. package/dist/images-read.d.cts +13 -0
  96. package/dist/images-read.d.ts +13 -0
  97. package/dist/images-read.js +249 -0
  98. package/dist/index.cjs +45 -5912
  99. package/dist/index.d.cts +21 -483
  100. package/dist/index.d.ts +21 -483
  101. package/dist/index.js +18 -5885
  102. package/dist/interpret.cjs +587 -0
  103. package/dist/interpret.d.cts +84 -0
  104. package/dist/interpret.d.ts +84 -0
  105. package/dist/interpret.js +586 -0
  106. package/dist/lexer.cjs +180 -0
  107. package/dist/lexer.d.cts +29 -0
  108. package/dist/lexer.d.ts +29 -0
  109. package/dist/lexer.js +179 -0
  110. package/dist/math-cmap.cjs +81 -0
  111. package/dist/math-cmap.d.cts +6 -0
  112. package/dist/math-cmap.d.ts +6 -0
  113. package/dist/math-cmap.js +80 -0
  114. package/dist/math-content-write.cjs +83 -0
  115. package/dist/math-content-write.d.cts +11 -0
  116. package/dist/math-content-write.d.ts +11 -0
  117. package/dist/math-content-write.js +81 -0
  118. package/dist/math-font-write.cjs +100 -0
  119. package/dist/math-font-write.d.cts +19 -0
  120. package/dist/math-font-write.d.ts +19 -0
  121. package/dist/math-font-write.js +99 -0
  122. package/dist/math-font.cjs +103 -0
  123. package/dist/math-font.d.cts +25 -0
  124. package/dist/math-font.d.ts +25 -0
  125. package/dist/math-font.js +102 -0
  126. package/dist/math-hmtx.cjs +17 -0
  127. package/dist/math-hmtx.d.cts +8 -0
  128. package/dist/math-hmtx.d.ts +8 -0
  129. package/dist/math-hmtx.js +16 -0
  130. package/dist/math-table.cjs +117 -0
  131. package/dist/math-table.d.cts +45 -0
  132. package/dist/math-table.d.ts +45 -0
  133. package/dist/math-table.js +116 -0
  134. package/dist/math-types-Ba8qAf1p.d.cts +82 -0
  135. package/dist/math-types-Ba8qAf1p.d.ts +82 -0
  136. package/dist/math-types.cjs +0 -0
  137. package/dist/math-types.d.cts +2 -0
  138. package/dist/math-types.d.ts +2 -0
  139. package/dist/math-types.js +0 -0
  140. package/dist/matrix-B3c2_a2f.d.cts +18 -0
  141. package/dist/matrix-B3c2_a2f.d.ts +18 -0
  142. package/dist/matrix.cjs +93 -0
  143. package/dist/matrix.d.cts +2 -0
  144. package/dist/matrix.d.ts +2 -0
  145. package/dist/matrix.js +83 -0
  146. package/dist/measure.cjs +54 -0
  147. package/dist/measure.d.cts +20 -0
  148. package/dist/measure.d.ts +20 -0
  149. package/dist/measure.js +53 -0
  150. package/dist/objects.cjs +100 -0
  151. package/dist/objects.d.cts +58 -0
  152. package/dist/objects.d.ts +58 -0
  153. package/dist/objects.js +84 -0
  154. package/dist/parse.cjs +230 -0
  155. package/dist/parse.d.cts +13 -0
  156. package/dist/parse.d.ts +13 -0
  157. package/dist/parse.js +228 -0
  158. package/dist/predictors.cjs +64 -0
  159. package/dist/predictors.d.cts +13 -0
  160. package/dist/predictors.d.ts +13 -0
  161. package/dist/predictors.js +62 -0
  162. package/dist/read.cjs +418 -0
  163. package/dist/read.d.cts +21 -0
  164. package/dist/read.d.ts +21 -0
  165. package/dist/read.js +413 -0
  166. package/dist/serialize.cjs +69 -0
  167. package/dist/serialize.d.cts +8 -0
  168. package/dist/serialize.d.ts +8 -0
  169. package/dist/serialize.js +66 -0
  170. package/dist/sfnt.cjs +52 -0
  171. package/dist/sfnt.d.cts +17 -0
  172. package/dist/sfnt.d.ts +17 -0
  173. package/dist/sfnt.js +46 -0
  174. package/dist/text-layout.cjs +224 -0
  175. package/dist/text-layout.d.cts +37 -0
  176. package/dist/text-layout.d.ts +37 -0
  177. package/dist/text-layout.js +222 -0
  178. package/dist/util/abort.cjs +7 -0
  179. package/dist/util/abort.d.cts +4 -0
  180. package/dist/util/abort.d.ts +4 -0
  181. package/dist/util/abort.js +6 -0
  182. package/dist/util/base64.cjs +48 -0
  183. package/dist/util/base64.d.cts +5 -0
  184. package/dist/util/base64.d.ts +5 -0
  185. package/dist/util/base64.js +46 -0
  186. package/dist/winansi.cjs +5 -0
  187. package/dist/winansi.d.cts +20 -0
  188. package/dist/winansi.d.ts +20 -0
  189. package/dist/winansi.js +2 -0
  190. package/dist/write.cjs +421 -0
  191. package/dist/write.d.cts +16 -0
  192. package/dist/write.d.ts +16 -0
  193. package/dist/write.js +419 -0
  194. package/dist/xref.cjs +325 -0
  195. package/dist/xref.d.cts +21 -0
  196. package/dist/xref.d.ts +21 -0
  197. package/dist/xref.js +324 -0
  198. package/package.json +9 -1
package/dist/write.js ADDED
@@ -0,0 +1,419 @@
1
+ import { a as winAnsiGlyphName, n as widthOfCode, t as STANDARD_METRICS } from "./afm-widths-Dxucrg7D.js";
2
+ import { base64ToBytes } from "./util/base64.js";
3
+ import { ByteWriter, concatBytes } from "./bytes/writer.js";
4
+ import { deflate } from "./bytes/flate.js";
5
+ import { pdfArray, pdfDict, pdfHexString, pdfName, pdfNum, pdfRef, pdfStream } from "./objects.js";
6
+ import { throwIfAborted } from "./util/abort.js";
7
+ import { resolveStandardFont } from "./fonts.js";
8
+ import { readJpegInfo } from "./image/jpeg-info.js";
9
+ import { decodePng } from "./image/png-decode.js";
10
+ import { writeObject } from "./serialize.js";
11
+ import { writeContentStream } from "./content-write.js";
12
+ import { collectUsedGlyphs, writeFormulaContentStream } from "./math-content-write.js";
13
+ import { loadMathFont } from "./math-font.js";
14
+ import { buildMathFontObjects } from "./math-font-write.js";
15
+ import { createStandardFontMeasurer } from "./measure.js";
16
+ //#region src/write.ts
17
+ const MATH_FONT_RESOURCE_NAME = "MF";
18
+ const FIRST_CHAR = 32;
19
+ const LAST_CHAR = 255;
20
+ const NOMINAL_STEM_V_REGULAR = 80;
21
+ const NOMINAL_STEM_V_BOLD = 120;
22
+ const FLAG_FIXED_PITCH = 1;
23
+ const FLAG_SERIF = 2;
24
+ const FLAG_NONSYMBOLIC = 32;
25
+ const FLAG_ITALIC = 64;
26
+ const FLAG_FORCE_BOLD = 262144;
27
+ function textToPdfString(text) {
28
+ const bytes = new Uint8Array(2 + text.length * 2);
29
+ bytes[0] = 254;
30
+ bytes[1] = 255;
31
+ for (let i = 0; i < text.length; i++) {
32
+ const code = text.charCodeAt(i);
33
+ bytes[2 + i * 2] = code >> 8 & 255;
34
+ bytes[2 + i * 2 + 1] = code & 255;
35
+ }
36
+ return pdfHexString(bytes);
37
+ }
38
+ function pad2(n) {
39
+ return n.toString().padStart(2, "0");
40
+ }
41
+ function formatPdfDate(iso) {
42
+ const date = new Date(iso);
43
+ return `D:${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
44
+ }
45
+ function buildInfoDict(doc) {
46
+ const entries = /* @__PURE__ */ new Map();
47
+ entries.set("Producer", textToPdfString("documents.js"));
48
+ if (doc.metadata.title !== void 0) entries.set("Title", textToPdfString(doc.metadata.title));
49
+ if (doc.metadata.author !== void 0) entries.set("Author", textToPdfString(doc.metadata.author));
50
+ if (doc.metadata.subject !== void 0) entries.set("Subject", textToPdfString(doc.metadata.subject));
51
+ if (doc.metadata.keywords !== void 0) entries.set("Keywords", textToPdfString(doc.metadata.keywords.join(", ")));
52
+ if (doc.metadata.creator !== void 0) entries.set("Creator", textToPdfString(doc.metadata.creator));
53
+ if (doc.metadata.createdIso !== void 0) entries.set("CreationDate", textToPdfString(formatPdfDate(doc.metadata.createdIso)));
54
+ if (doc.metadata.modifiedIso !== void 0) entries.set("ModDate", textToPdfString(formatPdfDate(doc.metadata.modifiedIso)));
55
+ return pdfDict(entries);
56
+ }
57
+ function computeFontFlags(standardName, metrics) {
58
+ let flags = FLAG_NONSYMBOLIC;
59
+ if (standardName.startsWith("Courier")) flags |= FLAG_FIXED_PITCH;
60
+ if (standardName.startsWith("Times")) flags |= FLAG_SERIF;
61
+ if (metrics.italicAngle !== 0) flags |= FLAG_ITALIC;
62
+ if (standardName.includes("Bold")) flags |= FLAG_FORCE_BOLD;
63
+ return flags;
64
+ }
65
+ function widthForWidthsArray(standardName, code) {
66
+ if (STANDARD_METRICS[standardName].fixedWidth === void 0 && winAnsiGlyphName(code) === void 0) return 0;
67
+ return widthOfCode(standardName, code);
68
+ }
69
+ function buildFontObjects(standardName, descriptorRef) {
70
+ const metrics = STANDARD_METRICS[standardName];
71
+ const widths = [];
72
+ for (let code = FIRST_CHAR; code <= LAST_CHAR; code++) widths.push(pdfNum(widthForWidthsArray(standardName, code)));
73
+ return {
74
+ font: pdfDict({
75
+ Type: pdfName("Font"),
76
+ Subtype: pdfName("Type1"),
77
+ BaseFont: pdfName(standardName),
78
+ Encoding: pdfName("WinAnsiEncoding"),
79
+ FirstChar: pdfNum(FIRST_CHAR),
80
+ LastChar: pdfNum(LAST_CHAR),
81
+ Widths: pdfArray(widths),
82
+ FontDescriptor: descriptorRef
83
+ }),
84
+ descriptor: pdfDict({
85
+ Type: pdfName("FontDescriptor"),
86
+ FontName: pdfName(standardName),
87
+ Flags: pdfNum(computeFontFlags(standardName, metrics)),
88
+ FontBBox: pdfArray(metrics.fontBBox.map((n) => pdfNum(n))),
89
+ ItalicAngle: pdfNum(metrics.italicAngle),
90
+ Ascent: pdfNum(metrics.ascender),
91
+ Descent: pdfNum(metrics.descender),
92
+ CapHeight: pdfNum(metrics.capHeight),
93
+ XHeight: pdfNum(metrics.xHeight),
94
+ StemV: pdfNum(standardName.includes("Bold") ? NOMINAL_STEM_V_BOLD : NOMINAL_STEM_V_REGULAR)
95
+ })
96
+ };
97
+ }
98
+ function prepareJpegImage(bytes) {
99
+ const info = readJpegInfo(bytes);
100
+ const colorSpace = info.components === 1 ? "DeviceGray" : info.components === 4 ? "DeviceCMYK" : "DeviceRGB";
101
+ const entries = /* @__PURE__ */ new Map([
102
+ ["Type", pdfName("XObject")],
103
+ ["Subtype", pdfName("Image")],
104
+ ["Width", pdfNum(info.width)],
105
+ ["Height", pdfNum(info.height)],
106
+ ["ColorSpace", pdfName(colorSpace)],
107
+ ["BitsPerComponent", pdfNum(info.precision)],
108
+ ["Filter", pdfName("DCTDecode")]
109
+ ]);
110
+ if (info.components === 4 && (info.adobeTransform === 2 || info.adobeTransform === void 0)) entries.set("Decode", pdfArray([
111
+ 1,
112
+ 0,
113
+ 1,
114
+ 0,
115
+ 1,
116
+ 0,
117
+ 1,
118
+ 0
119
+ ].map((n) => pdfNum(n))));
120
+ return {
121
+ dict: pdfDict(entries),
122
+ raw: bytes
123
+ };
124
+ }
125
+ function pngImageDict(width, height, colorSpace, compress) {
126
+ const entries = /* @__PURE__ */ new Map([
127
+ ["Type", pdfName("XObject")],
128
+ ["Subtype", pdfName("Image")],
129
+ ["Width", pdfNum(width)],
130
+ ["Height", pdfNum(height)],
131
+ ["ColorSpace", pdfName(colorSpace)],
132
+ ["BitsPerComponent", pdfNum(8)]
133
+ ]);
134
+ if (compress) entries.set("Filter", pdfName("FlateDecode"));
135
+ return pdfDict(entries);
136
+ }
137
+ function preparePngImage(bytes, compress) {
138
+ const raw = decodePng(bytes);
139
+ const colorSpace = raw.channels === 1 ? "DeviceGray" : "DeviceRGB";
140
+ return {
141
+ dict: pngImageDict(raw.width, raw.height, colorSpace, compress),
142
+ raw: compress ? deflate(raw.data) : raw.data,
143
+ alpha: raw.alpha === void 0 ? void 0 : {
144
+ dict: pngImageDict(raw.width, raw.height, "DeviceGray", compress),
145
+ raw: compress ? deflate(raw.alpha) : raw.alpha
146
+ }
147
+ };
148
+ }
149
+ function prepareImage(asset, compress) {
150
+ const bytes = base64ToBytes(asset.base64);
151
+ return asset.format === "jpeg" ? prepareJpegImage(bytes) : preparePngImage(bytes, compress);
152
+ }
153
+ function buildLinkAnnotDict(link) {
154
+ return pdfDict({
155
+ Type: pdfName("Annot"),
156
+ Subtype: pdfName("Link"),
157
+ Rect: pdfArray([
158
+ link.xPt,
159
+ link.yPt,
160
+ link.xPt + link.widthPt,
161
+ link.yPt + link.heightPt
162
+ ].map((n) => pdfNum(n))),
163
+ Border: pdfArray([
164
+ 0,
165
+ 0,
166
+ 0
167
+ ].map((n) => pdfNum(n))),
168
+ A: pdfDict({
169
+ Type: pdfName("Action"),
170
+ S: pdfName("URI"),
171
+ URI: pdfHexString(new TextEncoder().encode(link.uri))
172
+ })
173
+ });
174
+ }
175
+ function isLinkItem(item) {
176
+ return item.kind === "link";
177
+ }
178
+ const NOTES_ANNOTATION_HIDDEN_FLAG = 2;
179
+ const NOTES_ANNOTATION_AUTHOR = "documents.js:notes";
180
+ function buildNotesAnnotDict(notes) {
181
+ return pdfDict({
182
+ Type: pdfName("Annot"),
183
+ Subtype: pdfName("Text"),
184
+ Rect: pdfArray([
185
+ 0,
186
+ 0,
187
+ 0,
188
+ 0
189
+ ].map((n) => pdfNum(n))),
190
+ Contents: textToPdfString(notes),
191
+ T: textToPdfString(NOTES_ANNOTATION_AUTHOR),
192
+ F: pdfNum(NOTES_ANNOTATION_HIDDEN_FLAG)
193
+ });
194
+ }
195
+ function xrefEntry(offset, generation, inUse) {
196
+ return `${offset.toString().padStart(10, "0")} ${generation.toString().padStart(5, "0")} ${inUse ? "n" : "f"} \n`;
197
+ }
198
+ function writePdf(doc, options = {}) {
199
+ const compress = options.compress ?? true;
200
+ const measurer = createStandardFontMeasurer();
201
+ let nextObjNum = 1;
202
+ const catalogNum = nextObjNum++;
203
+ const pagesNum = nextObjNum++;
204
+ const infoNum = nextObjNum++;
205
+ const fontNames = /* @__PURE__ */ new Set();
206
+ const imageIds = /* @__PURE__ */ new Set();
207
+ for (const page of doc.pages) for (const item of page.items) if (item.kind === "text") fontNames.add(resolveStandardFont(item.font.family, item.font.weight === "bold", item.font.style === "italic").standardName);
208
+ else if (item.kind === "image") imageIds.add(item.imageId);
209
+ const fontAllocs = /* @__PURE__ */ new Map();
210
+ for (const [index, name] of [...fontNames].sort().entries()) {
211
+ const fontNum = nextObjNum++;
212
+ const descNum = nextObjNum++;
213
+ fontAllocs.set(name, {
214
+ fontNum,
215
+ descNum,
216
+ resourceName: `F${index + 1}`
217
+ });
218
+ }
219
+ const imageAllocs = /* @__PURE__ */ new Map();
220
+ for (const [index, imageId] of [...imageIds].sort().entries()) {
221
+ const asset = doc.images[imageId];
222
+ if (asset === void 0) throw new Error(`LayoutDocument references image "${imageId}" but it is not present in images`);
223
+ const prepared = prepareImage(asset, compress);
224
+ const imageNum = nextObjNum++;
225
+ const smaskNum = prepared.alpha === void 0 ? void 0 : nextObjNum++;
226
+ imageAllocs.set(imageId, {
227
+ imageNum,
228
+ smaskNum,
229
+ resourceName: `Im${index + 1}`,
230
+ prepared
231
+ });
232
+ }
233
+ const formulas = options.formulas ?? [];
234
+ const mathFontAlloc = formulas.length === 0 ? void 0 : {
235
+ type0Num: nextObjNum++,
236
+ cidFontNum: nextObjNum++,
237
+ descriptorNum: nextObjNum++,
238
+ fontFileNum: nextObjNum++,
239
+ toUnicodeNum: nextObjNum++,
240
+ resourceName: MATH_FONT_RESOURCE_NAME
241
+ };
242
+ const pageAllocs = doc.pages.map(() => ({
243
+ pageNum: nextObjNum++,
244
+ contentsNum: nextObjNum++
245
+ }));
246
+ const objects = [];
247
+ objects.push({
248
+ num: catalogNum,
249
+ value: pdfDict({
250
+ Type: pdfName("Catalog"),
251
+ Pages: pdfRef(pagesNum, 0)
252
+ })
253
+ });
254
+ objects.push({
255
+ num: pagesNum,
256
+ value: pdfDict({
257
+ Type: pdfName("Pages"),
258
+ Kids: pdfArray(pageAllocs.map((p) => pdfRef(p.pageNum, 0))),
259
+ Count: pdfNum(doc.pages.length)
260
+ })
261
+ });
262
+ objects.push({
263
+ num: infoNum,
264
+ value: buildInfoDict(doc)
265
+ });
266
+ for (const [standardName, alloc] of fontAllocs) {
267
+ const { font, descriptor } = buildFontObjects(standardName, pdfRef(alloc.descNum, 0));
268
+ objects.push({
269
+ num: alloc.fontNum,
270
+ value: font
271
+ });
272
+ objects.push({
273
+ num: alloc.descNum,
274
+ value: descriptor
275
+ });
276
+ }
277
+ for (const alloc of imageAllocs.values()) {
278
+ if (alloc.smaskNum !== void 0 && alloc.prepared.alpha !== void 0) {
279
+ alloc.prepared.dict.entries.set("SMask", pdfRef(alloc.smaskNum, 0));
280
+ objects.push({
281
+ num: alloc.smaskNum,
282
+ value: pdfStream(alloc.prepared.alpha.dict, alloc.prepared.alpha.raw)
283
+ });
284
+ }
285
+ objects.push({
286
+ num: alloc.imageNum,
287
+ value: pdfStream(alloc.prepared.dict, alloc.prepared.raw)
288
+ });
289
+ }
290
+ const mathFont = mathFontAlloc === void 0 ? void 0 : loadMathFont().font;
291
+ const usedGlyphs = mathFontAlloc === void 0 || mathFont === void 0 ? void 0 : collectUsedGlyphs(formulas, mathFont);
292
+ if (mathFontAlloc !== void 0 && mathFont !== void 0 && usedGlyphs !== void 0) {
293
+ const built = buildMathFontObjects(mathFont, usedGlyphs, {
294
+ cidFontRef: pdfRef(mathFontAlloc.cidFontNum, 0),
295
+ descriptorRef: pdfRef(mathFontAlloc.descriptorNum, 0),
296
+ fontFileRef: pdfRef(mathFontAlloc.fontFileNum, 0),
297
+ toUnicodeRef: pdfRef(mathFontAlloc.toUnicodeNum, 0)
298
+ }, compress);
299
+ objects.push({
300
+ num: mathFontAlloc.type0Num,
301
+ value: built.type0
302
+ });
303
+ objects.push({
304
+ num: mathFontAlloc.cidFontNum,
305
+ value: built.cidFont
306
+ });
307
+ objects.push({
308
+ num: mathFontAlloc.descriptorNum,
309
+ value: built.descriptor
310
+ });
311
+ objects.push({
312
+ num: mathFontAlloc.fontFileNum,
313
+ value: built.fontFile
314
+ });
315
+ objects.push({
316
+ num: mathFontAlloc.toUnicodeNum,
317
+ value: built.toUnicode
318
+ });
319
+ }
320
+ const resourceEntries = /* @__PURE__ */ new Map();
321
+ if (fontAllocs.size > 0 || mathFontAlloc !== void 0) {
322
+ const fontEntries = new Map([...fontAllocs.values()].map((alloc) => [alloc.resourceName, pdfRef(alloc.fontNum, 0)]));
323
+ if (mathFontAlloc !== void 0) fontEntries.set(mathFontAlloc.resourceName, pdfRef(mathFontAlloc.type0Num, 0));
324
+ resourceEntries.set("Font", pdfDict(fontEntries));
325
+ }
326
+ if (imageAllocs.size > 0) resourceEntries.set("XObject", pdfDict(new Map([...imageAllocs.values()].map((alloc) => [alloc.resourceName, pdfRef(alloc.imageNum, 0)]))));
327
+ const resourcesDict = pdfDict(resourceEntries);
328
+ const formulasByPage = /* @__PURE__ */ new Map();
329
+ for (const formula of formulas) {
330
+ const forPage = formulasByPage.get(formula.pageIndex);
331
+ if (forPage === void 0) formulasByPage.set(formula.pageIndex, [formula]);
332
+ else forPage.push(formula);
333
+ }
334
+ const context = {
335
+ measurer,
336
+ resolveFont: (font) => {
337
+ const standardName = resolveStandardFont(font.family, font.weight === "bold", font.style === "italic").standardName;
338
+ const alloc = fontAllocs.get(standardName);
339
+ if (alloc === void 0) throw new Error(`font "${standardName}" was not pre-allocated -- this is a writePdf internal invariant violation`);
340
+ return {
341
+ resourceName: alloc.resourceName,
342
+ standardName
343
+ };
344
+ },
345
+ resolveImage: (imageId) => {
346
+ const alloc = imageAllocs.get(imageId);
347
+ if (alloc === void 0) throw new Error(`image "${imageId}" was not pre-allocated -- this is a writePdf internal invariant violation`);
348
+ return { resourceName: alloc.resourceName };
349
+ }
350
+ };
351
+ doc.pages.forEach((page, pageIndex) => {
352
+ throwIfAborted(options.signal);
353
+ const { pageNum, contentsNum } = pageAllocs[pageIndex];
354
+ const { bytes: contentBytes, substitutions } = writeContentStream(page.items, context);
355
+ for (const substitution of substitutions) options.onSubstitution?.(substitution, { pageIndex });
356
+ const pageFormulas = formulasByPage.get(pageIndex);
357
+ const formulaBytes = pageFormulas === void 0 || mathFontAlloc === void 0 || mathFont === void 0 ? void 0 : writeFormulaContentStream(pageFormulas, {
358
+ font: mathFont,
359
+ resourceName: mathFontAlloc.resourceName
360
+ });
361
+ const combinedContentBytes = formulaBytes === void 0 ? contentBytes : concatBytes([contentBytes, formulaBytes]);
362
+ const finalContentBytes = compress ? deflate(combinedContentBytes) : combinedContentBytes;
363
+ const contentsDict = pdfDict(compress ? { Filter: pdfName("FlateDecode") } : {});
364
+ objects.push({
365
+ num: contentsNum,
366
+ value: pdfStream(contentsDict, finalContentBytes)
367
+ });
368
+ const annots = page.items.filter(isLinkItem).map((link) => buildLinkAnnotDict(link));
369
+ if (page.notes !== void 0 && page.notes.length > 0) annots.push(buildNotesAnnotDict(page.notes));
370
+ const pageEntries = /* @__PURE__ */ new Map([
371
+ ["Type", pdfName("Page")],
372
+ ["Parent", pdfRef(pagesNum, 0)],
373
+ ["MediaBox", pdfArray([
374
+ 0,
375
+ 0,
376
+ page.widthPt,
377
+ page.heightPt
378
+ ].map((n) => pdfNum(n)))],
379
+ ["Resources", resourcesDict],
380
+ ["Contents", pdfRef(contentsNum, 0)]
381
+ ]);
382
+ if (annots.length > 0) pageEntries.set("Annots", pdfArray(annots));
383
+ objects.push({
384
+ num: pageNum,
385
+ value: pdfDict(pageEntries)
386
+ });
387
+ });
388
+ const writer = new ByteWriter();
389
+ writer.writeAscii("%PDF-1.7\n");
390
+ const offsets = /* @__PURE__ */ new Map();
391
+ for (const { num, value } of objects) {
392
+ offsets.set(num, writer.length);
393
+ writer.writeAscii(`${num} 0 obj\n`);
394
+ writeObject(writer, value);
395
+ writer.writeAscii("\nendobj\n");
396
+ }
397
+ const maxObjNum = nextObjNum - 1;
398
+ const xrefOffset = writer.length;
399
+ writer.writeAscii("xref\n");
400
+ writer.writeAscii(`0 ${maxObjNum + 1}\n`);
401
+ writer.writeAscii(xrefEntry(0, 65535, false));
402
+ for (let num = 1; num <= maxObjNum; num++) {
403
+ const offset = offsets.get(num);
404
+ if (offset === void 0) throw new Error(`object ${num} was allocated but never written -- this is a writePdf internal invariant violation`);
405
+ writer.writeAscii(xrefEntry(offset, 0, true));
406
+ }
407
+ writer.writeAscii("trailer\n");
408
+ writeObject(writer, pdfDict({
409
+ Size: pdfNum(maxObjNum + 1),
410
+ Root: pdfRef(catalogNum, 0),
411
+ Info: pdfRef(infoNum, 0)
412
+ }));
413
+ writer.writeAscii("\nstartxref\n");
414
+ writer.writeAscii(`${xrefOffset}\n`);
415
+ writer.writeAscii("%%EOF");
416
+ return writer.toBytes();
417
+ }
418
+ //#endregion
419
+ export { NOTES_ANNOTATION_AUTHOR, writePdf };