@aboutgeo/pdiiif 0.0.0-stage → 0.2.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.
Files changed (69) hide show
  1. package/README.md +169 -2
  2. package/dist/__tests__/parser.test.d.ts +1 -0
  3. package/dist/__tests__/pdf.spec.d.ts +1 -0
  4. package/dist/__tests__/region.test.d.ts +1 -0
  5. package/dist/__tests__/setupJest.d.ts +0 -0
  6. package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
  7. package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
  8. package/dist/convert.d.ts +223 -0
  9. package/dist/download.d.ts +115 -0
  10. package/dist/iiif.d.ts +110 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.mjs +11137 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/io.d.ts +75 -0
  17. package/dist/log.d.ts +21 -0
  18. package/dist/metrics.d.ts +10 -0
  19. package/dist/ocr.d.ts +36 -0
  20. package/dist/optimization.d.ts +48 -0
  21. package/dist/optimization.worker.d.ts +1 -0
  22. package/dist/pdf/annos-text.d.ts +19 -0
  23. package/dist/pdf/annos.d.ts +4 -0
  24. package/dist/pdf/common.d.ts +48 -0
  25. package/dist/pdf/generator.d.ts +197 -0
  26. package/dist/pdf/image.d.ts +34 -0
  27. package/dist/pdf/parser.d.ts +131 -0
  28. package/dist/pdf/pkzip.d.ts +23 -0
  29. package/dist/pdf/png.d.ts +34 -0
  30. package/dist/pdf/util.d.ts +18 -0
  31. package/dist/res/licenses.d.ts +7 -0
  32. package/dist/res/srgbColorspace.d.ts +2 -0
  33. package/dist/util.d.ts +8 -0
  34. package/dist/version.d.ts +2 -0
  35. package/package.json +149 -4
  36. package/src/__tests__/fixtures/deep_toc.json +2953 -0
  37. package/src/__tests__/fixtures/flat_toc.json +2917 -0
  38. package/src/__tests__/fixtures/physdim.json +294 -0
  39. package/src/__tests__/fixtures/region_target.json +58 -0
  40. package/src/__tests__/fixtures/wunder.jpg +0 -0
  41. package/src/__tests__/parser.test.ts +42 -0
  42. package/src/__tests__/pdf.spec.ts +216 -0
  43. package/src/__tests__/region.test.ts +194 -0
  44. package/src/__tests__/setupJest.ts +2 -0
  45. package/src/convert.ts +1098 -0
  46. package/src/download.ts +703 -0
  47. package/src/global.d.ts +10 -0
  48. package/src/iiif.ts +605 -0
  49. package/src/index.ts +7 -0
  50. package/src/io.ts +243 -0
  51. package/src/log.ts +51 -0
  52. package/src/metrics.ts +47 -0
  53. package/src/ocr.ts +176 -0
  54. package/src/optimization.ts +201 -0
  55. package/src/optimization.worker.ts +118 -0
  56. package/src/pdf/annos-text.ts +382 -0
  57. package/src/pdf/annos.ts +240 -0
  58. package/src/pdf/common.ts +158 -0
  59. package/src/pdf/generator.ts +1665 -0
  60. package/src/pdf/image.ts +340 -0
  61. package/src/pdf/parser.ts +811 -0
  62. package/src/pdf/pkzip.ts +228 -0
  63. package/src/pdf/png.ts +397 -0
  64. package/src/pdf/util.ts +111 -0
  65. package/src/res/licenses.ts +266 -0
  66. package/src/res/srgbColorspace.ts +405 -0
  67. package/src/types.d.ts +6 -0
  68. package/src/util.ts +55 -0
  69. package/src/version.ts +1 -0
@@ -0,0 +1,1665 @@
1
+ /* eslint-disable no-new-wrappers */
2
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
3
+
4
+ /// PDF generation code
5
+ // FIXME: This is currently one hell of a mess, learning about PDF and coming up
6
+ // with good abstractions at the same time was too much of a challenge for me 🙈
7
+ import dedent from 'dedent-js';
8
+ import { Manifest } from '@iiif/presentation-3';
9
+ import { Manifest as ManifestV2 } from '@iiif/presentation-2';
10
+ import { OcrPage, OcrBlock, OcrParagraph, OcrLine, OcrWord } from 'ocr-parser';
11
+
12
+ import {
13
+ Metadata,
14
+ PdfObject,
15
+ PdfDictionary,
16
+ makeRef,
17
+ PdfArray,
18
+ PdfRef,
19
+ serialize,
20
+ PdfValue,
21
+ toUTF16BE,
22
+ StructTreeEntry,
23
+ } from './common.js';
24
+ import { TocItem, textEncoder, randomData, tryDeflateStream } from './util.js';
25
+ import { ArrayReader, Writer } from '../io.js';
26
+ import { OcrPageWithMarkup } from '../ocr.js';
27
+ import PdfImage, { JPEGImage, PNGImage } from './image.js';
28
+ import { PdfParser } from './parser.js';
29
+ import pdiiifVersion from '../version.js';
30
+ import log from '../log.js';
31
+ import {
32
+ CanvasImage,
33
+ ImageFetchFailure,
34
+ StartCanvasInfo,
35
+ isImageFetchFailure,
36
+ } from '../download.js';
37
+ import { Annotation, CanvasInfo, getI18nValue } from '../iiif.js';
38
+ import {
39
+ buildCentralFileDirectory,
40
+ buildLocalZipHeader,
41
+ CentralDirectoryFileSpec,
42
+ } from './pkzip.js';
43
+ import { crc32 } from '../util.js';
44
+ import { exportPdfAnnotation } from './annos.js';
45
+ import type { AnnotationFont } from './annos-text.js';
46
+ import {
47
+ annotationFontFaces,
48
+ exportPdfText,
49
+ } from './annos-text.js';
50
+ import { OptimizationParams } from '../optimization.js';
51
+
52
+ const PRODUCER = `pdiiif v${pdiiifVersion}`;
53
+
54
+ /// If the font is 10 pts, nominal character width is 5 pts
55
+ const CHAR_WIDTH = 2;
56
+
57
+ /// Taken from tesseract@2d6f38eebf9a14d9fbe65d785f0d7bd898ff46cb, tessdata/pdf.ttf
58
+ /// Created by Ken Sharp
59
+ /// (C) Copyright 2011, Google Inc.
60
+ /// Licensed under the Apache License, Version 2.0 (the "License");
61
+ /// you may not use this file except in compliance with the License.
62
+ /// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
63
+ /// Unless required by applicable law or agreed to in writing, software
64
+ /// distributed under the License is distributed on an "AS IS" BASIS,
65
+ /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
66
+ /// See the License for the specific language governing permissions and
67
+ /// limitations under the License.
68
+ const FONTDATA = new Uint8Array([
69
+ 0, 1, 0, 0, 0, 10, 0, 128, 0, 3, 0, 32, 79, 83, 47, 50, 86, 222, 200, 148, 0,
70
+ 0, 1, 40, 0, 0, 0, 96, 99, 109, 97, 112, 0, 10, 0, 52, 0, 0, 1, 144, 0, 0, 0,
71
+ 30, 103, 108, 121, 102, 21, 34, 65, 36, 0, 0, 1, 184, 0, 0, 0, 24, 104, 101,
72
+ 97, 100, 11, 120, 241, 101, 0, 0, 0, 172, 0, 0, 0, 54, 104, 104, 101, 97, 12,
73
+ 2, 4, 2, 0, 0, 0, 228, 0, 0, 0, 36, 104, 109, 116, 120, 4, 0, 0, 0, 0, 0, 1,
74
+ 136, 0, 0, 0, 8, 108, 111, 99, 97, 0, 12, 0, 0, 0, 0, 1, 176, 0, 0, 0, 6, 109,
75
+ 97, 120, 112, 0, 4, 0, 5, 0, 0, 1, 8, 0, 0, 0, 32, 110, 97, 109, 101, 242,
76
+ 235, 22, 218, 0, 0, 1, 208, 0, 0, 0, 75, 112, 111, 115, 116, 0, 1, 0, 1, 0, 0,
77
+ 2, 28, 0, 0, 0, 32, 0, 1, 0, 0, 0, 1, 0, 0, 176, 148, 113, 16, 95, 15, 60,
78
+ 245, 4, 7, 8, 0, 0, 0, 0, 0, 207, 154, 252, 110, 0, 0, 0, 0, 212, 195, 167,
79
+ 242, 0, 0, 0, 0, 4, 0, 8, 0, 0, 0, 0, 16, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
80
+ 8, 0, 255, 255, 0, 0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81
+ 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 2, 0, 4, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
82
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 144, 0, 5, 0, 0, 0, 0,
83
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 1, 0, 1, 0,
84
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 79, 79, 71, 0,
85
+ 64, 0, 0, 0, 0, 0, 1, 255, 255, 0, 0, 0, 1, 0, 1, 128, 0, 0, 0, 0, 0, 0, 0, 0,
86
+ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0,
87
+ 0, 0, 20, 0, 3, 0, 0, 0, 0, 0, 20, 0, 6, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88
+ 0, 0, 0, 12, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 8, 0, 0, 3, 0, 0, 49, 33, 17, 33,
89
+ 4, 0, 252, 0, 8, 0, 0, 0, 0, 3, 0, 42, 0, 0, 0, 3, 0, 0, 0, 5, 0, 22, 0, 0, 0,
90
+ 1, 0, 0, 0, 0, 0, 5, 0, 11, 0, 22, 0, 3, 0, 1, 4, 9, 0, 5, 0, 22, 0, 0, 0, 86,
91
+ 0, 101, 0, 114, 0, 115, 0, 105, 0, 111, 0, 110, 0, 32, 0, 49, 0, 46, 0, 48,
92
+ 86, 101, 114, 115, 105, 111, 110, 32, 49, 46, 48, 0, 0, 1, 0, 0, 0, 0, 0, 0,
93
+ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
94
+ ]);
95
+
96
+ type ZipDummyObjectSpec = {
97
+ filename: string;
98
+ data: Uint8Array;
99
+ deflatedData?: Uint8Array;
100
+ bytesUntilActualData: number;
101
+ };
102
+
103
+ export type GeneratorParams = {
104
+ // Writer to output the PDF to
105
+ writer: Writer;
106
+ // Metadata to include in the PDF
107
+ metadata: Metadata;
108
+ // Information about canvases included in the PDF
109
+ canvasInfos: CanvasInfo[];
110
+ // List of languages to use for rendering labels, in descending order of preference
111
+ langPref: readonly string[];
112
+ // Labels for pages, every position corresponds to the canvas in the same position
113
+ pageLabels?: string[];
114
+ // Outline tree for the PDF
115
+ outline: TocItem[];
116
+ // Whether the PDF should include a hidden text layer
117
+ hasText?: boolean;
118
+ // Render IIIF annotations as visible text instead of PDF annotations
119
+ annotationsAsText?: boolean;
120
+ // Standard PDF font family used when rendering visible annotation text
121
+ annotationFont?: AnnotationFont;
122
+ // Reading direction of the PDF
123
+ readingDirection?: 'right-to-left' | 'left-to-right';
124
+ // Information about the canvas (or canvas region) that should be displayed initially
125
+ initialCanvas?: StartCanvasInfo;
126
+ // The manifest to build the PDF from
127
+ manifestJson?: Manifest | ManifestV2;
128
+ // If this is enabled, the PDF will also be a valid ZIP archive of all the resources
129
+ // included in the PDF
130
+ zipPolyglot?: boolean;
131
+ // Base directory name for the polyglot ZIP archive, if not set the resources will be
132
+ // top-level in the archive
133
+ zipBaseDir?: string;
134
+ // Optimize images to reduce size
135
+ optimization?: OptimizationParams;
136
+ };
137
+
138
+ /** Streaming PDF generator based on a IIIF manifest.
139
+ *
140
+ * This class is responsible for generating a PDF document based on a IIIF manifest.
141
+ * It is designed to be used in a streaming fashion, i.e. it can start writing the PDF
142
+ * before all the resources have been loaded and thus does not require a huge amount
143
+ * of memory. On the flipside, this makes the code a lot more complex, since we need
144
+ * to keep track of the PDF's internal state and write objects in the correct order.
145
+ * Another complication is that we want to write out the catalog and page tree first
146
+ * to allow viewers to quickly display the first page, which requires a bunch of
147
+ * complicated pre-allocation of objects.
148
+ *
149
+ * FIXME: Can't we just write the pages first and then the catalog and page tree at
150
+ * the end of the file? Would make things *A LOT* easier and less complex and
151
+ * error-prone.
152
+ */
153
+ export default class PDFGenerator {
154
+ // Keep track of how many bytes have been written so far
155
+ _offset = 0;
156
+ // PDF objects that are scheduled for writing, will be written on _flush()
157
+ _objects: Array<PdfObject> = [];
158
+ // Number of the next PDF object
159
+ _nextObjNo = 1;
160
+ // References to various central objects
161
+ _objRefs: Record<string, PdfRef> = {};
162
+ // Tracks offset of every XObject
163
+ _offsets: number[] = [];
164
+ // Writer used for outputting the PDF
165
+ _writer: Writer | undefined;
166
+ // Have we already started writing the IIIF pages?
167
+ _pagesStarted = false;
168
+ // Information about each canvas, needed for pre-allocating objects
169
+ _canvasInfos: Array<CanvasInfo> = [];
170
+ // Object number of the first page
171
+ _firstPageObjectNum: number | undefined;
172
+ // Labels for every page in the PDF
173
+ _pageLabels?: string[];
174
+ // Number of cover pages inserted at the beginning of the PDF
175
+ _numCoverPages = 0;
176
+ // PDF outline
177
+ _outline: TocItem[] = [];
178
+ // Is the PDF supposed to have a hidden text layer?
179
+ _hasText = false;
180
+ // List of top-level entries in the PDF's logical structure tree
181
+ _strucTree: StructTreeEntry[] = [];
182
+ // Maps a page's object number to the marked content sequence IDs its content
183
+ // stream has
184
+ _pageMCIds: Map<number, Array<number>> = new Map();
185
+ // Identifier of the next structure parent entry
186
+ _nextStructParentId = 0;
187
+ // For every page, its corresponding parent ID for the parent tree
188
+ _pageParentIds: Map<number, number> = new Map();
189
+ // Language preference
190
+ _langPref: readonly string[];
191
+ _initialCanvas?: StartCanvasInfo;
192
+ private _polyglot: boolean;
193
+ private _manifestJson?: Manifest | ManifestV2;
194
+ private _zipCatalog?: Array<CentralDirectoryFileSpec>;
195
+ private _zipBaseDir?: string;
196
+ private _readingDirection: 'right-to-left' | 'left-to-right';
197
+ private _annotationsAsText: boolean;
198
+ private _annotationFont: AnnotationFont;
199
+ // FIXME: Overlap with _objRefs, should be unified
200
+ private _deferredReferences = new Map<string, PdfRef>();
201
+
202
+ /** Just basic setup of state, real setup is done in setup()
203
+ method since we need to call a bunch of async stuff */
204
+ constructor({
205
+ writer,
206
+ metadata,
207
+ canvasInfos,
208
+ langPref,
209
+ pageLabels,
210
+ outline = [],
211
+ readingDirection = 'left-to-right',
212
+ hasText = false,
213
+ annotationsAsText = false,
214
+ annotationFont = 'Helvetica',
215
+ initialCanvas,
216
+ manifestJson,
217
+ zipPolyglot = false,
218
+ zipBaseDir,
219
+ }: GeneratorParams) {
220
+ this._writer = writer;
221
+ this._canvasInfos = canvasInfos;
222
+ this._pageLabels = pageLabels;
223
+ this._outline = outline;
224
+ this._hasText = hasText;
225
+ this._annotationsAsText = annotationsAsText;
226
+ this._annotationFont = annotationFont;
227
+ this._readingDirection = readingDirection;
228
+ this._langPref = langPref;
229
+ this._initialCanvas = initialCanvas;
230
+ this._polyglot = zipPolyglot;
231
+ this._zipBaseDir = zipBaseDir;
232
+ this._manifestJson = manifestJson;
233
+
234
+ const pdfMetadata: PdfDictionary = {
235
+ ...Object.entries(metadata)
236
+ .filter((k, v) => v !== undefined)
237
+ .reduce((prev, [k, v]) => {
238
+ prev[k] = `(${v})`;
239
+ return prev;
240
+ }, {} as PdfDictionary),
241
+ Producer: `(${PRODUCER})`,
242
+ };
243
+ this._addObject(pdfMetadata, 'Info');
244
+ }
245
+
246
+ /** Set up the basic PDF document, creating neccessary objects. */
247
+ async setup(): Promise<void> {
248
+ // Add the catalog object, will be updated later
249
+ const catalog: PdfDictionary = {
250
+ Type: '/Catalog',
251
+ };
252
+ this._addObject(catalog, 'Catalog');
253
+
254
+ // Pages Dictionary, will be updated later
255
+ const pagesObj = this._addObject(
256
+ {
257
+ Type: '/Pages',
258
+ Count: this._canvasInfos.length,
259
+ },
260
+ 'Pages'
261
+ );
262
+ catalog.Pages = makeRef(pagesObj);
263
+
264
+ // Indicate that our PDF contains structure information, attached to the text layer
265
+ if (this._hasText) {
266
+ catalog.MarkInfo = {
267
+ Type: '/MarkInfo',
268
+ Marked: true,
269
+ };
270
+ }
271
+
272
+ if (this._outline.length > 0) {
273
+ // If we have an outline, display the ToC by default in PDF viewers and set up
274
+ // the required objects
275
+ catalog.PageMode = '/UseOutlines';
276
+ const outlines: PdfDictionary = {
277
+ Type: '/Outlines',
278
+ Count: 0,
279
+ };
280
+ const outlinesObj = this._addObject(outlines);
281
+ catalog.Outlines = makeRef(outlinesObj);
282
+ let prev: PdfObject | undefined;
283
+ for (const [idx, itm] of this._outline.entries()) {
284
+ const [childObj, numKids] = this._addOutline(itm, outlinesObj, prev);
285
+ (outlines.Count as number) += 1 + numKids;
286
+ if (idx === 0) {
287
+ outlines.First = makeRef(childObj);
288
+ } else if (idx === this._outline.length - 1) {
289
+ outlines.Last = makeRef(childObj);
290
+ }
291
+ prev = childObj;
292
+ }
293
+ } else {
294
+ // Otherwise, display the thumbnails in PDF viewers
295
+ catalog.PageMode = '/UseThumbs';
296
+ }
297
+
298
+ // Adjust reading direction to RTL if neccessary
299
+ catalog.ViewerPreferences = {
300
+ Direction: this._readingDirection === 'right-to-left' ? '/R2L' : '/L2R',
301
+ };
302
+
303
+ if (this._hasText) {
304
+ await this._setupHiddenTextFont();
305
+ }
306
+ if (this._annotationsAsText) {
307
+ for (const { resourceName, baseFont } of annotationFontFaces(
308
+ this._annotationFont
309
+ )) {
310
+ this._addObject(
311
+ {
312
+ Type: '/Font',
313
+ Subtype: '/Type1',
314
+ BaseFont: `/${baseFont}`,
315
+ Encoding: '/WinAnsiEncoding',
316
+ },
317
+ resourceName
318
+ );
319
+ }
320
+ }
321
+ }
322
+
323
+ /** Set up neccessary fonts for the hidden text layer. */
324
+ async _setupHiddenTextFont(): Promise<void> {
325
+ const typeZeroFont = this._addObject(
326
+ {
327
+ Type: '/Font',
328
+ Subtype: '/Type0',
329
+ BaseFont: '/GlyphLessFont',
330
+ Encoding: '/Identity-H',
331
+ },
332
+ 'Type0Font'
333
+ );
334
+
335
+ const typeTwoFont = this._addObject({
336
+ type: '/Font',
337
+ Subtype: '/CIDFontType2',
338
+ BaseFont: '/GlyphLessFont',
339
+ DW: 1000 / CHAR_WIDTH,
340
+ CIDSystemInfo: {
341
+ Ordering: '(Identity)',
342
+ Registry: '(Adobe)',
343
+ Supplement: 0,
344
+ },
345
+ });
346
+ (typeZeroFont.data as PdfDictionary).DescendantFonts = [
347
+ makeRef(typeTwoFont),
348
+ ];
349
+
350
+ // Set up character id to glyph id mapping
351
+ const cidtoGidMapData = new Uint8Array(128 * 1024);
352
+ for (let i = 0; i < cidtoGidMapData.length; i++) {
353
+ cidtoGidMapData[i] = i % 2 ? 1 : 0;
354
+ }
355
+ const comp = await tryDeflateStream(cidtoGidMapData);
356
+ const cidToGidMap = this._addObject(comp.dict, undefined, comp.stream);
357
+ (typeTwoFont.data as PdfDictionary).CIDToGIDMap = makeRef(cidToGidMap);
358
+
359
+ // Set up character code to unicode codepoint mapping
360
+ // Effectively an identity mapping, since in our font every character code
361
+ // exactly corresponds to the unicode codepoint
362
+ const cmapStream = dedent`
363
+ /CIDInit /ProcSet findresource begin
364
+ 12 dict begin
365
+ begincmap
366
+ /CIDSystemInfo
367
+ <<
368
+ /Registry (Adobe)
369
+ /Ordering (UCS)
370
+ /Supplement 0
371
+ >> def
372
+ /CMapName /Identity-H def
373
+ /CMapType 2 def
374
+ 1 begincodespacerange
375
+ <0000> <FFFF>
376
+ endcodespacerange
377
+ 1 beginbfrange
378
+ <0000> <FFFF> <0000>
379
+ endbfrange
380
+ endcmap
381
+ CMapName currentdict /CMap defineresource pop
382
+ end
383
+ end`;
384
+ const cmap = this._addObject(
385
+ {
386
+ Length: cmapStream.length,
387
+ },
388
+ undefined,
389
+ cmapStream
390
+ );
391
+ (typeZeroFont.data as PdfDictionary).ToUnicode = makeRef(cmap);
392
+
393
+ // Set up the font descriptor for our hidden text font
394
+ const fontDesc = this._addObject({
395
+ Type: '/FontDescriptor',
396
+ FontName: '/GlyphLessFont',
397
+ FontBBox: [0, 0, 1000 / CHAR_WIDTH, 1000],
398
+ Ascent: 1000,
399
+ CapHeight: 1000,
400
+ Descent: -1,
401
+ Flags: 5,
402
+ ItalicAngle: 0,
403
+ StemV: 80,
404
+ });
405
+ (typeTwoFont.data as PdfDictionary).FontDescriptor = makeRef(fontDesc);
406
+
407
+ const maybeCompressedFont = await tryDeflateStream(FONTDATA);
408
+ const fontDataObj = this._addObject(
409
+ {
410
+ Length1: FONTDATA.length,
411
+ ...maybeCompressedFont.dict,
412
+ },
413
+ undefined,
414
+ maybeCompressedFont.stream
415
+ );
416
+ (fontDesc.data as PdfDictionary).FontFile2 = makeRef(fontDataObj);
417
+ }
418
+
419
+ /** Register embedded OCR files in the PDF's catalog object. */
420
+ _registerEmbeddedFilesInCatalog() {
421
+ const catalog = this._objects[this._objRefs.Catalog.refObj]
422
+ .data as PdfDictionary;
423
+ const embeddedFiles: PdfArray = [
424
+ `(manifest.json)`,
425
+ makeRef(this._firstPageObjectNum! - (this._polyglot ? 3 : 2)),
426
+ ];
427
+ for (const [idx, canvas] of this._canvasInfos.entries()) {
428
+ if (!canvas.ocr) {
429
+ continue;
430
+ }
431
+ const pageObjNum = this.getCanvasObjectNumber(idx);
432
+ // The file spec for embedded OCR file is the previous to last XObject for a given canvas
433
+ let fileObjNum = pageObjNum + this.getObjectsPerCanvas(idx) - 2;
434
+ if (this._polyglot) {
435
+ // Except if the PDF is polyglot, then it's the second to last XObject
436
+ fileObjNum -= 1;
437
+ }
438
+ embeddedFiles.push(`(${canvas.ocr.id})`);
439
+ embeddedFiles.push(makeRef(fileObjNum));
440
+ }
441
+ if (!catalog.Names) {
442
+ catalog.Names = {
443
+ EmbeddedFiles: { Names: embeddedFiles },
444
+ };
445
+ } else {
446
+ const names = catalog.Names as PdfDictionary;
447
+ const nameTree = names.EmbeddedFiles as PdfDictionary;
448
+ nameTree.Names = (nameTree.Names as PdfArray).concat(embeddedFiles);
449
+ }
450
+ }
451
+
452
+ /** Create a PdfRef whose value is deferred, i.e. will be set at a later stage.
453
+ *
454
+ * Useful for bidirectional references.
455
+ *
456
+ * Prevents serialization of objects containing this reference as long as the
457
+ * value is not set.
458
+ *
459
+ * @param key A unique key to identify the reference
460
+ */
461
+ _makeDeferredReference(key: string): PdfRef {
462
+ if (!this._deferredReferences.has(key)) {
463
+ // Placeholder reference
464
+ const ref = makeRef(-1);
465
+ this._deferredReferences.set(key, ref);
466
+ }
467
+ return this._deferredReferences.get(key)!;
468
+ }
469
+
470
+ /** Add items to the PDF's outline, based on the passed TocItem tree.
471
+ *
472
+ * @param itm The item we want to add to the outline
473
+ * @param parent The parent outline item
474
+ * @param prev The preceding sibling outline item, if present
475
+ * @returns A tuple containing the object reference of the added outline item and the number
476
+ * of children outline items that were created
477
+ */
478
+ _addOutline(
479
+ itm: TocItem,
480
+ parent: PdfObject,
481
+ prev?: PdfObject
482
+ ): [PdfObject, number] {
483
+ let dest: PdfArray;
484
+ if (typeof itm.startCanvas === 'string') {
485
+ // Simple case, just linke to a whole canvas/page
486
+ const destCanvasIdx = this._canvasInfos.findIndex(
487
+ (ci) => ci.canvas.id === itm.startCanvas
488
+ );
489
+ if (destCanvasIdx < 0) {
490
+ throw Error(
491
+ `Could not find canvas with id ${itm.startCanvas} in manifest!`
492
+ );
493
+ }
494
+ dest = [destCanvasIdx, '/Fit'];
495
+ } else {
496
+ // More complex: link to a specific region on a canvas
497
+ const canvasId = itm.startCanvas.id;
498
+ const unitScale = 72 / itm.startCanvas.ppi;
499
+ const rect = itm.startCanvas.position;
500
+ const { width, height } = itm.startCanvas.dimensions;
501
+ const destCanvasIdx = this._canvasInfos.findIndex(
502
+ (ci) => ci.canvas.id === canvasId
503
+ );
504
+ if (destCanvasIdx < 0) {
505
+ throw Error(`Could not find canvas with id ${canvasId} in manifest!`);
506
+ }
507
+ dest = [
508
+ destCanvasIdx,
509
+ '/FitR',
510
+ // TODO: Thoroughly test that this is actually working!
511
+ unitScale * rect.x, // left
512
+ unitScale * rect.y, // bottom
513
+ unitScale * (width - (rect.x + rect.width)), // right,
514
+ unitScale * (height - (rect.y + rect.height)), // top,
515
+ ];
516
+ }
517
+
518
+ const rec: PdfDictionary = {
519
+ Title: `( ${itm.label} )`,
520
+ Parent: makeRef(parent),
521
+ // NOTE: The first entry is a number only during setup and will later be
522
+ // replaced with a reference to the actual page object, once we know
523
+ // how many objects are preceding the page objects.
524
+ Dest: dest,
525
+ };
526
+ const obj = this._addObject(rec);
527
+ if (prev) {
528
+ rec.Prev = makeRef(prev);
529
+ (prev.data as PdfDictionary).Next = makeRef(obj);
530
+ }
531
+
532
+ if (itm.children?.length) {
533
+ // Recursively add children
534
+ let prev: PdfObject | undefined;
535
+ rec.Count = 0;
536
+ for (const [idx, child] of itm.children.entries()) {
537
+ const [childObj, numChildren] = this._addOutline(child, obj, prev);
538
+ if (idx === 0) {
539
+ rec.First = makeRef(childObj);
540
+ } else if (idx === itm.children.length - 1) {
541
+ rec.Last = makeRef(childObj);
542
+ }
543
+ rec.Count = rec.Count + 1 + numChildren;
544
+ prev = childObj;
545
+ }
546
+ }
547
+ return [obj, (rec.Count as number) ?? 0];
548
+ }
549
+
550
+ /** Add a new object to the PDF document.
551
+ *
552
+ * @param val A PDF value, can be any of the supported types.
553
+ * @param refName An optional name to reference the object by.
554
+ * @param stream An optional stream to attach to the object, value must be adictionary in this case
555
+ * @returns The created object
556
+ */
557
+ _addObject(
558
+ val: PdfValue,
559
+ refName?: string,
560
+ stream?: Uint8Array | string
561
+ ): PdfObject {
562
+ const isObject = (x: unknown): x is object =>
563
+ typeof x === 'object' && x !== null;
564
+ if (stream) {
565
+ if (!isObject(val)) {
566
+ throw new Error(
567
+ 'PDF Objects with a stream must have a dictionary as its value'
568
+ );
569
+ }
570
+ if (!(val as PdfDictionary).Length) {
571
+ (val as PdfDictionary).Length = stream.length;
572
+ }
573
+ }
574
+ const obj = {
575
+ num: this._nextObjNo,
576
+ data: val,
577
+ stream,
578
+ };
579
+ this._nextObjNo++;
580
+ this._objects[obj.num] = obj;
581
+ if (refName) {
582
+ this._objRefs[refName] = makeRef(obj);
583
+ }
584
+ return obj;
585
+ }
586
+
587
+ /** Clone an object from a foreign PDF into the current PDF, adjusting
588
+ * the encountered indirect object references.
589
+ *
590
+ * @param parser PdfParser instance for the PDF the object is from
591
+ * @param obj The object to transplant into our document
592
+ * @param seenObjects A map of object numbers to known references, used to avoid
593
+ * infinite recursion
594
+ * @returns A reference to the transplanted object
595
+ */
596
+ private async _transplantObject(
597
+ parser: PdfParser,
598
+ obj: PdfObject,
599
+ seenObjects: Record<number, PdfRef> = {}
600
+ ): Promise<PdfRef> {
601
+ const handleValue = async (value: PdfValue): Promise<PdfValue> => {
602
+ if (value instanceof PdfRef) {
603
+ const o = await parser.resolveRef(value);
604
+ if (o === undefined) {
605
+ throw `Could not resolve reference to object '${value.refObj}'`;
606
+ }
607
+ // Check if we've already transplanted the object
608
+ if (seenObjects[o.num]) {
609
+ return seenObjects[o.num];
610
+ }
611
+ const objDict = o.data as PdfDictionary;
612
+ const newObj = this._addObject(objDict, undefined, o.stream);
613
+ const ref = new PdfRef(newObj.num);
614
+ seenObjects[o.num] = ref;
615
+ newObj.data = await handleValue(objDict);
616
+ if (objDict.Type === '/Page') {
617
+ // Redirect to our own Pages object
618
+ (newObj.data as PdfDictionary).Parent = this._objRefs.Pages;
619
+ }
620
+ return ref;
621
+ } else if (typeof value === 'string' && value[0] != '/') {
622
+ return `(${value})`;
623
+ } else if (Array.isArray(value)) {
624
+ const out = [];
625
+ for (const val of value) {
626
+ out.push(await handleValue(val));
627
+ }
628
+ return out;
629
+ } else if (typeof value === 'object' && value !== null) {
630
+ const out: PdfDictionary = {};
631
+ for (const [key, val] of Object.entries(value)) {
632
+ // Ignore structure keys for now
633
+ if (key === 'StructParent' || key === 'StructParents') {
634
+ continue;
635
+ }
636
+ out[key] = await handleValue(val as PdfDictionary);
637
+ }
638
+ return out;
639
+ }
640
+ return value;
641
+ };
642
+ const ref = new PdfRef(obj.num);
643
+ // TODO: Special case: if the object is a page, we need to check for
644
+ // a /StructParents key, check for the /StructTreeRoot key in
645
+ // the catalog, and then transplant that to our _strucTree
646
+ // and _pageMCIDs structures. Quite the handful!!
647
+ return (await handleValue(ref)) as PdfRef;
648
+ }
649
+
650
+ /** Insert cover pages from another PDF into our document. */
651
+ async insertCoverPages(pdfData: ArrayBuffer): Promise<void> {
652
+ if (this._pagesStarted) {
653
+ throw 'Cover pages must be inserted before writing the first regular page';
654
+ }
655
+ const reader = new ArrayReader(new Uint8Array(pdfData));
656
+ const parser = await PdfParser.parse(reader);
657
+ const pagesDict = this._objects[this._objRefs.Pages.refObj]
658
+ .data as PdfDictionary;
659
+ pagesDict.Kids = [];
660
+ // TODO: Parse and transplant the section and parent trees from
661
+ // the catalog into our own structures.
662
+ for await (const page of parser.pages()) {
663
+ const dict = page.data as PdfDictionary;
664
+ // Ignore associated structured content for now
665
+ delete dict.StructParents;
666
+ delete dict.Parent;
667
+ const newPageRef = await this._transplantObject(parser, page);
668
+ (pagesDict.Kids as PdfArray).push(newPageRef);
669
+ (pagesDict.Count as number) += 1;
670
+ this._numCoverPages += 1;
671
+ }
672
+ return;
673
+ }
674
+
675
+ /** Embed a file resource in the PDF.
676
+ *
677
+ * @param filename The filename for the embedded resource
678
+ * @param description A description of the file
679
+ * @param mimeType The MIME type of the file
680
+ * @param data The data to embed
681
+ */
682
+ private async _embedResource(
683
+ filename: string,
684
+ description: string,
685
+ mimeType: string,
686
+ data: string
687
+ ): Promise<void> {
688
+ // TODO: Add check that the file is actually pre-registered in
689
+ // the catalog!
690
+ const fileSpec: PdfDictionary = {
691
+ Type: '/Filespec',
692
+ F: `(${filename})`,
693
+ UF: toUTF16BE(filename),
694
+ Desc: `(${description})`,
695
+ EF: {
696
+ F: makeRef(this._nextObjNo + (this._polyglot ? 2 : 1)),
697
+ },
698
+ };
699
+
700
+ const maybeCompressed = await tryDeflateStream(data);
701
+ const embeddedFile = {
702
+ Type: '/EmbeddedFile',
703
+ Subtype: `(${mimeType})`,
704
+ ...maybeCompressed.dict,
705
+ };
706
+
707
+ this._addObject(fileSpec);
708
+ if (this._polyglot) {
709
+ let zipData: Uint8Array;
710
+ if (typeof data === 'string') {
711
+ zipData = textEncoder.encode(data);
712
+ } else {
713
+ zipData = data;
714
+ }
715
+ const extraDataLength = this._getSerializedSize(
716
+ {
717
+ num: this._nextObjNo + 2,
718
+ data: { ...embeddedFile, ...maybeCompressed.dict },
719
+ stream: maybeCompressed.stream,
720
+ },
721
+ true
722
+ );
723
+ this._insertZipHeaderDummyObject({
724
+ filename,
725
+ data: zipData,
726
+ deflatedData: maybeCompressed.dict.Filter
727
+ ? (maybeCompressed.stream as Uint8Array)
728
+ : undefined,
729
+ // 2 bytes zlib header of deflated data
730
+ bytesUntilActualData: extraDataLength + 2,
731
+ });
732
+ }
733
+ this._addObject(embeddedFile, undefined, maybeCompressed.stream);
734
+ }
735
+
736
+ /** Embed the IIIF Manifest JSON in the PDF.
737
+ *
738
+ * @param manifestJson The IIIF (v2 or v3) Manifest to embed
739
+ */
740
+ private async _embedManifest(
741
+ manifestJson: ManifestV2 | Manifest
742
+ ): Promise<void> {
743
+ let manifestMime = 'application/ld+json';
744
+ if (Array.isArray(manifestJson['@context'])) {
745
+ const manifestProfile = manifestJson['@context'].find((p) =>
746
+ p.startsWith('http://iiif.io/api/presentation')
747
+ );
748
+ if (manifestProfile) {
749
+ manifestMime += `;profile="${manifestProfile}"`;
750
+ }
751
+ } else if (manifestJson['@context']) {
752
+ manifestMime += `;profile="${manifestJson['@context']}"`;
753
+ }
754
+ await this._embedResource(
755
+ 'manifest.json',
756
+ 'IIIF Manifest this PDF is based on',
757
+ manifestMime,
758
+ JSON.stringify(manifestJson)
759
+ );
760
+ }
761
+
762
+ /** Once all setup is complete and we begin rendering pages into the document,
763
+ * we need to finalize the PDF header with the remaining information.
764
+ */
765
+ async finalizePdfHeader(): Promise<void> {
766
+ const catalog = this._objects[this._objRefs.Catalog.refObj]
767
+ .data as PdfDictionary;
768
+
769
+ // Create page tree with page labels
770
+ if (this._pageLabels) {
771
+ catalog.PageLabels = makeRef(
772
+ this._addObject({
773
+ Nums: this._pageLabels
774
+ .map((label, idx) =>
775
+ label
776
+ ? [idx + this._numCoverPages, { P: `( ${label} )` }]
777
+ : undefined
778
+ )
779
+ .filter((x) => x !== undefined)
780
+ .flat() as PdfArray,
781
+ })
782
+ );
783
+ }
784
+
785
+ const pagesObj = this._objects[this._objRefs.Pages.refObj];
786
+
787
+ // Now that we know from which object number the pages start, we can set the
788
+ // /Kids entry in the Pages object and update the outline destinations.
789
+ const pageDict = pagesObj.data as PdfDictionary;
790
+ if (!pageDict.Kids) {
791
+ pageDict.Kids = [];
792
+ }
793
+ this._firstPageObjectNum = this._nextObjNo;
794
+ if (this._manifestJson) {
795
+ this._firstPageObjectNum += 2;
796
+ if (this._polyglot) {
797
+ this._firstPageObjectNum++;
798
+ }
799
+ }
800
+ for (const [idx] of this._canvasInfos.entries()) {
801
+ (pageDict.Kids as PdfArray).push(
802
+ makeRef(this.getCanvasObjectNumber(idx))
803
+ );
804
+ }
805
+ this._objects
806
+ // Get ToC entry object, the first destination will be the canvas index
807
+ .filter((obj) => (obj.data as PdfDictionary)?.Dest !== undefined)
808
+ .forEach((obj: PdfObject) => {
809
+ const dest = (obj.data as PdfDictionary).Dest as PdfArray;
810
+ if (typeof dest[0] !== 'number') {
811
+ return;
812
+ }
813
+ dest[0] = makeRef(this.getCanvasObjectNumber(dest[0]));
814
+ });
815
+
816
+ // Register the structural content tree root
817
+ if (this._hasText) {
818
+ catalog.StructTreeRoot = makeRef(
819
+ this._nextObjNo + this.totalCanvasObjects
820
+ );
821
+ }
822
+
823
+ // Register the optional content groups, if present
824
+ if (this._canvasInfos.some((ci) => ci.images.some((i) => i.choiceInfo))) {
825
+ // We're *very* explicit with the visibility of the various OCGs to
826
+ // ensure as broad a viewer support as possible (especially pdf.js
827
+ // needed it...)
828
+ const initiallyEnabledOCGs: PdfRef[] = [];
829
+ const initiallyDisabledOCGs: PdfRef[] = [];
830
+ const allOCGs: PdfRef[] = [];
831
+ const rbGroups: PdfRef[][] = [];
832
+ for (const [canvasIdx, { images }] of this._canvasInfos.entries()) {
833
+ const pageObjNum = this.getCanvasObjectNumber(canvasIdx);
834
+ let ocgStart = pageObjNum + 2 + images.length;
835
+ if (this._polyglot) {
836
+ // Take 'dummy' objects for ZIP polyglot into account
837
+ ocgStart += images.length;
838
+ }
839
+ let ocgIdx = 0;
840
+ const rbGroup = [];
841
+ for (const img of images) {
842
+ if (!img.choiceInfo) {
843
+ continue;
844
+ }
845
+ const ref = makeRef(ocgStart + ocgIdx);
846
+ if (img.choiceInfo.enabled) {
847
+ initiallyEnabledOCGs.push(ref);
848
+ } else {
849
+ initiallyDisabledOCGs.push(ref);
850
+ }
851
+ allOCGs.push(ref);
852
+ rbGroup.push(ref);
853
+ ocgIdx++;
854
+ }
855
+ rbGroups.push(rbGroup);
856
+ }
857
+ catalog.OCProperties = {
858
+ OCGs: allOCGs,
859
+ D: {
860
+ BaseState: '/OFF',
861
+ ON: initiallyEnabledOCGs,
862
+ OFF: initiallyDisabledOCGs,
863
+ RBGroups: rbGroups,
864
+ },
865
+ };
866
+ }
867
+
868
+ // Set the initial view of the PDF
869
+ if (typeof this._initialCanvas === 'string') {
870
+ // ...to a whole page
871
+ catalog.OpenAction = [
872
+ makeRef(
873
+ this.getCanvasObjectNumber(
874
+ this._canvasInfos.findIndex(
875
+ (ci) => ci.canvas.id === this._initialCanvas
876
+ )
877
+ )
878
+ ),
879
+ ];
880
+ } else if (this._initialCanvas) {
881
+ // ...to a specific region on a page
882
+ const unitScale = 72 / this._initialCanvas.ppi;
883
+ const rect = this._initialCanvas.position;
884
+ const { width, height } = this._initialCanvas.dimensions;
885
+ catalog.OpenAction = [
886
+ makeRef(
887
+ this.getCanvasObjectNumber(
888
+ this._canvasInfos.findIndex(
889
+ (ci) => ci.canvas.id === this._initialCanvas
890
+ )
891
+ )
892
+ ),
893
+ '/FitR',
894
+ // TODO: Thoroughly test that this is actually working!
895
+ unitScale * rect.x, // left
896
+ unitScale * rect.y, // bottom
897
+ unitScale * (width - (rect.x + rect.width)), // right,
898
+ unitScale * (height - (rect.y + rect.height)), // top,
899
+ ];
900
+ }
901
+
902
+ this._registerEmbeddedFilesInCatalog();
903
+
904
+ await this._flush();
905
+
906
+ if (this._manifestJson) {
907
+ await this._embedManifest(this._manifestJson);
908
+ await this._flush();
909
+ }
910
+ }
911
+
912
+ /** Render a new page, based on a IIIF canvas, its associated annotations and OCR text.
913
+ *
914
+ * @param canvasId The ID of the canvas to render
915
+ * @param width The width of the canvas in pixels
916
+ * @param height The height of the canvas in pixels
917
+ * @param images The images to render on the canvas
918
+ * @param annotations The annotations to render on the canvas
919
+ * @param ocrText The OCR text to render on the canvas
920
+ * @param ppi The resolution of the canvas in pixels per inch, used to determine the physical
921
+ * size of the PDF page. Assumes 300ppi by default.
922
+ */
923
+ async renderPage(
924
+ canvasId: string,
925
+ {
926
+ width: canvasWidth,
927
+ height: canvasHeight,
928
+ }: { width: number; height: number },
929
+ images: (CanvasImage | ImageFetchFailure)[],
930
+ annotations: Annotation[],
931
+ ocrText?: OcrPageWithMarkup,
932
+ ppi = 300
933
+ ): Promise<void> {
934
+ if (!this._pagesStarted) {
935
+ log.debug('Initial page, finalizing PDF header structures.');
936
+ await this.finalizePdfHeader();
937
+ this._pagesStarted = true;
938
+ }
939
+
940
+ // Factor to multiply pixels by to get equivalent PDF units (72 pdf units === 1 inch)
941
+ const unitScale = 72 / ppi;
942
+ const pageDict: PdfDictionary = {
943
+ Type: '/Page',
944
+ Parent: this._objRefs.Pages,
945
+ MediaBox: [0, 0, unitScale * canvasWidth, unitScale * canvasHeight],
946
+ Resources: {
947
+ ProcSet: ['/PDF', '/Text', '/ImageB', '/ImageI', '/ImageC'],
948
+ },
949
+ };
950
+
951
+ if (this._hasText) {
952
+ pageDict.StructParents = this._nextStructParentId;
953
+ this._pageParentIds.set(this._nextObjNo, this._nextStructParentId);
954
+ this._nextStructParentId++;
955
+ }
956
+
957
+ const pageFonts: PdfDictionary = {};
958
+ if (ocrText && this._objRefs.Type0Font) {
959
+ pageFonts['f-0-0'] = this._objRefs.Type0Font;
960
+ }
961
+ if (this._annotationsAsText) {
962
+ for (const { resourceName } of annotationFontFaces(this._annotationFont)) {
963
+ pageFonts[resourceName] = this._objRefs[resourceName];
964
+ }
965
+ }
966
+ if (Object.keys(pageFonts).length > 0) {
967
+ (pageDict.Resources as PdfDictionary).Font = pageFonts;
968
+ }
969
+ const page = this._addObject(pageDict);
970
+
971
+ // Draw images onto the page
972
+ const contentOps: string[] = [];
973
+ const optionalGroupIds: { [imgId: string]: string } = {};
974
+ for (const [idx, image] of images.entries()) {
975
+ if (isImageFetchFailure(image)) {
976
+ continue;
977
+ }
978
+ const { x, y, width, height, choiceInfo, crop } = image;
979
+ const drawWidth = unitScale * width;
980
+ const drawHeight = unitScale * height;
981
+ const drawX = unitScale * x;
982
+ const drawY = unitScale * (canvasHeight - height - y);
983
+ const imageId = `/Im${idx + 1}`;
984
+
985
+ if (choiceInfo?.optional) {
986
+ const ocId = `/oc${Object.keys(optionalGroupIds).length + 1}`;
987
+ optionalGroupIds[imageId] = ocId;
988
+ contentOps.push(`/OC ${ocId} BDC`);
989
+ }
990
+
991
+ if (crop) {
992
+ // Clip to the target area and place the full image so that the
993
+ // cropped part exactly fills it. The image space is a unit square
994
+ // with the origin in the bottom left corner; the crop is relative
995
+ // to the top left corner.
996
+ const fullWidth = drawWidth / crop.width;
997
+ const fullHeight = drawHeight / crop.height;
998
+ const fullX = drawX - crop.x * fullWidth;
999
+ const fullY = drawY - (1 - crop.y - crop.height) * fullHeight;
1000
+ contentOps.push(
1001
+ `q ${drawX} ${drawY} ${drawWidth} ${drawHeight} re W n`
1002
+ );
1003
+ contentOps.push(`${fullWidth} 0 0 ${fullHeight} ${fullX} ${fullY} cm`);
1004
+ } else {
1005
+ contentOps.push(
1006
+ `q ${drawWidth} 0 0 ${drawHeight} ${drawX} ${drawY} cm`
1007
+ );
1008
+ }
1009
+ contentOps.push(`${imageId} Do`);
1010
+ contentOps.push('Q');
1011
+ if (choiceInfo?.optional) {
1012
+ contentOps.push('EMC');
1013
+ }
1014
+ }
1015
+
1016
+ if (ocrText) {
1017
+ contentOps.push(this._renderOcrText(ocrText, unitScale));
1018
+ }
1019
+ if (this._annotationsAsText && annotations?.length) {
1020
+ const annotationOps = await Promise.all(
1021
+ annotations.map((anno) =>
1022
+ exportPdfText(
1023
+ anno,
1024
+ unitScale,
1025
+ canvasHeight,
1026
+ canvasWidth,
1027
+ this._annotationFont
1028
+ )
1029
+ )
1030
+ );
1031
+ contentOps.push(...annotationOps.flat());
1032
+ }
1033
+
1034
+ log.debug('Trying to compress content stream.');
1035
+ const contentStreamComp = await tryDeflateStream(contentOps.join('\n'));
1036
+ const contentsObj = this._addObject(
1037
+ contentStreamComp.dict,
1038
+ undefined,
1039
+ contentStreamComp.stream
1040
+ );
1041
+ (page.data as PdfDictionary).Contents = makeRef(contentsObj);
1042
+
1043
+ // Register all resources for the page
1044
+ const pageResources = (page.data as PdfDictionary)
1045
+ .Resources as PdfDictionary;
1046
+ const xObjects: PdfDictionary = {};
1047
+ const properties: PdfDictionary = {};
1048
+ for (const [idx, img] of images.entries()) {
1049
+ if (isImageFetchFailure(img)) {
1050
+ continue;
1051
+ }
1052
+ const imageId = `/Im${idx + 1}`;
1053
+ xObjects[imageId.substring(1)] = this._makeDeferredReference(imageId);
1054
+ if (img.choiceInfo?.optional) {
1055
+ const ocgId = optionalGroupIds[imageId];
1056
+ properties[ocgId.substring(1)] = this._makeDeferredReference(ocgId);
1057
+ }
1058
+ }
1059
+ pageResources.XObject = xObjects;
1060
+ if (Object.keys(properties).length > 0) {
1061
+ pageResources.Properties = properties;
1062
+ }
1063
+
1064
+ log.debug('Creating image objects.');
1065
+ const canvasIdx = this._canvasInfos.findIndex(
1066
+ (ci) => ci.canvas.id === canvasId
1067
+ );
1068
+ for (const [imgIdx, img] of images.entries()) {
1069
+ if (isImageFetchFailure(img)) {
1070
+ // Dummy image data object
1071
+ this._addObject({});
1072
+ if (this._polyglot) {
1073
+ // Dummy dummy zip header object
1074
+ this._addObject({});
1075
+ }
1076
+ continue;
1077
+ }
1078
+ const imageData = new Uint8Array(img.data!);
1079
+ const image = PdfImage.open(imageData);
1080
+
1081
+ const imageObjs = image.toObjects(
1082
+ // Account for local zip header object if polyglot Zip-PDF is enabled
1083
+ this._polyglot ? this._nextObjNo + 1 : this._nextObjNo
1084
+ );
1085
+
1086
+ if (img.format !== 'jpeg' && image instanceof JPEGImage) {
1087
+ // We calculated with 3 objects for this image, since it was either identified
1088
+ // as PNG or we did not have a format in the manifest. So we need to add empty
1089
+ // dummy objects to keep the object numbers in sync.
1090
+ let objNum = imageObjs.slice(-1)[0].num;
1091
+ for (let i = 0; imageObjs.length < 3; i++) {
1092
+ imageObjs.push({ num: objNum++ });
1093
+ }
1094
+ }
1095
+
1096
+ // Resolve deferred references to this image
1097
+ const mainImageObj = imageObjs[0];
1098
+ const imageId = `/Im${imgIdx + 1}`;
1099
+ this._deferredReferences.get(imageId)!.refObj = mainImageObj.num;
1100
+
1101
+ if (this._polyglot) {
1102
+ if (image instanceof JPEGImage) {
1103
+ const imgPreambleSize = this._getSerializedSize(mainImageObj, true);
1104
+ const filename = `img/canvas-${canvasIdx}-${imgIdx}.jpg`;
1105
+ this._insertZipHeaderDummyObject({
1106
+ filename,
1107
+ data: imageData,
1108
+ bytesUntilActualData: imgPreambleSize,
1109
+ });
1110
+ } else {
1111
+ // Polyglot PDF is not possible for PNG images, since PNGs are not stored
1112
+ // as-is in the PDF, but can be split and stored across multiple objects
1113
+ // To keep our pre-calculated object numbers valid, we need to insert an
1114
+ // empty dummy object in place of the local zip header
1115
+ this._addObject({});
1116
+ }
1117
+ }
1118
+ imageObjs.forEach((obj) => this._objects.push(obj));
1119
+ this._nextObjNo = imageObjs.slice(-1)[0].num + 1;
1120
+ }
1121
+
1122
+ if (images.some((i) => i?.choiceInfo?.optional)) {
1123
+ log.debug('Creating optional content groups for page');
1124
+ for (const [idx, img] of images.entries()) {
1125
+ const imageId = `/Im${idx + 1}`;
1126
+ if (!img?.choiceInfo) {
1127
+ continue;
1128
+ }
1129
+ if (isImageFetchFailure(img)) {
1130
+ // Dummy object to maintain precalculated object numbers
1131
+ this._addObject({});
1132
+ continue;
1133
+ }
1134
+ this._deferredReferences.get(optionalGroupIds[imageId])!.refObj =
1135
+ this._nextObjNo;
1136
+ this._addObject({
1137
+ Type: '/OCG',
1138
+ Name: img.choiceInfo.label
1139
+ ? `(${getI18nValue(img.choiceInfo.label, this._langPref, '/')})`
1140
+ : undefined,
1141
+ Intent: '/View',
1142
+ Usage: img.choiceInfo.visibleByDefault ? '/ON' : '/OFF',
1143
+ } as PdfDictionary);
1144
+ }
1145
+ }
1146
+
1147
+ const canvasInfo = this._canvasInfos[canvasIdx];
1148
+
1149
+ // Embed OCR text, if present
1150
+ if (ocrText?.markup) {
1151
+ const canvasIdx = this._canvasInfos.findIndex(
1152
+ (ci) => ci.canvas.id === canvasId
1153
+ );
1154
+ let filename = `ocr/canvas-${canvasIdx}`;
1155
+ if (ocrText.mimeType.indexOf('html') >= 0) {
1156
+ filename += '.html';
1157
+ } else {
1158
+ filename += '.xml';
1159
+ }
1160
+
1161
+ await this._embedResource(
1162
+ filename,
1163
+ `OCR for canvas #${canvasIdx}`,
1164
+ ocrText.mimeType,
1165
+ ocrText.markup
1166
+ );
1167
+ } else if (canvasInfo?.ocr) {
1168
+ // Canvas Info says we have OCR, but none was passed, possible
1169
+ // when the OCR doesn't have CORS or fetching failed for another reason
1170
+ // Add two empty objects so object references are still valid
1171
+ this._addObject({});
1172
+ this._addObject({});
1173
+ // Add one more if we have a polyglot PDF/ZIP
1174
+ if (this._polyglot) {
1175
+ this._addObject({});
1176
+ }
1177
+ }
1178
+
1179
+ // Add annotations, if present
1180
+ if (!this._annotationsAsText && annotations && annotations.length > 0) {
1181
+ log.debug('Creating annotations for page');
1182
+ pageDict.Annots = (
1183
+ await Promise.all(
1184
+ annotations.map((anno) =>
1185
+ exportPdfAnnotation(anno, unitScale, canvasHeight)
1186
+ )
1187
+ )
1188
+ )
1189
+ .flat()
1190
+ .map((pdfAnno) => makeRef(this._addObject(pdfAnno)));
1191
+ }
1192
+
1193
+ // Write out all of the objects
1194
+ log.debug('Flushing data for page');
1195
+ await this._flush();
1196
+ log.debug('Finished rendering page');
1197
+ }
1198
+
1199
+ /** Get PDF instructions to render a hidden text layer with the page's OCR.
1200
+ *
1201
+ * This owes *a lot* to Tesseract's PDF renderer[1] and the IA's `pdf-tools`[2]
1202
+ * that ported it to Python. Accordingly, the license of this method is Apache 2.0.
1203
+ *
1204
+ * [1] https://github.com/tesseract-ocr/tesseract/blob/5.0.0-beta-20210916/src/api/pdfrenderer.cpp
1205
+ * [2] https://github.com/internetarchive/archive-pdf-tools/blob/master/internetarchivepdf/pdfrenderer.py
1206
+ *
1207
+ * Apache License
1208
+ * Version 2.0, January 2004
1209
+ * http://www.apache.org/licenses/
1210
+ */
1211
+ _renderOcrText(ocr: OcrPageWithMarkup, unitScale: number): string {
1212
+ // TODO: Handle changes in writing direction!
1213
+ // TODO: Handle baselines, at least the simple ``cx+d` skewed-line-type, proper polyline support
1214
+ // requires a per-character transformation matrix, which is a bit much for the current
1215
+ // MVP-ish state
1216
+ const pageHeight = ocr.height;
1217
+ const ops: Array<string> = [];
1218
+ ops.push('BT'); // Begin text rendering
1219
+ ops.push('3 Tr'); // Use "invisible ink" (no fill, no stroke)
1220
+ const pageObjNum = this._nextObjNo - 1;
1221
+ let lineIdx = 0;
1222
+ const entries: StructTreeEntry[] = [];
1223
+ const handleChild = (
1224
+ child: OcrPage | OcrBlock | OcrParagraph | OcrLine,
1225
+ parent?: StructTreeEntry
1226
+ ) => {
1227
+ if (child.type === 'block') {
1228
+ entries.push({
1229
+ type: 'Sect',
1230
+ children: [],
1231
+ pageObjNum,
1232
+ mcs: [],
1233
+ });
1234
+ } else if (child.type === 'paragraph') {
1235
+ entries.push({
1236
+ type: 'P',
1237
+ children: [],
1238
+ pageObjNum,
1239
+ mcs: [],
1240
+ });
1241
+ if (parent) {
1242
+ parent.children.push(entries.slice(-1)[0]);
1243
+ }
1244
+ } else if (child.type === 'line') {
1245
+ ops.push(
1246
+ ...this.renderOcrLine(
1247
+ child,
1248
+ lineIdx,
1249
+ unitScale,
1250
+ pageHeight,
1251
+ pageObjNum
1252
+ )
1253
+ );
1254
+ if (parent) {
1255
+ parent.children.push({
1256
+ type: 'Span',
1257
+ children: [],
1258
+ pageObjNum,
1259
+ mcs: [lineIdx],
1260
+ });
1261
+ }
1262
+ lineIdx++;
1263
+ return;
1264
+ }
1265
+ for (const grandchild of child.children) {
1266
+ handleChild(grandchild, entries.slice(-1)[0]);
1267
+ }
1268
+ };
1269
+ handleChild(ocr);
1270
+ this._strucTree.push(...entries);
1271
+ ops.push('ET');
1272
+ return ops.join('\n');
1273
+ }
1274
+
1275
+ /** Get PDF instructions to render a single line of OCR text. */
1276
+ renderOcrLine(
1277
+ line: OcrLine,
1278
+ lineIdx: number,
1279
+ unitScale: number,
1280
+ pageHeight: number,
1281
+ pageObjNum: number
1282
+ ): string[] {
1283
+ const fontRef = '/f-0-0';
1284
+ const scaleX = 1;
1285
+ const scaleY = 1;
1286
+ const shearX = 0;
1287
+ const shearY = 0;
1288
+ const ops: Array<string> = [];
1289
+ // Begin of marked content sequence that wraps the line in a Span
1290
+ ops.push(`/Span << /MCID ${lineIdx} >> BDC`);
1291
+ // Approximated font size for western scripts, PDF font size is specified in multiples of
1292
+ // 'user units', which default to 1/72inch. The `userScale` gives us the units per pixel.
1293
+ const fontSize = line.height * unitScale * 0.75;
1294
+ //const fontSize = 8; // TODO: This is what Tesseract uses, why does this work?
1295
+ ops.push(`${fontRef} ${fontSize} Tf`);
1296
+ // We use a text matrix for every line. Tesseract uses a per-paragraph matrix, but we don't
1297
+ // neccesarily have block/paragraph information available, so we'll use the next-closest
1298
+ // thing. This means that every word on the line is positioned relative to the line, not
1299
+ // relative to the page as in the markup.
1300
+ const xPos = line.x * unitScale;
1301
+ const lineY = pageHeight - line.y - line.height * 0.75;
1302
+ const yPos = lineY * unitScale;
1303
+ ops.push(`${scaleX} ${shearX} ${shearY} ${scaleY} ${xPos} ${yPos} Tm`);
1304
+ let xOld = 0;
1305
+ let yOld = 0;
1306
+ // TODO: What to do if non-word line content?
1307
+ for (const word of line.words) {
1308
+ if (!word.text) {
1309
+ continue;
1310
+ }
1311
+ if (!word.width) {
1312
+ continue;
1313
+ }
1314
+ // Position drawing with relative moveto
1315
+ const wordX = (word.x - line.x) * unitScale;
1316
+ // Convert beween different y-origins in OCR and PDF
1317
+ const wordYAbsolute = pageHeight - word.y - word.height * 0.75;
1318
+ const wordY = (wordYAbsolute - lineY) * unitScale;
1319
+ const wordWidth = word.width * unitScale;
1320
+ const wordHeight = word.height * unitScale;
1321
+ const dx = wordX - xOld;
1322
+ const dy = wordY - yOld;
1323
+ ops.push(`${dx * scaleX + dy * shearX} ${dx * shearY + dy * scaleY} Td`);
1324
+ xOld = wordX;
1325
+ yOld = wordY;
1326
+ // Calculate horizontal stretch
1327
+ // TODO: This is ripped straight from Tesseract, I have no clue what it does
1328
+ // FIXME: The end of the line seems to be too far to the left sometimes,
1329
+ // while the start seems to match
1330
+ const wordLength = Math.pow(
1331
+ Math.pow(wordWidth, 2) + Math.pow(wordHeight, 2),
1332
+ 0.5
1333
+ );
1334
+ const pdfWordLen = word.text.length;
1335
+ ops.push(
1336
+ `${CHAR_WIDTH * ((100 * wordLength) / (fontSize * pdfWordLen))} Tz`
1337
+ );
1338
+ // TODO: Account for trailing space in width calculation to prevent readers
1339
+ // from inserting a line break
1340
+ const textBytes = serialize(toUTF16BE(word.text + ' ', false));
1341
+ ops.push(`[ ${textBytes} ] TJ`);
1342
+ }
1343
+ ops.push('EMC');
1344
+ // Add a newline to visually group together all statements belonging to a line
1345
+ ops.push('');
1346
+ if (!this._pageMCIds.has(pageObjNum)) {
1347
+ this._pageMCIds.set(pageObjNum, []);
1348
+ }
1349
+ this._pageMCIds.get(pageObjNum)!.push(lineIdx);
1350
+ return ops;
1351
+ }
1352
+
1353
+ /** How many bytes have we written to the output so far? */
1354
+ get bytesWritten(): number {
1355
+ return this._offset;
1356
+ }
1357
+
1358
+ /** Number of objects needed to render all canvases */
1359
+ get totalCanvasObjects(): number {
1360
+ // Every canvas needs 1 object per image, 1 for the content stream and 1 for the page definition.
1361
+ return this._canvasInfos.reduce(
1362
+ (sum, _, idx) => sum + this.getCanvasObjectNumber(idx),
1363
+ 0
1364
+ );
1365
+ }
1366
+
1367
+ /** How many objects are needed to render the canvas at the given index? */
1368
+ getObjectsPerCanvas(canvasIdx: number): number {
1369
+ const { images, ocr, numAnnotations } = this._canvasInfos[canvasIdx];
1370
+ let numObjects =
1371
+ // 1 XObject for JPEGs, 3 for PNGs or unknown formats
1372
+ // The minority of PNGs actually need three XObjects, but we can't know
1373
+ // that in advance and so we simply add empty dummy objects if we need less.
1374
+ images
1375
+ .map((img) => (img.format === 'jpeg' ? 1 : 3))
1376
+ .reduce((a, b) => a + b, 0) +
1377
+ // Page dictionary and content
1378
+ 2 +
1379
+ // 1 Optional Content Group per optional image
1380
+ images.filter((i) => i.choiceInfo !== undefined).length +
1381
+ // Text-rendered annotations add no separate PDF objects.
1382
+ (this._annotationsAsText ? 0 : numAnnotations);
1383
+ if (this._polyglot) {
1384
+ // For a polyglot PDF, we need to precede every XObject that we'd like
1385
+ // to expose as a file in the ZIP with a separate XObject that contains
1386
+ // the local ZIP header for that file. Currently this concerns the
1387
+ // images and the OCR data
1388
+ // PNG images can't be embedded in the polyglot ZIP, so we simply add an
1389
+ // empty object for each PNG image in place of the zip header object.
1390
+ numObjects = numObjects + images.length + (ocr ? 1 : 0);
1391
+ }
1392
+ if (ocr) {
1393
+ numObjects += 2;
1394
+ }
1395
+ return numObjects;
1396
+ }
1397
+
1398
+ /** Get the object number for the canvas at the given index. */
1399
+ getCanvasObjectNumber(canvasIdx: number): number {
1400
+ let num = this._firstPageObjectNum!;
1401
+ for (const [idx] of this._canvasInfos.entries()) {
1402
+ if (idx === canvasIdx) {
1403
+ return num;
1404
+ }
1405
+ num += this.getObjectsPerCanvas(idx);
1406
+ }
1407
+ throw new Error(`Canvas #${canvasIdx} not found.`);
1408
+ }
1409
+
1410
+ /** Flush remaining data to output. */
1411
+ async _flush(): Promise<void> {
1412
+ if (this._offsets.length === 0) {
1413
+ log.debug('Writing PDF header');
1414
+ await this._write(`%PDF-1.5\n%\xde\xad\xbe\xef\n`);
1415
+ }
1416
+ for (const obj of this._objects) {
1417
+ if (!obj) {
1418
+ continue;
1419
+ }
1420
+ log.debug(`Serializing object #${obj.num}`);
1421
+ await this._serializeObject(obj);
1422
+ }
1423
+ this._objects = [];
1424
+ }
1425
+
1426
+ /** Get the serialized size in bytes of a PDF object. */
1427
+ _getSerializedSize(
1428
+ { num, data, stream }: PdfObject,
1429
+ untilStreamStart = false
1430
+ ): number {
1431
+ let size = 0;
1432
+ size += `${num} 0 obj\n`.length;
1433
+
1434
+ if (data) {
1435
+ size += serialize(data).length;
1436
+ }
1437
+ if (stream) {
1438
+ size += '\nstream\n'.length;
1439
+ if (untilStreamStart) {
1440
+ return size;
1441
+ }
1442
+ if (typeof stream === 'string') {
1443
+ size += textEncoder.encode(stream).byteLength;
1444
+ } else {
1445
+ size += stream.byteLength;
1446
+ }
1447
+ size += '\nendstream'.length;
1448
+ }
1449
+ size += '\nendobj\n'.length;
1450
+ return size;
1451
+ }
1452
+
1453
+ /** Serialize a PDF object to the output. */
1454
+ async _serializeObject(obj: PdfObject): Promise<void> {
1455
+ this._offsets.push(this._offset);
1456
+ const { num, data, stream } = obj;
1457
+ await this._write(`${num} 0 obj\n`);
1458
+ if (data) {
1459
+ await this._write(serialize(data));
1460
+ }
1461
+ if (stream) {
1462
+ await this._write('\nstream\n');
1463
+ await this._write(stream);
1464
+ await this._write('\nendstream');
1465
+ }
1466
+ await this._write('\nendobj\n');
1467
+ }
1468
+
1469
+ /** Write data to the output. */
1470
+ async _write(data: Uint8Array | string): Promise<void> {
1471
+ if (this._writer === undefined) {
1472
+ throw new Error(
1473
+ 'Cannot perform mutating operations on an already closed PDFGenerator.'
1474
+ );
1475
+ }
1476
+ const bytes = typeof data === 'string'
1477
+ ? textEncoder.encode(data)
1478
+ : data;
1479
+
1480
+ this._offset += bytes.byteLength;
1481
+ await this._writer.write(data);
1482
+ }
1483
+
1484
+ /** Write the PDF objects required for the structure tree */
1485
+ async _writeStructureTree(): Promise<void> {
1486
+ const parentRoot: PdfDictionary = {
1487
+ Nums: [],
1488
+ };
1489
+ const parentRootRef = makeRef(this._addObject(parentRoot));
1490
+ const root: PdfDictionary = {
1491
+ Type: '/StructTreeRoot',
1492
+ K: [],
1493
+ ParentTree: parentRootRef,
1494
+ ParentTreeNextKey: this._nextStructParentId,
1495
+ };
1496
+ const pageParents: Map<number, Array<PdfRef>> = new Map();
1497
+ const rootRef = makeRef(this._addObject(root));
1498
+ const visitEntry = async (
1499
+ entry: StructTreeEntry,
1500
+ parent: PdfDictionary,
1501
+ parentRef: PdfRef
1502
+ ): Promise<void> => {
1503
+ const obj: PdfDictionary = {
1504
+ Type: '/StructElem',
1505
+ S: `/${entry.type}`,
1506
+ P: parentRef,
1507
+ Pg: makeRef(entry.pageObjNum),
1508
+ K: [],
1509
+ };
1510
+ if (!pageParents.has(entry.pageObjNum)) {
1511
+ pageParents.set(entry.pageObjNum, []);
1512
+ }
1513
+ const objRef = makeRef(this._addObject(obj));
1514
+ (parent.K as PdfRef[]).push(objRef);
1515
+ if (entry.children.length > 0) {
1516
+ for (const i of entry.children) {
1517
+ await visitEntry(i, obj, objRef);
1518
+ }
1519
+ } else if (entry.mcs.length == 1) {
1520
+ obj.K = entry.mcs[0];
1521
+ } else if (entry.mcs.length > 0) {
1522
+ obj.K = entry.mcs;
1523
+ }
1524
+ if (entry.mcs.length > 0) {
1525
+ const parents = pageParents.get(entry.pageObjNum)!;
1526
+ for (const mcId of entry.mcs) {
1527
+ parents[mcId] = objRef;
1528
+ }
1529
+ }
1530
+ if (this._objects.length > 1000) {
1531
+ await this._flush();
1532
+ }
1533
+ };
1534
+ for (const i of this._strucTree) {
1535
+ await visitEntry(i, root, rootRef);
1536
+ }
1537
+ for (const [pageObjNum, parents] of pageParents) {
1538
+ const pidx = this._pageParentIds.get(pageObjNum)!;
1539
+ (parentRoot.Nums as PdfArray).push(
1540
+ pidx,
1541
+ makeRef(this._addObject(parents))
1542
+ );
1543
+ }
1544
+ await this._flush();
1545
+ }
1546
+
1547
+ /** Finish writing the PDF and close the writer.
1548
+ *
1549
+ * Writes XRef table, trailer and EOF marker to the output.
1550
+ * Also adds ZIP central directory if polyglot PDF is enabled.
1551
+ */
1552
+ async end(): Promise<void> {
1553
+ if (!this._writer) {
1554
+ return;
1555
+ }
1556
+ /* FIXME: Disabled due to poor performance on large volumes and a strange
1557
+ * interaction with streamsaver, where the PDF would be prematurely
1558
+ * closed in the middle of writing out the structure tree.
1559
+ log.debug("Writing structure tree");
1560
+ if (this._strucTree.length > 0) {
1561
+ await this._writeStructureTree();
1562
+ }
1563
+ */
1564
+ log.debug('Writing xref table');
1565
+ type XrefEntry = [number, number, 'f' | 'n'];
1566
+ const xrefEntries: Array<XrefEntry> = [
1567
+ [0, 65535, 'f'],
1568
+ ...this._offsets.map((offset): XrefEntry => [offset, 0, 'n']),
1569
+ ];
1570
+ const xRefTable = xrefEntries
1571
+ .map(([off, gen, free]) =>
1572
+ [
1573
+ off.toString(10).padStart(10, '0'),
1574
+ gen.toString(10).padStart(5, '0'),
1575
+ free,
1576
+ '',
1577
+ ].join(' ')
1578
+ )
1579
+ .join('\n');
1580
+ const xrefOffset = this._offset;
1581
+ await this._write(`xref\n0 ${xrefEntries.length}\n${xRefTable}\n`);
1582
+ const trailerDict: PdfDictionary = {
1583
+ Size: xrefEntries.length,
1584
+ Root: this._objRefs.Catalog,
1585
+ Info: this._objRefs.Info,
1586
+ ID: [randomData(32), randomData(32)],
1587
+ };
1588
+ await this._write(`\ntrailer\n${serialize(trailerDict)}`);
1589
+ const trailer = `startxref\n${xrefOffset}\n%%EOF`;
1590
+ if (this._polyglot && this._zipCatalog) {
1591
+ log.debug('Writing zip end of central directory');
1592
+ await this._write('9990 0 obj\n<<>>\nstream\n');
1593
+ const endObj = '\nendstream\nendobj\n';
1594
+ await this._write(
1595
+ buildCentralFileDirectory({
1596
+ files: this._zipCatalog,
1597
+ trailingLength: trailer.length + endObj.length,
1598
+ offset: this._offset,
1599
+ })
1600
+ );
1601
+ await this._write(endObj);
1602
+ }
1603
+ await this._flush();
1604
+ log.debug('Writing trailer');
1605
+ await this._write(trailer);
1606
+ log.debug('Flushing');
1607
+ await this._flush();
1608
+ // FIXME: Never resolves on Node.js, is it really
1609
+ // needed in browsers?
1610
+ //log.debug('Waiting for drainage');
1611
+ //await this._writer.waitForDrain();
1612
+ log.debug('PDF finished, closing writer');
1613
+ await this._writer.close();
1614
+ log.debug('Writer closed');
1615
+ this._writer = undefined;
1616
+ }
1617
+
1618
+ /** Insert a 'dummy' PDF object that isn't referenced anywhere, but which
1619
+ * contains the data neccessary to expose the following object's data as a
1620
+ * file in the ZIP archive.
1621
+ */
1622
+ private _insertZipHeaderDummyObject({
1623
+ filename,
1624
+ data,
1625
+ deflatedData,
1626
+ bytesUntilActualData,
1627
+ }: ZipDummyObjectSpec): void {
1628
+ if (this._zipBaseDir) {
1629
+ filename = `${this._zipBaseDir}/${filename}`;
1630
+ }
1631
+ const zipObjOffset =
1632
+ this._offset +
1633
+ this._objects.reduce((acc, obj) => acc + this._getSerializedSize(obj), 0);
1634
+ const creationDate = new Date();
1635
+ bytesUntilActualData += '\nendstream\nendobj\n'.length;
1636
+ const zipObj = this._addObject(
1637
+ {},
1638
+ undefined,
1639
+ buildLocalZipHeader({
1640
+ filename,
1641
+ data,
1642
+ compressedData: deflatedData,
1643
+ extraDataLength: bytesUntilActualData,
1644
+ creationDate,
1645
+ })
1646
+ );
1647
+ const localHeaderOffset =
1648
+ zipObjOffset + this._getSerializedSize(zipObj, true);
1649
+ if (!this._zipCatalog) {
1650
+ this._zipCatalog = [];
1651
+ }
1652
+ this._zipCatalog.push({
1653
+ localHeaderOffset,
1654
+ deflated: deflatedData?.length !== data.length,
1655
+ creationDate: new Date(),
1656
+ crc32: crc32(data),
1657
+ dataLength: data.length,
1658
+ // skip 2 bytes for zlib header
1659
+ compressedDataLength: deflatedData
1660
+ ? deflatedData.length - 2
1661
+ : data.length,
1662
+ filename,
1663
+ });
1664
+ }
1665
+ }