@vaadin-component-factory/vcf-pdf-viewer 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/README.md +1 -1
  2. package/package.json +42 -26
  3. package/{src/display → pdfjs/dist}/display_utils.js +344 -139
  4. package/{src/display → pdfjs/dist}/fetch_stream.js +115 -97
  5. package/pdfjs/dist/l10n_utils.js +140 -0
  6. package/{src/shared → pdfjs/dist}/message_handler.js +243 -259
  7. package/{src/display → pdfjs/dist}/network.js +149 -87
  8. package/{src/display/content_disposition.js → pdfjs/dist/network_utils.js} +167 -55
  9. package/{src/display → pdfjs/dist}/node_stream.js +133 -98
  10. package/pdfjs/dist/pdf.js +12778 -0
  11. package/pdfjs/dist/pdf_link_service.js +638 -0
  12. package/pdfjs/dist/pdf_rendering_queue.js +199 -0
  13. package/pdfjs/dist/pdf_thumbnail_viewer.js +819 -0
  14. package/pdfjs/dist/pdf_viewer.js +3598 -0
  15. package/pdfjs/dist/ui_utils.js +1033 -0
  16. package/{src/shared → pdfjs/dist}/util.js +301 -287
  17. package/pdfjs/dist/worker.js +62813 -0
  18. package/src/vcf-pdf-viewer.js +98 -46
  19. package/theme/lumo/vcf-pdf-viewer-styles.js +4 -4
  20. package/theme/material/vcf-pdf-viewer-styles.js +4 -4
  21. package/theme/material/vcf-pdf-viewer.js +2 -2
  22. package/src/core/.eslintrc +0 -13
  23. package/src/core/annotation.js +0 -2948
  24. package/src/core/arithmetic_decoder.js +0 -182
  25. package/src/core/ascii_85_stream.js +0 -98
  26. package/src/core/ascii_hex_stream.js +0 -79
  27. package/src/core/base_stream.js +0 -110
  28. package/src/core/bidi.js +0 -438
  29. package/src/core/calibri_factors.js +0 -308
  30. package/src/core/catalog.js +0 -1459
  31. package/src/core/ccitt.js +0 -1062
  32. package/src/core/ccitt_stream.js +0 -60
  33. package/src/core/cff_font.js +0 -116
  34. package/src/core/cff_parser.js +0 -1949
  35. package/src/core/charsets.js +0 -119
  36. package/src/core/chunked_stream.js +0 -557
  37. package/src/core/cmap.js +0 -1039
  38. package/src/core/colorspace.js +0 -1533
  39. package/src/core/core_utils.js +0 -464
  40. package/src/core/crypto.js +0 -1900
  41. package/src/core/decode_stream.js +0 -170
  42. package/src/core/decrypt_stream.js +0 -59
  43. package/src/core/default_appearance.js +0 -99
  44. package/src/core/document.js +0 -1456
  45. package/src/core/encodings.js +0 -301
  46. package/src/core/evaluator.js +0 -4601
  47. package/src/core/file_spec.js +0 -108
  48. package/src/core/flate_stream.js +0 -402
  49. package/src/core/font_renderer.js +0 -882
  50. package/src/core/fonts.js +0 -3260
  51. package/src/core/fonts_utils.js +0 -221
  52. package/src/core/function.js +0 -1257
  53. package/src/core/glyf.js +0 -706
  54. package/src/core/glyphlist.js +0 -4558
  55. package/src/core/helvetica_factors.js +0 -353
  56. package/src/core/image.js +0 -802
  57. package/src/core/image_utils.js +0 -291
  58. package/src/core/jbig2.js +0 -2572
  59. package/src/core/jbig2_stream.js +0 -73
  60. package/src/core/jpeg_stream.js +0 -105
  61. package/src/core/jpg.js +0 -1416
  62. package/src/core/jpx.js +0 -2343
  63. package/src/core/jpx_stream.js +0 -87
  64. package/src/core/liberationsans_widths.js +0 -221
  65. package/src/core/lzw_stream.js +0 -150
  66. package/src/core/metadata_parser.js +0 -146
  67. package/src/core/metrics.js +0 -2970
  68. package/src/core/murmurhash3.js +0 -139
  69. package/src/core/myriadpro_factors.js +0 -290
  70. package/src/core/name_number_tree.js +0 -153
  71. package/src/core/object_loader.js +0 -149
  72. package/src/core/opentype_file_builder.js +0 -154
  73. package/src/core/operator_list.js +0 -734
  74. package/src/core/parser.js +0 -1416
  75. package/src/core/pattern.js +0 -985
  76. package/src/core/pdf_manager.js +0 -217
  77. package/src/core/predictor_stream.js +0 -238
  78. package/src/core/primitives.js +0 -402
  79. package/src/core/ps_parser.js +0 -272
  80. package/src/core/run_length_stream.js +0 -61
  81. package/src/core/segoeui_factors.js +0 -308
  82. package/src/core/standard_fonts.js +0 -817
  83. package/src/core/stream.js +0 -103
  84. package/src/core/struct_tree.js +0 -335
  85. package/src/core/to_unicode_map.js +0 -103
  86. package/src/core/type1_font.js +0 -421
  87. package/src/core/type1_parser.js +0 -776
  88. package/src/core/unicode.js +0 -1649
  89. package/src/core/worker.js +0 -848
  90. package/src/core/worker_stream.js +0 -135
  91. package/src/core/writer.js +0 -278
  92. package/src/core/xfa/bind.js +0 -652
  93. package/src/core/xfa/builder.js +0 -207
  94. package/src/core/xfa/config.js +0 -1926
  95. package/src/core/xfa/connection_set.js +0 -202
  96. package/src/core/xfa/data.js +0 -82
  97. package/src/core/xfa/datasets.js +0 -76
  98. package/src/core/xfa/factory.js +0 -111
  99. package/src/core/xfa/fonts.js +0 -181
  100. package/src/core/xfa/formcalc_lexer.js +0 -385
  101. package/src/core/xfa/formcalc_parser.js +0 -1340
  102. package/src/core/xfa/html_utils.js +0 -639
  103. package/src/core/xfa/layout.js +0 -383
  104. package/src/core/xfa/locale_set.js +0 -345
  105. package/src/core/xfa/namespaces.js +0 -81
  106. package/src/core/xfa/parser.js +0 -184
  107. package/src/core/xfa/setup.js +0 -38
  108. package/src/core/xfa/signature.js +0 -40
  109. package/src/core/xfa/som.js +0 -338
  110. package/src/core/xfa/stylesheet.js +0 -40
  111. package/src/core/xfa/template.js +0 -6260
  112. package/src/core/xfa/text.js +0 -290
  113. package/src/core/xfa/unknown.js +0 -29
  114. package/src/core/xfa/utils.js +0 -217
  115. package/src/core/xfa/xdp.js +0 -59
  116. package/src/core/xfa/xfa_object.js +0 -1130
  117. package/src/core/xfa/xhtml.js +0 -543
  118. package/src/core/xfa_fonts.js +0 -208
  119. package/src/core/xml_parser.js +0 -507
  120. package/src/core/xref.js +0 -899
  121. package/src/display/annotation_layer.js +0 -2107
  122. package/src/display/annotation_storage.js +0 -113
  123. package/src/display/api.js +0 -3292
  124. package/src/display/base_factory.js +0 -180
  125. package/src/display/canvas.js +0 -2828
  126. package/src/display/font_loader.js +0 -484
  127. package/src/display/metadata.js +0 -41
  128. package/src/display/network_utils.js +0 -100
  129. package/src/display/node_utils.js +0 -83
  130. package/src/display/optional_content_config.js +0 -189
  131. package/src/display/pattern_helper.js +0 -659
  132. package/src/display/svg.js +0 -1709
  133. package/src/display/text_layer.js +0 -847
  134. package/src/display/transport_stream.js +0 -303
  135. package/src/display/worker_options.js +0 -40
  136. package/src/display/xfa_layer.js +0 -204
  137. package/src/doc_helper.js +0 -25
  138. package/src/images/logo.svg +0 -41
  139. package/src/interfaces.js +0 -169
  140. package/src/license_header.js +0 -14
  141. package/src/license_header_libre.js +0 -21
  142. package/src/pdf.image_decoders.js +0 -46
  143. package/src/pdf.js +0 -146
  144. package/src/pdf.sandbox.external.js +0 -181
  145. package/src/pdf.sandbox.js +0 -151
  146. package/src/pdf.scripting.js +0 -25
  147. package/src/pdf.worker.entry.js +0 -19
  148. package/src/pdf.worker.js +0 -23
  149. package/src/scripting_api/aform.js +0 -608
  150. package/src/scripting_api/app.js +0 -621
  151. package/src/scripting_api/color.js +0 -129
  152. package/src/scripting_api/common.js +0 -58
  153. package/src/scripting_api/console.js +0 -38
  154. package/src/scripting_api/constants.js +0 -208
  155. package/src/scripting_api/doc.js +0 -1195
  156. package/src/scripting_api/error.js +0 -23
  157. package/src/scripting_api/event.js +0 -232
  158. package/src/scripting_api/field.js +0 -620
  159. package/src/scripting_api/fullscreen.js +0 -145
  160. package/src/scripting_api/initialization.js +0 -223
  161. package/src/scripting_api/pdf_object.js +0 -24
  162. package/src/scripting_api/print_params.js +0 -146
  163. package/src/scripting_api/proxy.js +0 -139
  164. package/src/scripting_api/thermometer.js +0 -69
  165. package/src/scripting_api/util.js +0 -581
  166. package/src/shared/.eslintrc +0 -13
  167. package/src/shared/cffStandardStrings.js +0 -311
  168. package/src/shared/compatibility.js +0 -114
  169. package/src/shared/fonts_utils.js +0 -429
  170. package/src/shared/is_node.js +0 -27
  171. package/src/shared/scripting_utils.js +0 -85
  172. package/src/worker_loader.js +0 -32
@@ -1,848 +0,0 @@
1
- /* Copyright 2012 Mozilla Foundation
2
- *
3
- * Licensed under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License.
5
- * You may obtain a copy of the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS,
11
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- * See the License for the specific language governing permissions and
13
- * limitations under the License.
14
- */
15
-
16
- import {
17
- AbortException,
18
- arrayByteLength,
19
- arraysToBytes,
20
- createPromiseCapability,
21
- getVerbosityLevel,
22
- info,
23
- InvalidPDFException,
24
- isString,
25
- MissingPDFException,
26
- PasswordException,
27
- setVerbosityLevel,
28
- stringToPDFString,
29
- UnexpectedResponseException,
30
- UnknownErrorException,
31
- UNSUPPORTED_FEATURES,
32
- VerbosityLevel,
33
- warn,
34
- } from "../shared/util.js";
35
- import { clearPrimitiveCaches, Dict, Ref } from "./primitives.js";
36
- import { LocalPdfManager, NetworkPdfManager } from "./pdf_manager.js";
37
- import { incrementalUpdate } from "./writer.js";
38
- import { isNodeJS } from "../shared/is_node.js";
39
- import { MessageHandler } from "../shared/message_handler.js";
40
- import { PDFWorkerStream } from "./worker_stream.js";
41
- import { XRefParseException } from "./core_utils.js";
42
-
43
- class WorkerTask {
44
- constructor(name) {
45
- this.name = name;
46
- this.terminated = false;
47
- this._capability = createPromiseCapability();
48
- }
49
-
50
- get finished() {
51
- return this._capability.promise;
52
- }
53
-
54
- finish() {
55
- this._capability.resolve();
56
- }
57
-
58
- terminate() {
59
- this.terminated = true;
60
- }
61
-
62
- ensureNotTerminated() {
63
- if (this.terminated) {
64
- throw new Error("Worker task was terminated");
65
- }
66
- }
67
- }
68
-
69
- class WorkerMessageHandler {
70
- static setup(handler, port) {
71
- let testMessageProcessed = false;
72
- handler.on("test", function wphSetupTest(data) {
73
- if (testMessageProcessed) {
74
- return; // we already processed 'test' message once
75
- }
76
- testMessageProcessed = true;
77
-
78
- // check if Uint8Array can be sent to worker
79
- if (!(data instanceof Uint8Array)) {
80
- handler.send("test", null);
81
- return;
82
- }
83
- // making sure postMessage transfers are working
84
- const supportTransfers = data[0] === 255;
85
- handler.postMessageTransfers = supportTransfers;
86
-
87
- handler.send("test", { supportTransfers });
88
- });
89
-
90
- handler.on("configure", function wphConfigure(data) {
91
- setVerbosityLevel(data.verbosity);
92
- });
93
-
94
- handler.on("GetDocRequest", function wphSetupDoc(data) {
95
- return WorkerMessageHandler.createDocumentHandler(data, port);
96
- });
97
- }
98
-
99
- static createDocumentHandler(docParams, port) {
100
- // This context is actually holds references on pdfManager and handler,
101
- // until the latter is destroyed.
102
- let pdfManager;
103
- let terminated = false;
104
- let cancelXHRs = null;
105
- const WorkerTasks = [];
106
- const verbosity = getVerbosityLevel();
107
-
108
- const apiVersion = docParams.apiVersion;
109
- const workerVersion =
110
- typeof PDFJSDev !== "undefined" && !PDFJSDev.test("TESTING")
111
- ? PDFJSDev.eval("BUNDLE_VERSION")
112
- : null;
113
- if (apiVersion !== workerVersion) {
114
- throw new Error(
115
- `The API version "${apiVersion}" does not match ` +
116
- `the Worker version "${workerVersion}".`
117
- );
118
- }
119
-
120
- if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
121
- // Fail early, and predictably, rather than having (some) fonts fail to
122
- // load/render with slightly cryptic error messages in environments where
123
- // the `Array.prototype` has been *incorrectly* extended.
124
- //
125
- // PLEASE NOTE: We do *not* want to slow down font parsing by adding
126
- // `hasOwnProperty` checks all over the code-base.
127
- const enumerableProperties = [];
128
- for (const property in []) {
129
- enumerableProperties.push(property);
130
- }
131
- if (enumerableProperties.length) {
132
- throw new Error(
133
- "The `Array.prototype` contains unexpected enumerable properties: " +
134
- enumerableProperties.join(", ") +
135
- "; thus breaking e.g. `for...in` iteration of `Array`s."
136
- );
137
- }
138
-
139
- // Ensure that (primarily) Node.js users won't accidentally attempt to use
140
- // a non-translated/non-polyfilled build of the library, since that would
141
- // quickly fail anyway because of missing functionality.
142
- if (
143
- (typeof PDFJSDev === "undefined" || PDFJSDev.test("SKIP_BABEL")) &&
144
- typeof ReadableStream === "undefined"
145
- ) {
146
- throw new Error(
147
- "The browser/environment lacks native support for critical " +
148
- "functionality used by the PDF.js library (e.g. `ReadableStream`); " +
149
- "please use a `legacy`-build instead."
150
- );
151
- }
152
- }
153
-
154
- const docId = docParams.docId;
155
- const docBaseUrl = docParams.docBaseUrl;
156
- const workerHandlerName = docParams.docId + "_worker";
157
- let handler = new MessageHandler(workerHandlerName, docId, port);
158
-
159
- // Ensure that postMessage transfers are always correctly enabled/disabled,
160
- // to prevent "DataCloneError" in browsers without transfers support.
161
- handler.postMessageTransfers = docParams.postMessageTransfers;
162
-
163
- function ensureNotTerminated() {
164
- if (terminated) {
165
- throw new Error("Worker was terminated");
166
- }
167
- }
168
-
169
- function startWorkerTask(task) {
170
- WorkerTasks.push(task);
171
- }
172
-
173
- function finishWorkerTask(task) {
174
- task.finish();
175
- const i = WorkerTasks.indexOf(task);
176
- WorkerTasks.splice(i, 1);
177
- }
178
-
179
- async function loadDocument(recoveryMode) {
180
- await pdfManager.ensureDoc("checkHeader");
181
- await pdfManager.ensureDoc("parseStartXRef");
182
- await pdfManager.ensureDoc("parse", [recoveryMode]);
183
-
184
- if (!recoveryMode) {
185
- // Check that at least the first page can be successfully loaded,
186
- // since otherwise the XRef table is definitely not valid.
187
- await pdfManager.ensureDoc("checkFirstPage");
188
- }
189
-
190
- const isPureXfa = await pdfManager.ensureDoc("isPureXfa");
191
- if (isPureXfa) {
192
- const task = new WorkerTask("loadXfaFonts");
193
- startWorkerTask(task);
194
- await Promise.all([
195
- pdfManager
196
- .loadXfaFonts(handler, task)
197
- .catch(reason => {
198
- // Ignore errors, to allow the document to load.
199
- })
200
- .then(() => finishWorkerTask(task)),
201
- pdfManager.loadXfaImages(),
202
- ]);
203
- }
204
-
205
- const [numPages, fingerprints] = await Promise.all([
206
- pdfManager.ensureDoc("numPages"),
207
- pdfManager.ensureDoc("fingerprints"),
208
- ]);
209
-
210
- // Get htmlForXfa after numPages to avoid to create HTML twice.
211
- const htmlForXfa = isPureXfa
212
- ? await pdfManager.ensureDoc("htmlForXfa")
213
- : null;
214
-
215
- return { numPages, fingerprints, htmlForXfa };
216
- }
217
-
218
- function getPdfManager(data, evaluatorOptions, enableXfa) {
219
- const pdfManagerCapability = createPromiseCapability();
220
- let newPdfManager;
221
-
222
- const source = data.source;
223
- if (source.data) {
224
- try {
225
- newPdfManager = new LocalPdfManager(
226
- docId,
227
- source.data,
228
- source.password,
229
- evaluatorOptions,
230
- enableXfa,
231
- docBaseUrl
232
- );
233
- pdfManagerCapability.resolve(newPdfManager);
234
- } catch (ex) {
235
- pdfManagerCapability.reject(ex);
236
- }
237
- return pdfManagerCapability.promise;
238
- }
239
-
240
- let pdfStream,
241
- cachedChunks = [];
242
- try {
243
- pdfStream = new PDFWorkerStream(handler);
244
- } catch (ex) {
245
- pdfManagerCapability.reject(ex);
246
- return pdfManagerCapability.promise;
247
- }
248
-
249
- const fullRequest = pdfStream.getFullReader();
250
- fullRequest.headersReady
251
- .then(function () {
252
- if (!fullRequest.isRangeSupported) {
253
- return;
254
- }
255
-
256
- // We don't need auto-fetch when streaming is enabled.
257
- const disableAutoFetch =
258
- source.disableAutoFetch || fullRequest.isStreamingSupported;
259
- newPdfManager = new NetworkPdfManager(
260
- docId,
261
- pdfStream,
262
- {
263
- msgHandler: handler,
264
- password: source.password,
265
- length: fullRequest.contentLength,
266
- disableAutoFetch,
267
- rangeChunkSize: source.rangeChunkSize,
268
- },
269
- evaluatorOptions,
270
- enableXfa,
271
- docBaseUrl
272
- );
273
- // There may be a chance that `newPdfManager` is not initialized for
274
- // the first few runs of `readchunk` block of code. Be sure to send
275
- // all cached chunks, if any, to chunked_stream via pdf_manager.
276
- for (let i = 0; i < cachedChunks.length; i++) {
277
- newPdfManager.sendProgressiveData(cachedChunks[i]);
278
- }
279
-
280
- cachedChunks = [];
281
- pdfManagerCapability.resolve(newPdfManager);
282
- cancelXHRs = null;
283
- })
284
- .catch(function (reason) {
285
- pdfManagerCapability.reject(reason);
286
- cancelXHRs = null;
287
- });
288
-
289
- let loaded = 0;
290
- const flushChunks = function () {
291
- const pdfFile = arraysToBytes(cachedChunks);
292
- if (source.length && pdfFile.length !== source.length) {
293
- warn("reported HTTP length is different from actual");
294
- }
295
- // the data is array, instantiating directly from it
296
- try {
297
- newPdfManager = new LocalPdfManager(
298
- docId,
299
- pdfFile,
300
- source.password,
301
- evaluatorOptions,
302
- enableXfa,
303
- docBaseUrl
304
- );
305
- pdfManagerCapability.resolve(newPdfManager);
306
- } catch (ex) {
307
- pdfManagerCapability.reject(ex);
308
- }
309
- cachedChunks = [];
310
- };
311
- const readPromise = new Promise(function (resolve, reject) {
312
- const readChunk = function ({ value, done }) {
313
- try {
314
- ensureNotTerminated();
315
- if (done) {
316
- if (!newPdfManager) {
317
- flushChunks();
318
- }
319
- cancelXHRs = null;
320
- return;
321
- }
322
-
323
- loaded += arrayByteLength(value);
324
- if (!fullRequest.isStreamingSupported) {
325
- handler.send("DocProgress", {
326
- loaded,
327
- total: Math.max(loaded, fullRequest.contentLength || 0),
328
- });
329
- }
330
-
331
- if (newPdfManager) {
332
- newPdfManager.sendProgressiveData(value);
333
- } else {
334
- cachedChunks.push(value);
335
- }
336
-
337
- fullRequest.read().then(readChunk, reject);
338
- } catch (e) {
339
- reject(e);
340
- }
341
- };
342
- fullRequest.read().then(readChunk, reject);
343
- });
344
- readPromise.catch(function (e) {
345
- pdfManagerCapability.reject(e);
346
- cancelXHRs = null;
347
- });
348
-
349
- cancelXHRs = function (reason) {
350
- pdfStream.cancelAllRequests(reason);
351
- };
352
-
353
- return pdfManagerCapability.promise;
354
- }
355
-
356
- function setupDoc(data) {
357
- function onSuccess(doc) {
358
- ensureNotTerminated();
359
- handler.send("GetDoc", { pdfInfo: doc });
360
- }
361
-
362
- function onFailure(ex) {
363
- ensureNotTerminated();
364
-
365
- if (ex instanceof PasswordException) {
366
- const task = new WorkerTask(`PasswordException: response ${ex.code}`);
367
- startWorkerTask(task);
368
-
369
- handler
370
- .sendWithPromise("PasswordRequest", ex)
371
- .then(function ({ password }) {
372
- finishWorkerTask(task);
373
- pdfManager.updatePassword(password);
374
- pdfManagerReady();
375
- })
376
- .catch(function () {
377
- finishWorkerTask(task);
378
- handler.send("DocException", ex);
379
- });
380
- } else if (
381
- ex instanceof InvalidPDFException ||
382
- ex instanceof MissingPDFException ||
383
- ex instanceof UnexpectedResponseException ||
384
- ex instanceof UnknownErrorException
385
- ) {
386
- handler.send("DocException", ex);
387
- } else {
388
- handler.send(
389
- "DocException",
390
- new UnknownErrorException(ex.message, ex.toString())
391
- );
392
- }
393
- }
394
-
395
- function pdfManagerReady() {
396
- ensureNotTerminated();
397
-
398
- loadDocument(false).then(onSuccess, function (reason) {
399
- ensureNotTerminated();
400
-
401
- // Try again with recoveryMode == true
402
- if (!(reason instanceof XRefParseException)) {
403
- onFailure(reason);
404
- return;
405
- }
406
- pdfManager.requestLoadedStream();
407
- pdfManager.onLoadedStream().then(function () {
408
- ensureNotTerminated();
409
-
410
- loadDocument(true).then(onSuccess, onFailure);
411
- });
412
- });
413
- }
414
-
415
- ensureNotTerminated();
416
-
417
- const evaluatorOptions = {
418
- maxImageSize: data.maxImageSize,
419
- disableFontFace: data.disableFontFace,
420
- ignoreErrors: data.ignoreErrors,
421
- isEvalSupported: data.isEvalSupported,
422
- fontExtraProperties: data.fontExtraProperties,
423
- useSystemFonts: data.useSystemFonts,
424
- cMapUrl: data.cMapUrl,
425
- standardFontDataUrl: data.standardFontDataUrl,
426
- };
427
-
428
- getPdfManager(data, evaluatorOptions, data.enableXfa)
429
- .then(function (newPdfManager) {
430
- if (terminated) {
431
- // We were in a process of setting up the manager, but it got
432
- // terminated in the middle.
433
- newPdfManager.terminate(
434
- new AbortException("Worker was terminated.")
435
- );
436
- throw new Error("Worker was terminated");
437
- }
438
- pdfManager = newPdfManager;
439
-
440
- pdfManager.onLoadedStream().then(function (stream) {
441
- handler.send("DataLoaded", { length: stream.bytes.byteLength });
442
- });
443
- })
444
- .then(pdfManagerReady, onFailure);
445
- }
446
-
447
- handler.on("GetPage", function wphSetupGetPage(data) {
448
- return pdfManager.getPage(data.pageIndex).then(function (page) {
449
- return Promise.all([
450
- pdfManager.ensure(page, "rotate"),
451
- pdfManager.ensure(page, "ref"),
452
- pdfManager.ensure(page, "userUnit"),
453
- pdfManager.ensure(page, "view"),
454
- ]).then(function ([rotate, ref, userUnit, view]) {
455
- return {
456
- rotate,
457
- ref,
458
- userUnit,
459
- view,
460
- };
461
- });
462
- });
463
- });
464
-
465
- handler.on("GetPageIndex", function wphSetupGetPageIndex({ ref }) {
466
- const pageRef = Ref.get(ref.num, ref.gen);
467
- return pdfManager.ensureCatalog("getPageIndex", [pageRef]);
468
- });
469
-
470
- handler.on("GetDestinations", function wphSetupGetDestinations(data) {
471
- return pdfManager.ensureCatalog("destinations");
472
- });
473
-
474
- handler.on("GetDestination", function wphSetupGetDestination(data) {
475
- return pdfManager.ensureCatalog("getDestination", [data.id]);
476
- });
477
-
478
- handler.on("GetPageLabels", function wphSetupGetPageLabels(data) {
479
- return pdfManager.ensureCatalog("pageLabels");
480
- });
481
-
482
- handler.on("GetPageLayout", function wphSetupGetPageLayout(data) {
483
- return pdfManager.ensureCatalog("pageLayout");
484
- });
485
-
486
- handler.on("GetPageMode", function wphSetupGetPageMode(data) {
487
- return pdfManager.ensureCatalog("pageMode");
488
- });
489
-
490
- handler.on("GetViewerPreferences", function (data) {
491
- return pdfManager.ensureCatalog("viewerPreferences");
492
- });
493
-
494
- handler.on("GetOpenAction", function (data) {
495
- return pdfManager.ensureCatalog("openAction");
496
- });
497
-
498
- handler.on("GetAttachments", function wphSetupGetAttachments(data) {
499
- return pdfManager.ensureCatalog("attachments");
500
- });
501
-
502
- handler.on("GetJavaScript", function wphSetupGetJavaScript(data) {
503
- return pdfManager.ensureCatalog("javaScript");
504
- });
505
-
506
- handler.on("GetDocJSActions", function wphSetupGetDocJSActions(data) {
507
- return pdfManager.ensureCatalog("jsActions");
508
- });
509
-
510
- handler.on("GetPageJSActions", function ({ pageIndex }) {
511
- return pdfManager.getPage(pageIndex).then(function (page) {
512
- return pdfManager.ensure(page, "jsActions");
513
- });
514
- });
515
-
516
- handler.on("GetOutline", function wphSetupGetOutline(data) {
517
- return pdfManager.ensureCatalog("documentOutline");
518
- });
519
-
520
- handler.on("GetOptionalContentConfig", function (data) {
521
- return pdfManager.ensureCatalog("optionalContentConfig");
522
- });
523
-
524
- handler.on("GetPermissions", function (data) {
525
- return pdfManager.ensureCatalog("permissions");
526
- });
527
-
528
- handler.on("GetMetadata", function wphSetupGetMetadata(data) {
529
- return Promise.all([
530
- pdfManager.ensureDoc("documentInfo"),
531
- pdfManager.ensureCatalog("metadata"),
532
- ]);
533
- });
534
-
535
- handler.on("GetMarkInfo", function wphSetupGetMarkInfo(data) {
536
- return pdfManager.ensureCatalog("markInfo");
537
- });
538
-
539
- handler.on("GetData", function wphSetupGetData(data) {
540
- pdfManager.requestLoadedStream();
541
- return pdfManager.onLoadedStream().then(function (stream) {
542
- return stream.bytes;
543
- });
544
- });
545
-
546
- handler.on("GetStats", function wphSetupGetStats(data) {
547
- return pdfManager.ensureXRef("stats");
548
- });
549
-
550
- handler.on("GetAnnotations", function ({ pageIndex, intent }) {
551
- return pdfManager.getPage(pageIndex).then(function (page) {
552
- return page.getAnnotationsData(intent);
553
- });
554
- });
555
-
556
- handler.on("GetFieldObjects", function (data) {
557
- return pdfManager.ensureDoc("fieldObjects");
558
- });
559
-
560
- handler.on("HasJSActions", function (data) {
561
- return pdfManager.ensureDoc("hasJSActions");
562
- });
563
-
564
- handler.on("GetCalculationOrderIds", function (data) {
565
- return pdfManager.ensureDoc("calculationOrderIds");
566
- });
567
-
568
- handler.on(
569
- "SaveDocument",
570
- function ({ isPureXfa, numPages, annotationStorage, filename }) {
571
- pdfManager.requestLoadedStream();
572
-
573
- const promises = [
574
- pdfManager.onLoadedStream(),
575
- pdfManager.ensureCatalog("acroForm"),
576
- pdfManager.ensureDoc("xref"),
577
- pdfManager.ensureDoc("startXRef"),
578
- ];
579
-
580
- if (isPureXfa) {
581
- promises.push(pdfManager.serializeXfaData(annotationStorage));
582
- } else {
583
- for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
584
- promises.push(
585
- pdfManager.getPage(pageIndex).then(function (page) {
586
- const task = new WorkerTask(`Save: page ${pageIndex}`);
587
- return page
588
- .save(handler, task, annotationStorage)
589
- .finally(function () {
590
- finishWorkerTask(task);
591
- });
592
- })
593
- );
594
- }
595
- }
596
-
597
- return Promise.all(promises).then(function ([
598
- stream,
599
- acroForm,
600
- xref,
601
- startXRef,
602
- ...refs
603
- ]) {
604
- let newRefs = [];
605
- let xfaData = null;
606
- if (isPureXfa) {
607
- xfaData = refs[0];
608
- if (!xfaData) {
609
- return stream.bytes;
610
- }
611
- } else {
612
- for (const ref of refs) {
613
- newRefs = ref
614
- .filter(x => x !== null)
615
- .reduce((a, b) => a.concat(b), newRefs);
616
- }
617
-
618
- if (newRefs.length === 0) {
619
- // No new refs so just return the initial bytes
620
- return stream.bytes;
621
- }
622
- }
623
-
624
- const xfa = (acroForm instanceof Dict && acroForm.get("XFA")) || [];
625
- let xfaDatasets = null;
626
- if (Array.isArray(xfa)) {
627
- for (let i = 0, ii = xfa.length; i < ii; i += 2) {
628
- if (xfa[i] === "datasets") {
629
- xfaDatasets = xfa[i + 1];
630
- }
631
- }
632
- } else {
633
- // TODO: Support XFA streams.
634
- warn("Unsupported XFA type.");
635
- }
636
-
637
- let newXrefInfo = Object.create(null);
638
- if (xref.trailer) {
639
- // Get string info from Info in order to compute fileId.
640
- const infoObj = Object.create(null);
641
- const xrefInfo = xref.trailer.get("Info") || null;
642
- if (xrefInfo instanceof Dict) {
643
- xrefInfo.forEach((key, value) => {
644
- if (isString(key) && isString(value)) {
645
- infoObj[key] = stringToPDFString(value);
646
- }
647
- });
648
- }
649
-
650
- newXrefInfo = {
651
- rootRef: xref.trailer.getRaw("Root") || null,
652
- encryptRef: xref.trailer.getRaw("Encrypt") || null,
653
- newRef: xref.getNewRef(),
654
- infoRef: xref.trailer.getRaw("Info") || null,
655
- info: infoObj,
656
- fileIds: xref.trailer.get("ID") || null,
657
- startXRef,
658
- filename,
659
- };
660
- }
661
- xref.resetNewRef();
662
-
663
- return incrementalUpdate({
664
- originalData: stream.bytes,
665
- xrefInfo: newXrefInfo,
666
- newRefs,
667
- xref,
668
- datasetsRef: xfaDatasets,
669
- xfaData,
670
- });
671
- });
672
- }
673
- );
674
-
675
- handler.on("GetOperatorList", function wphSetupRenderPage(data, sink) {
676
- const pageIndex = data.pageIndex;
677
- pdfManager.getPage(pageIndex).then(function (page) {
678
- const task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
679
- startWorkerTask(task);
680
-
681
- // NOTE: Keep this condition in sync with the `info` helper function.
682
- const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;
683
-
684
- // Pre compile the pdf page and fetch the fonts/images.
685
- page
686
- .getOperatorList({
687
- handler,
688
- sink,
689
- task,
690
- intent: data.intent,
691
- renderInteractiveForms: data.renderInteractiveForms,
692
- annotationStorage: data.annotationStorage,
693
- })
694
- .then(
695
- function (operatorListInfo) {
696
- finishWorkerTask(task);
697
-
698
- if (start) {
699
- info(
700
- `page=${pageIndex + 1} - getOperatorList: time=` +
701
- `${Date.now() - start}ms, len=${operatorListInfo.length}`
702
- );
703
- }
704
- sink.close();
705
- },
706
- function (reason) {
707
- finishWorkerTask(task);
708
- if (task.terminated) {
709
- return; // ignoring errors from the terminated thread
710
- }
711
- // For compatibility with older behavior, generating unknown
712
- // unsupported feature notification on errors.
713
- handler.send("UnsupportedFeature", {
714
- featureId: UNSUPPORTED_FEATURES.errorOperatorList,
715
- });
716
-
717
- sink.error(reason);
718
-
719
- // TODO: Should `reason` be re-thrown here (currently that casues
720
- // "Uncaught exception: ..." messages in the console)?
721
- }
722
- );
723
- });
724
- });
725
-
726
- handler.on("GetTextContent", function wphExtractText(data, sink) {
727
- const pageIndex = data.pageIndex;
728
- sink.onPull = function (desiredSize) {};
729
- sink.onCancel = function (reason) {};
730
-
731
- pdfManager.getPage(pageIndex).then(function (page) {
732
- const task = new WorkerTask("GetTextContent: page " + pageIndex);
733
- startWorkerTask(task);
734
-
735
- // NOTE: Keep this condition in sync with the `info` helper function.
736
- const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;
737
-
738
- page
739
- .extractTextContent({
740
- handler,
741
- task,
742
- sink,
743
- normalizeWhitespace: data.normalizeWhitespace,
744
- includeMarkedContent: data.includeMarkedContent,
745
- combineTextItems: data.combineTextItems,
746
- })
747
- .then(
748
- function () {
749
- finishWorkerTask(task);
750
-
751
- if (start) {
752
- info(
753
- `page=${pageIndex + 1} - getTextContent: time=` +
754
- `${Date.now() - start}ms`
755
- );
756
- }
757
- sink.close();
758
- },
759
- function (reason) {
760
- finishWorkerTask(task);
761
- if (task.terminated) {
762
- return; // ignoring errors from the terminated thread
763
- }
764
- sink.error(reason);
765
-
766
- // TODO: Should `reason` be re-thrown here (currently that casues
767
- // "Uncaught exception: ..." messages in the console)?
768
- }
769
- );
770
- });
771
- });
772
-
773
- handler.on("GetStructTree", function wphGetStructTree(data) {
774
- return pdfManager.getPage(data.pageIndex).then(function (page) {
775
- return pdfManager.ensure(page, "getStructTree");
776
- });
777
- });
778
-
779
- handler.on("FontFallback", function (data) {
780
- return pdfManager.fontFallback(data.id, handler);
781
- });
782
-
783
- handler.on("Cleanup", function wphCleanup(data) {
784
- return pdfManager.cleanup(/* manuallyTriggered = */ true);
785
- });
786
-
787
- handler.on("Terminate", function wphTerminate(data) {
788
- terminated = true;
789
-
790
- const waitOn = [];
791
- if (pdfManager) {
792
- pdfManager.terminate(new AbortException("Worker was terminated."));
793
-
794
- const cleanupPromise = pdfManager.cleanup();
795
- waitOn.push(cleanupPromise);
796
-
797
- pdfManager = null;
798
- } else {
799
- clearPrimitiveCaches();
800
- }
801
- if (cancelXHRs) {
802
- cancelXHRs(new AbortException("Worker was terminated."));
803
- }
804
-
805
- for (const task of WorkerTasks) {
806
- waitOn.push(task.finished);
807
- task.terminate();
808
- }
809
-
810
- return Promise.all(waitOn).then(function () {
811
- // Notice that even if we destroying handler, resolved response promise
812
- // must be sent back.
813
- handler.destroy();
814
- handler = null;
815
- });
816
- });
817
-
818
- handler.on("Ready", function wphReady(data) {
819
- setupDoc(docParams);
820
- docParams = null; // we don't need docParams anymore -- saving memory.
821
- });
822
- return workerHandlerName;
823
- }
824
-
825
- static initializeFromPort(port) {
826
- const handler = new MessageHandler("worker", "main", port);
827
- WorkerMessageHandler.setup(handler, port);
828
- handler.send("ready", null);
829
- }
830
- }
831
-
832
- function isMessagePort(maybePort) {
833
- return (
834
- typeof maybePort.postMessage === "function" && "onmessage" in maybePort
835
- );
836
- }
837
-
838
- // Worker thread (and not Node.js)?
839
- if (
840
- typeof window === "undefined" &&
841
- !isNodeJS &&
842
- typeof self !== "undefined" &&
843
- isMessagePort(self)
844
- ) {
845
- WorkerMessageHandler.initializeFromPort(self);
846
- }
847
-
848
- export { WorkerMessageHandler, WorkerTask };