pdf-parser.js 5.2.30 → 5.3.1

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 (189) hide show
  1. package/dist/{afm-widths-BHD2HZIL.cjs → afm-widths-C6U0SQj9.cjs} +5 -1448
  2. package/dist/{afm-widths-B_IGbGky.js → afm-widths-p3UfaXme.js} +3 -1398
  3. package/dist/afm-widths.cjs +1 -1
  4. package/dist/afm-widths.js +1 -1
  5. package/dist/annotations.d.cts +3 -3
  6. package/dist/annotations.d.ts +3 -3
  7. package/dist/attachments.d.cts +2 -2
  8. package/dist/attachments.d.ts +2 -2
  9. package/dist/builtin-encoding.cjs +4 -3
  10. package/dist/builtin-encoding.js +2 -1
  11. package/dist/cmap.d.cts +1 -1
  12. package/dist/cmap.d.ts +1 -1
  13. package/dist/content-read.d.cts +1 -1
  14. package/dist/content-read.d.ts +1 -1
  15. package/dist/content-write.cjs +1 -1
  16. package/dist/content-write.d.cts +1 -1
  17. package/dist/content-write.d.ts +1 -1
  18. package/dist/content-write.js +1 -1
  19. package/dist/diagnostics-C9FxfZ6H.d.cts +22 -0
  20. package/dist/diagnostics-C9FxfZ6H.d.ts +22 -0
  21. package/dist/diagnostics.d.cts +1 -21
  22. package/dist/diagnostics.d.ts +1 -21
  23. package/dist/document.d.cts +1 -1
  24. package/dist/document.d.ts +1 -1
  25. package/dist/{embedded-font-ByD7ZiQS.d.ts → embedded-font-CQZbTTDM.d.ts} +1 -1
  26. package/dist/{embedded-font-DgVBedw6.d.cts → embedded-font-CqePfvrl.d.cts} +1 -1
  27. package/dist/embedded-font-write.d.cts +1 -1
  28. package/dist/embedded-font-write.d.ts +1 -1
  29. package/dist/embedded-font.cjs +2 -2
  30. package/dist/embedded-font.d.cts +1 -1
  31. package/dist/embedded-font.d.ts +1 -1
  32. package/dist/embedded-font.js +2 -2
  33. package/dist/encoding-glyph-unicode.cjs +353 -0
  34. package/dist/encoding-glyph-unicode.d.cts +4 -0
  35. package/dist/encoding-glyph-unicode.d.ts +4 -0
  36. package/dist/encoding-glyph-unicode.js +352 -0
  37. package/dist/encoding-standard-tables.cjs +531 -0
  38. package/dist/encoding-standard-tables.d.cts +7 -0
  39. package/dist/encoding-standard-tables.d.ts +7 -0
  40. package/dist/encoding-standard-tables.js +527 -0
  41. package/dist/encoding-symbol-tables.cjs +533 -0
  42. package/dist/encoding-symbol-tables.d.cts +7 -0
  43. package/dist/encoding-symbol-tables.d.ts +7 -0
  44. package/dist/encoding-symbol-tables.js +529 -0
  45. package/dist/encoding.cjs +1 -9
  46. package/dist/encoding.d.cts +1 -9
  47. package/dist/encoding.d.ts +1 -9
  48. package/dist/encoding.js +2 -2
  49. package/dist/encrypt.d.cts +1 -1
  50. package/dist/encrypt.d.ts +1 -1
  51. package/dist/filters.d.cts +1 -1
  52. package/dist/filters.d.ts +1 -1
  53. package/dist/font-read.cjs +4 -3
  54. package/dist/font-read.d.cts +2 -2
  55. package/dist/font-read.d.ts +2 -2
  56. package/dist/font-read.js +2 -1
  57. package/dist/font-registry.d.cts +1 -1
  58. package/dist/font-registry.d.ts +1 -1
  59. package/dist/form.d.cts +2 -2
  60. package/dist/form.d.ts +2 -2
  61. package/dist/gdef-table-D0Hzn4KD.d.cts +15 -0
  62. package/dist/gdef-table-DL0V8wEZ.d.ts +15 -0
  63. package/dist/gdef-table.d.cts +1 -14
  64. package/dist/gdef-table.d.ts +1 -14
  65. package/dist/glyf-contours.d.cts +12 -1
  66. package/dist/glyf-contours.d.ts +12 -1
  67. package/dist/gsub-context.cjs +13 -0
  68. package/dist/gsub-context.d.cts +34 -0
  69. package/dist/gsub-context.d.ts +34 -0
  70. package/dist/gsub-context.js +2 -0
  71. package/dist/gsub-table-BDpJWqpf.d.ts +52 -0
  72. package/dist/gsub-table-D6niKeLi.js +556 -0
  73. package/dist/gsub-table-DW7Wmi9V.d.cts +52 -0
  74. package/dist/gsub-table-hFfYmf1W.cjs +741 -0
  75. package/dist/gsub-table.cjs +21 -556
  76. package/dist/gsub-table.d.cts +2 -2
  77. package/dist/gsub-table.d.ts +2 -2
  78. package/dist/gsub-table.js +2 -554
  79. package/dist/images-read.d.cts +2 -2
  80. package/dist/images-read.d.ts +2 -2
  81. package/dist/index.cjs +6 -6
  82. package/dist/index.d.cts +2 -2
  83. package/dist/index.d.ts +2 -2
  84. package/dist/index.js +6 -6
  85. package/dist/interpret-CqXdXgkY.cjs +712 -0
  86. package/dist/interpret-aWWhdIzr.js +677 -0
  87. package/dist/interpret-colors.cjs +6 -0
  88. package/dist/interpret-colors.d.cts +9 -0
  89. package/dist/interpret-colors.d.ts +9 -0
  90. package/dist/interpret-colors.js +2 -0
  91. package/dist/interpret-marked.cjs +25 -0
  92. package/dist/interpret-marked.d.cts +11 -0
  93. package/dist/interpret-marked.d.ts +11 -0
  94. package/dist/interpret-marked.js +23 -0
  95. package/dist/interpret-shapes.cjs +212 -0
  96. package/dist/interpret-shapes.d.cts +32 -0
  97. package/dist/interpret-shapes.d.ts +32 -0
  98. package/dist/interpret-shapes.js +199 -0
  99. package/dist/interpret-types.cjs +0 -0
  100. package/dist/interpret-types.d.cts +123 -0
  101. package/dist/interpret-types.d.ts +123 -0
  102. package/dist/interpret-types.js +0 -0
  103. package/dist/interpret.cjs +3 -887
  104. package/dist/interpret.d.cts +5 -116
  105. package/dist/interpret.d.ts +5 -116
  106. package/dist/interpret.js +2 -887
  107. package/dist/math-font.cjs +1 -1
  108. package/dist/math-font.js +1 -1
  109. package/dist/measure.cjs +1 -1
  110. package/dist/measure.js +1 -1
  111. package/dist/names.d.cts +2 -2
  112. package/dist/names.d.ts +2 -2
  113. package/dist/navigation.d.cts +2 -2
  114. package/dist/navigation.d.ts +2 -2
  115. package/dist/optional-content.d.cts +2 -2
  116. package/dist/optional-content.d.ts +2 -2
  117. package/dist/ot-layout-common-BcsGRFBS.d.cts +10 -0
  118. package/dist/ot-layout-common-BcsGRFBS.d.ts +10 -0
  119. package/dist/ot-layout-common.d.cts +1 -9
  120. package/dist/ot-layout-common.d.ts +1 -9
  121. package/dist/parse.d.cts +1 -1
  122. package/dist/parse.d.ts +1 -1
  123. package/dist/predictors.d.cts +1 -1
  124. package/dist/predictors.d.ts +1 -1
  125. package/dist/raster-Cdm3idP_.js +794 -0
  126. package/dist/raster-EG2KYRZ0.cjs +829 -0
  127. package/dist/raster-text.cjs +5 -0
  128. package/dist/raster-text.d.cts +20 -0
  129. package/dist/raster-text.d.ts +20 -0
  130. package/dist/raster-text.js +2 -0
  131. package/dist/raster.cjs +4 -795
  132. package/dist/raster.d.cts +17 -6
  133. package/dist/raster.d.ts +17 -6
  134. package/dist/raster.js +2 -792
  135. package/dist/read-convert.cjs +310 -0
  136. package/dist/read-convert.d.cts +58 -0
  137. package/dist/read-convert.d.ts +58 -0
  138. package/dist/read-convert.js +295 -0
  139. package/dist/read.cjs +5 -293
  140. package/dist/read.d.cts +1 -1
  141. package/dist/read.d.ts +1 -1
  142. package/dist/read.js +4 -292
  143. package/dist/structure.d.cts +2 -2
  144. package/dist/structure.d.ts +2 -2
  145. package/dist/winansi.cjs +1 -1
  146. package/dist/winansi.js +1 -1
  147. package/dist/write-annotations.cjs +132 -0
  148. package/dist/write-annotations.d.cts +29 -0
  149. package/dist/write-annotations.d.ts +29 -0
  150. package/dist/write-annotations.js +121 -0
  151. package/dist/write-font-objects.cjs +76 -0
  152. package/dist/write-font-objects.d.cts +35 -0
  153. package/dist/write-font-objects.d.ts +35 -0
  154. package/dist/write-font-objects.js +75 -0
  155. package/dist/write-form.cjs +91 -0
  156. package/dist/write-form.d.cts +19 -0
  157. package/dist/write-form.d.ts +19 -0
  158. package/dist/write-form.js +89 -0
  159. package/dist/write-images.cjs +148 -0
  160. package/dist/write-images.d.cts +25 -0
  161. package/dist/write-images.d.ts +25 -0
  162. package/dist/write-images.js +140 -0
  163. package/dist/write-outline.cjs +46 -0
  164. package/dist/write-outline.d.cts +18 -0
  165. package/dist/write-outline.d.ts +18 -0
  166. package/dist/write-outline.js +45 -0
  167. package/dist/write-page-emit.cjs +97 -0
  168. package/dist/write-page-emit.d.cts +63 -0
  169. package/dist/write-page-emit.d.ts +63 -0
  170. package/dist/write-page-emit.js +96 -0
  171. package/dist/write-pages.cjs +37 -0
  172. package/dist/write-pages.d.cts +21 -0
  173. package/dist/write-pages.d.ts +21 -0
  174. package/dist/write-pages.js +36 -0
  175. package/dist/write-strings.cjs +41 -0
  176. package/dist/write-strings.d.cts +9 -0
  177. package/dist/write-strings.d.ts +9 -0
  178. package/dist/write-strings.js +37 -0
  179. package/dist/write.cjs +53 -553
  180. package/dist/write.d.cts +1 -1
  181. package/dist/write.d.ts +1 -1
  182. package/dist/write.js +49 -549
  183. package/dist/xref.d.cts +1 -1
  184. package/dist/xref.d.ts +1 -1
  185. package/package.json +1 -1
  186. package/dist/glyf-contours-B1PsI9oA.d.ts +0 -13
  187. package/dist/glyf-contours-NHBpgks-.d.cts +0 -13
  188. package/dist/gsub-table-Bm9kSMzk.d.cts +0 -16
  189. package/dist/gsub-table-CdfESH2-.d.ts +0 -16
package/dist/write.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LayoutDocument } from "./layout.cjs";
2
- import { r as EmbeddedFaceSubstitution } from "./embedded-font-DgVBedw6.cjs";
2
+ import { r as EmbeddedFaceSubstitution } from "./embedded-font-CqePfvrl.cjs";
3
3
  import { WinAnsiSubstitution } from "./winansi.cjs";
4
4
  import { PdfEncryptionOptions } from "./encrypt-write.cjs";
5
5
  import { FontRegistry } from "./font-registry.cjs";
package/dist/write.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LayoutDocument } from "./layout.js";
2
- import { r as EmbeddedFaceSubstitution } from "./embedded-font-ByD7ZiQS.js";
2
+ import { r as EmbeddedFaceSubstitution } from "./embedded-font-CQZbTTDM.js";
3
3
  import { WinAnsiSubstitution } from "./winansi.js";
4
4
  import { PdfEncryptionOptions } from "./encrypt-write.js";
5
5
  import { FontRegistry } from "./font-registry.js";
package/dist/write.js CHANGED
@@ -1,26 +1,19 @@
1
- import { n as widthOfCode, t as STANDARD_METRICS } from "./afm-widths-B_IGbGky.js";
2
- import { NOTES_ANNOTATION_AUTHOR } from "./notes-annotation-author.js";
3
- import { pdfArray, pdfBool, pdfDict, pdfHexString, pdfLiteralString, pdfName, pdfNull, pdfNum, pdfRef, pdfStream } from "./objects.js";
4
- import { ByteWriter, concatBytes } from "./bytes/writer.js";
1
+ import { n as widthOfCode, t as STANDARD_METRICS } from "./afm-widths-p3UfaXme.js";
2
+ import { pdfArray, pdfDict, pdfHexString, pdfLiteralString, pdfName, pdfNull, pdfNum, pdfRef, pdfStream } from "./objects.js";
3
+ import { ByteWriter } from "./bytes/writer.js";
5
4
  import { writeObject } from "./serialize.js";
6
- import { ByteReader } from "./bytes/reader.js";
7
5
  import { deflate } from "./bytes/flate.js";
8
- import { parseValue } from "./parse.js";
9
- import { throwIfAborted } from "./util/abort.js";
10
6
  import { randomBytes } from "./crypto/random.js";
11
7
  import { createStandardEncryptor, encryptIndirectObject } from "./encrypt-write.js";
12
- import { readJpegInfo as readJpegInfo$1 } from "./image/jpeg-info.js";
13
- import { encodeCcittFax } from "./image/ccitt-encode.js";
14
- import { decodePng } from "./image/png-decode.js";
15
- import { collectEmbeddedGlyphs } from "./embedded-font.js";
16
- import { writeContentStream } from "./content-write.js";
17
- import { buildEmbeddedFontObjects } from "./embedded-font-write.js";
8
+ import { prepareImage } from "./write-images.js";
9
+ import { buildInfoDict } from "./write-strings.js";
10
+ import { restoreResidueRow, xrefEntry } from "./write-annotations.js";
11
+ import { emitFormObjects } from "./write-form.js";
12
+ import { emitFontObjects } from "./write-font-objects.js";
18
13
  import { resolveFaceWithRegistry } from "./font-registry.js";
19
- import { collectUsedGlyphs, writeFormulaContentStream } from "./math-content-write.js";
20
- import { loadMathFont } from "./math-font.js";
21
- import { buildMathFontObjects } from "./math-font-write.js";
22
14
  import { createFontMeasurer } from "./measure.js";
23
- import { subsetSfnt } from "./sfnt-subset.js";
15
+ import { emitPageObjects } from "./write-page-emit.js";
16
+ import { emitOutlineObjects } from "./write-outline.js";
24
17
  import { base64ToBytes } from "byte-codec";
25
18
  //#region src/write.ts
26
19
  const MATH_FONT_RESOURCE_NAME = "MF";
@@ -35,43 +28,6 @@ const FLAG_NONSYMBOLIC = 32;
35
28
  const FLAG_ITALIC = 64;
36
29
  const FLAG_FORCE_BOLD = 262144;
37
30
  const FILE_ID_BYTES = 16;
38
- const BITS_PER_BYTE = 8;
39
- const BYTE_SHIFT = Math.log2(BITS_PER_BYTE);
40
- const BYTE_MASK = 255;
41
- const PACKED_BIT_MSB_MASK = 128;
42
- const BIT_INDEX_MASK = 7;
43
- function textToPdfString(text) {
44
- const bytes = new Uint8Array(2 + text.length * 2);
45
- bytes[0] = 254;
46
- bytes[1] = 255;
47
- let offset = 2;
48
- for (const unit of text.split("")) {
49
- const code = unit.charCodeAt(0);
50
- bytes[offset] = code >> BITS_PER_BYTE & BYTE_MASK;
51
- bytes[offset + 1] = code & BYTE_MASK;
52
- offset += 2;
53
- }
54
- return pdfHexString(bytes);
55
- }
56
- function pad2(n) {
57
- return n.toString().padStart(2, "0");
58
- }
59
- function formatPdfDate(iso) {
60
- const date = new Date(iso);
61
- return `D:${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
62
- }
63
- function buildInfoDict(doc) {
64
- const entries = /* @__PURE__ */ new Map();
65
- entries.set("Producer", textToPdfString("documents.js"));
66
- if (doc.metadata.title !== void 0) entries.set("Title", textToPdfString(doc.metadata.title));
67
- if (doc.metadata.author !== void 0) entries.set("Author", textToPdfString(doc.metadata.author));
68
- if (doc.metadata.subject !== void 0) entries.set("Subject", textToPdfString(doc.metadata.subject));
69
- if (doc.metadata.keywords !== void 0) entries.set("Keywords", textToPdfString(doc.metadata.keywords.join(", ")));
70
- if (doc.metadata.creator !== void 0) entries.set("Creator", textToPdfString(doc.metadata.creator));
71
- if (doc.metadata.createdIso !== void 0) entries.set("CreationDate", textToPdfString(formatPdfDate(doc.metadata.createdIso)));
72
- if (doc.metadata.modifiedIso !== void 0) entries.set("ModDate", textToPdfString(formatPdfDate(doc.metadata.modifiedIso)));
73
- return pdfDict(entries);
74
- }
75
31
  function computeFontFlags(standardName, metrics) {
76
32
  let flags = FLAG_NONSYMBOLIC;
77
33
  if (standardName.startsWith("Courier")) flags |= FLAG_FIXED_PITCH;
@@ -112,245 +68,6 @@ function buildFontObjects(standardName, descriptorRef) {
112
68
  function codePointsOf(texts) {
113
69
  return new Set(texts.flatMap((text) => [...text].map((character) => character.codePointAt(0))));
114
70
  }
115
- const JPEG_COMPONENTS_CMYK = 4;
116
- function prepareJpegImage(bytes) {
117
- const info = readJpegInfo$1(bytes);
118
- const colorSpace = info.components === 1 ? "DeviceGray" : info.components === JPEG_COMPONENTS_CMYK ? "DeviceCMYK" : "DeviceRGB";
119
- const entries = /* @__PURE__ */ new Map([
120
- ["Type", pdfName("XObject")],
121
- ["Subtype", pdfName("Image")],
122
- ["Width", pdfNum(info.width)],
123
- ["Height", pdfNum(info.height)],
124
- ["ColorSpace", pdfName(colorSpace)],
125
- ["BitsPerComponent", pdfNum(info.precision)],
126
- ["Filter", pdfName("DCTDecode")]
127
- ]);
128
- if (info.components === JPEG_COMPONENTS_CMYK && (info.adobeTransform === 2 || info.adobeTransform === void 0)) entries.set("Decode", pdfArray([
129
- 1,
130
- 0,
131
- 1,
132
- 0,
133
- 1,
134
- 0,
135
- 1,
136
- 0
137
- ].map((n) => pdfNum(n))));
138
- return {
139
- dict: pdfDict(entries),
140
- raw: bytes
141
- };
142
- }
143
- function pngImageDict(width, height, colorSpace, compress) {
144
- const entries = /* @__PURE__ */ new Map([
145
- ["Type", pdfName("XObject")],
146
- ["Subtype", pdfName("Image")],
147
- ["Width", pdfNum(width)],
148
- ["Height", pdfNum(height)],
149
- ["ColorSpace", pdfName(colorSpace)],
150
- ["BitsPerComponent", pdfNum(BITS_PER_BYTE)]
151
- ]);
152
- if (compress) entries.set("Filter", pdfName("FlateDecode"));
153
- return pdfDict(entries);
154
- }
155
- function packBilevel(raw) {
156
- const rowBytes = raw.width + BIT_INDEX_MASK >> BYTE_SHIFT;
157
- const packed = new Uint8Array(rowBytes * raw.height);
158
- const view = new DataView(packed.buffer);
159
- for (let index = 0; index < raw.data.length; index++) {
160
- const sample = raw.data[index];
161
- if (sample !== 0 && sample !== BYTE_MASK) return;
162
- if (sample === BYTE_MASK) {
163
- const x = index % raw.width;
164
- const byteIndex = Math.floor(index / raw.width) * rowBytes + (x >> BYTE_SHIFT);
165
- view.setUint8(byteIndex, view.getUint8(byteIndex) | PACKED_BIT_MSB_MASK >> (x & BIT_INDEX_MASK));
166
- }
167
- }
168
- return packed;
169
- }
170
- function preparePngImage(bytes, compress) {
171
- const raw = decodePng(bytes);
172
- const colorSpace = raw.channels === 1 ? "DeviceGray" : "DeviceRGB";
173
- if (compress && raw.channels === 1 && raw.alpha === void 0) {
174
- const bilevel = packBilevel(raw);
175
- if (bilevel !== void 0) {
176
- const flate = deflate(raw.data);
177
- const g4 = encodeCcittFax(bilevel, {
178
- columns: raw.width,
179
- rows: raw.height,
180
- maxBytes: flate.length
181
- });
182
- if (g4 !== void 0) return {
183
- dict: pdfDict(/* @__PURE__ */ new Map([
184
- ["Type", pdfName("XObject")],
185
- ["Subtype", pdfName("Image")],
186
- ["Width", pdfNum(raw.width)],
187
- ["Height", pdfNum(raw.height)],
188
- ["ColorSpace", pdfName("DeviceGray")],
189
- ["BitsPerComponent", pdfNum(1)],
190
- ["Filter", pdfName("CCITTFaxDecode")],
191
- ["DecodeParms", pdfDict(/* @__PURE__ */ new Map([
192
- ["K", pdfNum(-1)],
193
- ["Columns", pdfNum(raw.width)],
194
- ["Rows", pdfNum(raw.height)],
195
- ["BlackIs1", pdfBool(false)]
196
- ]))]
197
- ])),
198
- raw: g4,
199
- alpha: void 0
200
- };
201
- return {
202
- dict: pngImageDict(raw.width, raw.height, colorSpace, true),
203
- raw: flate,
204
- alpha: void 0
205
- };
206
- }
207
- }
208
- return {
209
- dict: pngImageDict(raw.width, raw.height, colorSpace, compress),
210
- raw: compress ? deflate(raw.data) : raw.data,
211
- alpha: raw.alpha === void 0 ? void 0 : {
212
- dict: pngImageDict(raw.width, raw.height, "DeviceGray", compress),
213
- raw: compress ? deflate(raw.alpha) : raw.alpha
214
- }
215
- };
216
- }
217
- function preparePassthroughImage(asset, original, compress) {
218
- const png = preparePngImage(base64ToBytes(asset.base64), compress);
219
- const entries = /* @__PURE__ */ new Map([
220
- ["Type", pdfName("XObject")],
221
- ["Subtype", pdfName("Image")],
222
- ["Width", pdfNum(asset.widthPx)],
223
- ["Height", pdfNum(asset.heightPx)],
224
- ["Filter", pdfName(original.filter === "jbig2" ? "JBIG2Decode" : "JPXDecode")]
225
- ]);
226
- if (original.filter === "jbig2") {
227
- entries.set("ColorSpace", pdfName("DeviceGray"));
228
- entries.set("BitsPerComponent", pdfNum(1));
229
- }
230
- return {
231
- dict: pdfDict(entries),
232
- raw: base64ToBytes(original.base64),
233
- alpha: png.alpha
234
- };
235
- }
236
- function prepareImage(asset, compress) {
237
- if (asset.original !== void 0) return preparePassthroughImage(asset, asset.original, compress);
238
- const bytes = base64ToBytes(asset.base64);
239
- return asset.format === "jpeg" ? prepareJpegImage(bytes) : preparePngImage(bytes, compress);
240
- }
241
- function buildLinkAnnotDict(link) {
242
- return pdfDict({
243
- Type: pdfName("Annot"),
244
- Subtype: pdfName("Link"),
245
- Rect: pdfArray([
246
- link.xPt,
247
- link.yPt,
248
- link.xPt + link.widthPt,
249
- link.yPt + link.heightPt
250
- ].map((n) => pdfNum(n))),
251
- Border: pdfArray([
252
- 0,
253
- 0,
254
- 0
255
- ].map((n) => pdfNum(n))),
256
- A: pdfDict({
257
- Type: pdfName("Action"),
258
- S: pdfName("URI"),
259
- URI: pdfHexString(new TextEncoder().encode(link.uri))
260
- })
261
- });
262
- }
263
- function destinationViewArray(target) {
264
- const n = (value) => value === void 0 ? pdfNull() : pdfNum(value);
265
- if (target.kind === "xyz") return [
266
- pdfName("XYZ"),
267
- n(target.leftPt),
268
- n(target.topPt),
269
- n(target.zoom)
270
- ];
271
- if (target.kind === "fitH") return [pdfName("FitH"), n(target.topPt)];
272
- if (target.kind === "fitV") return [pdfName("FitV"), n(target.leftPt)];
273
- if (target.kind === "fitR") return [
274
- pdfName("FitR"),
275
- n(target.leftPt),
276
- n(target.bottomPt),
277
- n(target.rightPt),
278
- n(target.topPt)
279
- ];
280
- if (target.kind === "fitBH") return [pdfName("FitBH"), n(target.topPt)];
281
- if (target.kind === "fitBV") return [pdfName("FitBV"), n(target.leftPt)];
282
- return [pdfName(target.kind === "fitB" ? "FitB" : "Fit")];
283
- }
284
- function resolveDestinationArray(doc, pageAllocs, name, what) {
285
- const destination = doc.destinations?.find((d) => d.name === name);
286
- if (destination === void 0) throw new Error(`${what} names destination "${name}", which the document's destinations table does not carry — this is a caller-invariant violation`);
287
- const targetPage = pageAllocs[destination.pageIndex];
288
- if (targetPage === void 0) throw new Error(`destination "${destination.name}" names page index ${destination.pageIndex}, which is beyond the document's own pages — this is a caller-invariant violation`);
289
- return [pdfRef(targetPage.pageNum, 0), ...destinationViewArray(destination.target)];
290
- }
291
- function buildInternalLinkAnnotDict(link, doc, pageAllocs) {
292
- return pdfDict({
293
- Type: pdfName("Annot"),
294
- Subtype: pdfName("Link"),
295
- Rect: pdfArray([
296
- link.xPt,
297
- link.yPt,
298
- link.xPt + link.widthPt,
299
- link.yPt + link.heightPt
300
- ].map((v) => pdfNum(v))),
301
- Border: pdfArray([
302
- 0,
303
- 0,
304
- 0
305
- ].map((v) => pdfNum(v))),
306
- Dest: pdfArray(resolveDestinationArray(doc, pageAllocs, link.destination, "internal link"))
307
- });
308
- }
309
- function isLinkItem(item) {
310
- return item.kind === "link";
311
- }
312
- function isInternalLinkItem(item) {
313
- return item.kind === "internalLink";
314
- }
315
- const NOTES_ANNOTATION_HIDDEN_FLAG = 2;
316
- function buildNotesAnnotDict(notes) {
317
- return pdfDict({
318
- Type: pdfName("Annot"),
319
- Subtype: pdfName("Text"),
320
- Rect: pdfArray([
321
- 0,
322
- 0,
323
- 0,
324
- 0
325
- ].map((n) => pdfNum(n))),
326
- Contents: textToPdfString(notes),
327
- T: textToPdfString(NOTES_ANNOTATION_AUTHOR),
328
- F: pdfNum(NOTES_ANNOTATION_HIDDEN_FLAG)
329
- });
330
- }
331
- const XREF_OFFSET_DIGITS = 10;
332
- const XREF_GENERATION_DIGITS = 5;
333
- function xrefEntry(offset, generation, inUse) {
334
- return `${offset.toString().padStart(XREF_OFFSET_DIGITS, "0")} ${generation.toString().padStart(XREF_GENERATION_DIGITS, "0")} ${inUse ? "n" : "f"} \n`;
335
- }
336
- function parseResidueRow(residue) {
337
- const reader = new ByteReader(new TextEncoder().encode(residue.xml));
338
- return parseValue(reader, () => void 0);
339
- }
340
- function objectContainsReference(obj) {
341
- if (obj.kind === "ref") return true;
342
- if (obj.kind === "array") return obj.items.some(objectContainsReference);
343
- if (obj.kind === "dict") return [...obj.entries.values()].some(objectContainsReference);
344
- if (obj.kind === "stream") return [...obj.dict.entries.values()].some(objectContainsReference);
345
- return false;
346
- }
347
- function restoreResidueRow(source, key) {
348
- const row = source?.[key];
349
- if (row === void 0) return;
350
- const parsed = parseResidueRow(row);
351
- if (parsed === void 0 || objectContainsReference(parsed)) return;
352
- return parsed;
353
- }
354
71
  function writePdf(doc, options = {}) {
355
72
  const compress = options.compress ?? true;
356
73
  const registry = options.fonts;
@@ -555,43 +272,13 @@ function writePdf(doc, options = {}) {
555
272
  value: pdfDict({ EmbeddedFiles: pdfDict({ Names: pdfArray(names) }) })
556
273
  });
557
274
  }
558
- if (outlineRootNum !== void 0) {
559
- let itemCursor = 0;
560
- const emitItems = (items, parentNum) => {
561
- const siblingNums = [];
562
- let prevNum;
563
- for (const item of items) {
564
- const ownNum = outlineItemNums[itemCursor];
565
- itemCursor += 1;
566
- siblingNums.push(ownNum);
567
- const childNums = emitItems(item.children, ownNum);
568
- const entries = [["Title", pdfLiteralString(new TextEncoder().encode(item.title))], ["Parent", pdfRef(parentNum, 0)]];
569
- if (item.destination !== void 0) entries.push(["Dest", pdfArray(resolveDestinationArray(doc, pageAllocs, item.destination, `outline item "${item.title}"`))]);
570
- if (prevNum !== void 0) entries.push(["Prev", pdfRef(prevNum, 0)]);
571
- if (siblingNums.length < items.length) entries.push(["Next", pdfRef(outlineItemNums[itemCursor], 0)]);
572
- if (childNums.length > 0) {
573
- entries.push(["First", pdfRef(childNums[0], 0)]);
574
- entries.push(["Last", pdfRef(childNums[childNums.length - 1], 0)]);
575
- entries.push(["Count", pdfNum(childNums.length)]);
576
- }
577
- objects.push({
578
- num: ownNum,
579
- value: pdfDict(Object.fromEntries(entries))
580
- });
581
- prevNum = ownNum;
582
- }
583
- return siblingNums;
584
- };
585
- const topLevelNums = emitItems(doc.outline ?? [], outlineRootNum);
586
- objects.push({
587
- num: outlineRootNum,
588
- value: pdfDict({
589
- Type: pdfName("Outlines"),
590
- First: pdfRef(topLevelNums[0], 0),
591
- Last: pdfRef(topLevelNums[topLevelNums.length - 1], 0)
592
- })
593
- });
594
- }
275
+ emitOutlineObjects({
276
+ objects,
277
+ outlineItemNums,
278
+ outlineRootNum,
279
+ doc,
280
+ pageAllocs
281
+ });
595
282
  for (const layer of doc.layers ?? []) {
596
283
  const num = layerNumByName.get(layer.name);
597
284
  objects.push({
@@ -603,85 +290,13 @@ function writePdf(doc, options = {}) {
603
290
  });
604
291
  }
605
292
  const widgetAnnotsByPage = /* @__PURE__ */ new Map();
606
- const noteWidgetAnnot = (widget, ref) => {
607
- const existing = widgetAnnotsByPage.get(widget.pageIndex);
608
- if (existing === void 0) widgetAnnotsByPage.set(widget.pageIndex, [ref]);
609
- else existing.push(ref);
610
- };
611
- const widgetRectArray = (widget) => pdfArray([
612
- widget.xPt,
613
- widget.yPt,
614
- widget.xPt + widget.widthPt,
615
- widget.yPt + widget.heightPt
616
- ].map((n) => pdfNum(n)));
617
- const widgetDict = (widget) => pdfDict({
618
- Subtype: pdfName("Widget"),
619
- Rect: widgetRectArray(widget),
620
- P: pdfRef(pageAllocs[widget.pageIndex].pageNum, 0)
621
- });
622
- const FIELD_TYPE_PDF_NAME = {
623
- text: "Tx",
624
- checkbox: "Btn",
625
- radio: "Btn",
626
- button: "Btn",
627
- listbox: "Ch",
628
- combobox: "Ch",
629
- signature: "Sig"
630
- };
631
- const emitFormFieldObjects = (fields, parentName) => {
632
- for (const field of fields) {
633
- const ownName = parentName === void 0 ? field.name : field.name.startsWith(`${parentName}.`) ? field.name.slice(parentName.length + 1) : field.name;
634
- const entries = [];
635
- if (ownName.length > 0) entries.push(["T", pdfLiteralString(new TextEncoder().encode(ownName))]);
636
- if (field.alias !== void 0) entries.push(["TU", pdfLiteralString(new TextEncoder().encode(field.alias))]);
637
- if (field.fieldType === "group") entries.push(["Kids", pdfArray(field.children.map((child) => pdfRef(formNumOf(child), 0)))]);
638
- else {
639
- entries.push(["FT", pdfName(FIELD_TYPE_PDF_NAME[field.fieldType])]);
640
- const FLAG_READ_ONLY = 1;
641
- const FLAG_PUSHBUTTON = 4;
642
- const FLAG_RADIO = 32768;
643
- const FLAG_COMBO = 131072;
644
- let flags = 0;
645
- if (field.readOnly === true) flags |= FLAG_READ_ONLY;
646
- if (field.fieldType === "button") flags |= FLAG_PUSHBUTTON;
647
- if (field.fieldType === "radio") flags |= FLAG_RADIO;
648
- if (field.fieldType === "combobox") flags |= FLAG_COMBO;
649
- if (flags !== 0) entries.push(["Ff", pdfNum(flags)]);
650
- if (field.fieldType === "text" || field.fieldType === "listbox" || field.fieldType === "combobox") {
651
- if (field.value !== void 0) entries.push(["V", pdfLiteralString(new TextEncoder().encode(field.value))]);
652
- } else if (field.fieldType === "checkbox" || field.fieldType === "radio") entries.push(["V", pdfName(field.value ?? (field.checked === true ? "Yes" : "Off"))]);
653
- if (field.options !== void 0) entries.push(["Opt", pdfArray(field.options.map((option) => pdfLiteralString(new TextEncoder().encode(option))))]);
654
- const firstWidget = field.widgets[0];
655
- if (field.widgets.length === 1 && firstWidget !== void 0) {
656
- entries.push(["Subtype", pdfName("Widget")]);
657
- entries.push(["Rect", widgetRectArray(firstWidget)]);
658
- entries.push(["P", pdfRef(pageAllocs[firstWidget.pageIndex].pageNum, 0)]);
659
- noteWidgetAnnot(firstWidget, pdfRef(formNumOf(field), 0));
660
- } else if (formExtraWidgetNums.has(field)) {
661
- const extraNums = formExtraWidgetNums.get(field) ?? [];
662
- entries.push(["Kids", pdfArray(extraNums.map((num) => pdfRef(num, 0)))]);
663
- for (const [index, num] of extraNums.entries()) {
664
- const widget = field.widgets[index];
665
- if (widget !== void 0) noteWidgetAnnot(widget, pdfRef(num, 0));
666
- }
667
- }
668
- }
669
- objects.push({
670
- num: formNumOf(field),
671
- value: pdfDict(Object.fromEntries(entries))
672
- });
673
- const extraNums = formExtraWidgetNums.get(field) ?? [];
674
- for (const [index, num] of extraNums.entries()) {
675
- const widget = field.widgets[index];
676
- if (widget !== void 0) objects.push({
677
- num,
678
- value: widgetDict(widget)
679
- });
680
- }
681
- emitFormFieldObjects(field.children, field.name);
682
- }
683
- };
684
- emitFormFieldObjects(doc.form ?? [], void 0);
293
+ emitFormObjects({
294
+ objects,
295
+ widgetAnnotsByPage,
296
+ pageAllocs,
297
+ formNumOf,
298
+ formExtraWidgetNums
299
+ }, doc.form ?? []);
685
300
  if (structRootNum !== void 0) {
686
301
  const emitStructureElement = (element, parentNum) => {
687
302
  const entries = [
@@ -747,67 +362,14 @@ function writePdf(doc, options = {}) {
747
362
  value: pdfStream(alloc.prepared.dict, alloc.prepared.raw)
748
363
  });
749
364
  }
750
- const mathFont = mathFontAlloc === void 0 ? void 0 : loadMathFont().font;
751
- const usedGlyphs = mathFontAlloc === void 0 || mathFont === void 0 ? void 0 : collectUsedGlyphs(formulas, mathFont);
752
- if (mathFontAlloc !== void 0 && mathFont !== void 0 && usedGlyphs !== void 0) {
753
- const built = buildMathFontObjects(mathFont, usedGlyphs, {
754
- cidFontRef: pdfRef(mathFontAlloc.cidFontNum, 0),
755
- descriptorRef: pdfRef(mathFontAlloc.descriptorNum, 0),
756
- fontFileRef: pdfRef(mathFontAlloc.fontFileNum, 0),
757
- toUnicodeRef: pdfRef(mathFontAlloc.toUnicodeNum, 0)
758
- }, compress);
759
- objects.push({
760
- num: mathFontAlloc.type0Num,
761
- value: built.type0
762
- });
763
- objects.push({
764
- num: mathFontAlloc.cidFontNum,
765
- value: built.cidFont
766
- });
767
- objects.push({
768
- num: mathFontAlloc.descriptorNum,
769
- value: built.descriptor
770
- });
771
- objects.push({
772
- num: mathFontAlloc.fontFileNum,
773
- value: built.fontFile
774
- });
775
- objects.push({
776
- num: mathFontAlloc.toUnicodeNum,
777
- value: built.toUnicode
778
- });
779
- }
780
- for (const [face, alloc] of embeddedAllocs) {
781
- const faceUsedGlyphs = collectEmbeddedGlyphs(alloc.texts, face);
782
- const subset = subsetSfnt(face.font, [...alloc.codePoints], [...faceUsedGlyphs.keys()]);
783
- if (subset === void 0) throw new Error(`font "${face.postScriptName}" resolved to an embeddable face, but its glyph outlines could not be subsetted — only TrueType-outline ('glyf') fonts can be embedded, so supply a TrueType face for this family or drop it from the registry`);
784
- const built = buildEmbeddedFontObjects(face, subset, faceUsedGlyphs, {
785
- cidFontRef: pdfRef(alloc.cidFontNum, 0),
786
- descriptorRef: pdfRef(alloc.descriptorNum, 0),
787
- fontFileRef: pdfRef(alloc.fontFileNum, 0),
788
- toUnicodeRef: pdfRef(alloc.toUnicodeNum, 0)
789
- }, compress);
790
- objects.push({
791
- num: alloc.type0Num,
792
- value: built.type0
793
- });
794
- objects.push({
795
- num: alloc.cidFontNum,
796
- value: built.cidFont
797
- });
798
- objects.push({
799
- num: alloc.descriptorNum,
800
- value: built.descriptor
801
- });
802
- objects.push({
803
- num: alloc.fontFileNum,
804
- value: built.fontFile
805
- });
806
- objects.push({
807
- num: alloc.toUnicodeNum,
808
- value: built.toUnicode
809
- });
810
- }
365
+ const mathFontResult = emitFontObjects({
366
+ objects,
367
+ formulas,
368
+ mathFontAlloc,
369
+ embeddedAllocs,
370
+ compress
371
+ });
372
+ const mathFont = mathFontResult === void 0 ? void 0 : mathFontResult.font;
811
373
  const resourceEntries = /* @__PURE__ */ new Map();
812
374
  if (fontAllocs.size > 0 || embeddedAllocs.size > 0 || mathFontAlloc !== void 0) {
813
375
  const fontEntries = new Map([...fontAllocs.values()].map((alloc) => [alloc.resourceName, pdfRef(alloc.fontNum, 0)]));
@@ -817,86 +379,24 @@ function writePdf(doc, options = {}) {
817
379
  }
818
380
  if (imageAllocs.size > 0) resourceEntries.set("XObject", pdfDict(new Map([...imageAllocs.values()].map((alloc) => [alloc.resourceName, pdfRef(alloc.imageNum, 0)]))));
819
381
  const resourcesDict = pdfDict(resourceEntries);
820
- const markedStructureByPage = /* @__PURE__ */ new Map();
821
- const formulasByPage = /* @__PURE__ */ new Map();
822
- for (const formula of formulas) {
823
- const forPage = formulasByPage.get(formula.pageIndex);
824
- if (forPage === void 0) formulasByPage.set(formula.pageIndex, [formula]);
825
- else forPage.push(formula);
826
- }
827
- const context = {
382
+ const markedStructureByPage = emitPageObjects({
383
+ doc,
384
+ options,
385
+ objects,
386
+ compress,
828
387
  measurer,
829
- resolveFont: (font) => {
830
- const resolved = resolveFaceWithRegistry(registry, font);
831
- if (resolved.kind === "embedded") {
832
- const alloc = embeddedAllocs.get(resolved.face);
833
- if (alloc === void 0) throw new Error(`embedded font "${resolved.face.postScriptName}" was not pre-allocated — this is a writePdf internal invariant violation`);
834
- return {
835
- kind: "embedded",
836
- resourceName: alloc.resourceName,
837
- face: resolved.face
838
- };
839
- }
840
- const alloc = fontAllocs.get(resolved.standardName);
841
- if (alloc === void 0) throw new Error(`font "${resolved.standardName}" was not pre-allocated — this is a writePdf internal invariant violation`);
842
- return {
843
- kind: "standard",
844
- resourceName: alloc.resourceName,
845
- standardName: resolved.standardName
846
- };
847
- },
848
- resolveImage: (imageId) => {
849
- const alloc = imageAllocs.get(imageId);
850
- if (alloc === void 0) throw new Error(`image "${imageId}" was not pre-allocated — this is a writePdf internal invariant violation`);
851
- return { resourceName: alloc.resourceName };
852
- }
853
- };
854
- doc.pages.forEach((page, pageIndex) => {
855
- throwIfAborted(options.signal);
856
- const { pageNum, contentsNum } = pageAllocs[pageIndex];
857
- let pageMcid = 0;
858
- const pageContext = {
859
- ...context,
860
- nextMcid: () => pageMcid++,
861
- layerObjectNumberOf: (name) => layerNumByName.get(name)
862
- };
863
- const { bytes: contentBytes, substitutions, missingGlyphs, markedStructure } = writeContentStream(page.items, pageContext);
864
- if (markedStructure.length > 0) markedStructureByPage.set(pageIndex, [...markedStructure]);
865
- for (const substitution of substitutions) options.onSubstitution?.(substitution, { pageIndex });
866
- for (const missing of missingGlyphs) options.onMissingGlyph?.(missing, { pageIndex });
867
- const pageFormulas = formulasByPage.get(pageIndex);
868
- const formulaBytes = pageFormulas === void 0 || mathFontAlloc === void 0 || mathFont === void 0 ? void 0 : writeFormulaContentStream(pageFormulas, {
869
- font: mathFont,
870
- resourceName: mathFontAlloc.resourceName
871
- });
872
- const combinedContentBytes = formulaBytes === void 0 ? contentBytes : concatBytes([contentBytes, formulaBytes]);
873
- const finalContentBytes = compress ? deflate(combinedContentBytes) : combinedContentBytes;
874
- const contentsDict = pdfDict(compress ? { Filter: pdfName("FlateDecode") } : {});
875
- objects.push({
876
- num: contentsNum,
877
- value: pdfStream(contentsDict, finalContentBytes)
878
- });
879
- const annots = [...page.items.filter(isLinkItem).map((link) => buildLinkAnnotDict(link)), ...page.items.filter(isInternalLinkItem).map((link) => buildInternalLinkAnnotDict(link, doc, pageAllocs))];
880
- if (page.notes !== void 0 && page.notes.length > 0) annots.push(buildNotesAnnotDict(page.notes));
881
- annots.push(...widgetAnnotsByPage.get(pageIndex) ?? []);
882
- const pageEntries = /* @__PURE__ */ new Map([
883
- ["Type", pdfName("Page")],
884
- ["Parent", pdfRef(pagesNum, 0)],
885
- ["MediaBox", pdfArray([
886
- 0,
887
- 0,
888
- page.widthPt,
889
- page.heightPt
890
- ].map((n) => pdfNum(n)))],
891
- ["Resources", resourcesDict],
892
- ["Contents", pdfRef(contentsNum, 0)]
893
- ]);
894
- if (annots.length > 0) pageEntries.set("Annots", pdfArray(annots));
895
- if (markedStructureByPage.has(pageIndex)) pageEntries.set("StructParents", pdfNum(pageIndex));
896
- objects.push({
897
- num: pageNum,
898
- value: pdfDict(pageEntries)
899
- });
388
+ registry,
389
+ fontAllocs,
390
+ embeddedAllocs,
391
+ imageAllocs,
392
+ layerNumByName,
393
+ formulas,
394
+ mathFontAlloc,
395
+ mathFont,
396
+ pageAllocs,
397
+ pagesNum,
398
+ resourcesDict,
399
+ widgetAnnotsByPage
900
400
  });
901
401
  if (structRootNum !== void 0 && structParentTreeNum !== void 0) {
902
402
  const nums = [];
package/dist/xref.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { PdfDiagnosticSink } from "./diagnostics.cjs";
1
+ import { i as PdfDiagnosticSink } from "./diagnostics-C9FxfZ6H.cjs";
2
2
  import { n as PdfDict } from "./objects-e2RS3-yT.cjs";
3
3
  //#region src/xref.d.ts
4
4
  interface XrefOffsetEntry {
package/dist/xref.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PdfDiagnosticSink } from "./diagnostics.js";
1
+ import { i as PdfDiagnosticSink } from "./diagnostics-C9FxfZ6H.js";
2
2
  import { n as PdfDict } from "./objects-e2RS3-yT.js";
3
3
  //#region src/xref.d.ts
4
4
  interface XrefOffsetEntry {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pdf-parser.js",
3
- "version": "5.2.30",
3
+ "version": "5.3.1",
4
4
  "description": "Hand-written, dependency-minimal PDF codec: parses arbitrary real-world PDFs and generates new ones, built on its own codec-owned LayoutDocument item model and Zod 4 codecs.",
5
5
  "type": "module",
6
6
  "repository": {