Repository navigation
Expand file tree
/
Copy pathpdf.js
More file actions
1949 lines (1858 loc) · 100 KB
/
Copy pathpdf.js
File metadata and controls
1949 lines (1858 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pdf.js — 飞鼠格式 PDF 转换域:加密/拆分/合并/渲染图片/扫描 OCR/表格→Excel/DOCX/HTML。
// 第三批抽取自 server.js(零逻辑改动,纯搬移)。
// convertScannedPdfToOcrDocx 依赖 text-docx.js(第四批),convertPresentationTo* 依赖
// office-convert.js(第四批)——顶层不 require 以避免循环,函数内延迟 require。
const fs = require("fs");
const fsp = require("fs/promises");
const crypto = require("node:crypto");
const os = require("os");
const path = require("path");
const yazl = require("yazl");
const sanitize = require("sanitize-filename");
const { PDFDocument } = require("pdf-lib");
const { PDFTOPPM_PATH, DOCENGINE_PATH, QPDF_PATH, pdfImageTargets } = require("./config");
const { run, commandExists, escapeHtml, safeBaseName } = require("./utils");
const { zipFiles, openZipEntries, openZipEntriesFromBuffer, readZipEntryToFile } = require("./zip-util");
const { convertImagesToPdf } = require("./image");
const { throwIfCanceled } = require("./conversion-cancellation");
const { ocrAvailable, createOcrWorker, recognizeImageTextWithWorker, recognizeImageResultWithWorker } = require("./ocr");
const { loadPdfjs } = require("./pdfjs");
const { classifyPdf } = require("./pdf-classifier");
const {
extractPdfRowsByPage,
renderPdfTablePage,
extractComplexPdfTableModel,
writePdfTableWorkbook
} = require("./pdf-table");
const { assertPdfPages } = require("./resource-policy");
const { mergeCnSpaces } = require("./pdf-table-runtime");
const { OfficeQualityError } = require("./office-quality");
const { withStructuredPdf } = require("./pdf-structure-engine");
const { chooseTableCandidate } = require("./pdf-structure-score");
const { structureError, validateStructureManifest } = require("./pdf-structure-contract");
const { writePdfOfficeDocx } = require("./pdf-office-docx");
const { writePdfOfficeXlsx } = require("./pdf-office-xlsx");
const { parseXmlToJson } = require("./xml-json");
const logger = require("./logger");
const { extractPdfScanRegions } = require("./pdf-ocr-regions");
const { reportConversionProgress, captureConversionProgressReporter } = require("./conversion-progress");
const { createOfficeWorkspace } = require("./office-runtime");
const { createPdfRenderWorkspace } = require("./pdf-render-workspace");
async function convertPdfDecrypt(inputPath, outputPath, password) {
const pwd = String(password || "");
// 优先用 qpdf(支持 RC4/AES-128/AES-256,含本应用 qpdf 加密的 AES-256 输出);
// qpdf 缺失时回退 pdf-lib(仅支持 RC4/AES-128,兜底)。
if (await commandExists(QPDF_PATH, ["--version"])) {
const args = pwd
? [`--password=${pwd}`, "--decrypt", "--", inputPath, outputPath]
: ["--decrypt", "--", inputPath, outputPath];
await run(QPDF_PATH, args, { timeout: 1000 * 60 * 5 });
return;
}
const data = await fsp.readFile(inputPath);
const pdf = await PDFDocument.load(data, { password: pwd, ignoreEncryption: false });
await fsp.writeFile(outputPath, await pdf.save());
}
async function convertPdfEncrypt(inputPath, outputPath, password) {
const pwd = String(password || "");
if (!pwd.trim()) {
const error = new Error("加密 PDF 需要先设置密码。");
error.code = "PDF_ENCRYPT_NO_PASSWORD";
error.messages = {
zhCN: "加密 PDF 需要先设置密码。",
enUS: "A password is required to encrypt the PDF."
};
throw error;
}
if (!(await commandExists(QPDF_PATH, ["--version"]))) {
const error = new Error("PDF 加密引擎(qpdf)不可用,请确认安装包完整。");
error.code = "PDF_ENCRYPT_UNAVAILABLE";
error.messages = {
zhCN: "PDF 加密引擎(qpdf)不可用,请确认安装包完整。",
enUS: "PDF encryption engine (qpdf) is unavailable. Verify the installation bundle is complete."
};
throw error;
}
await run(QPDF_PATH, ["--encrypt", pwd, pwd, "256", "--", inputPath, outputPath], { timeout: 1000 * 60 * 5 });
}
const OCR_QUALITY_THRESHOLD = 0.65;
function normalizedPdfText(value) {
return String(value || "").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
}
function missingPdfText(pages, editableText) {
const actual = normalizedPdfText(editableText);
const missing = pages.flatMap((page) => pdfCoverageSegments(page)
.filter((text) => {
const expected = normalizedPdfText(text);
// A geometrically separated segment may be one Chinese title glyph or
// a table number. Do not silently discard it after cell segmentation.
return expected.length > 0 && !actual.includes(expected);
}).map((text) => ({ pageNumber: page.pageNumber, text })));
// A table's row number is not evidence that the same page number survived.
// Geometrically identified numeric footers retain their surrounding marks
// and multiplicity instead of being matched as digits anywhere in the body.
const compact = String(editableText || '').normalize('NFKC').replace(/\s/gu, '');
const counts = new Map();
for (const footer of nativePdfFooters(pages)) {
const count = (counts.get(footer.text) || 0) + 1;
counts.set(footer.text, count);
if (compact.split(footer.text).length - 1 < count
&& !missing.some(item => item.pageNumber === footer.pageNumber && item.text === footer.text)) {
missing.push({ pageNumber: footer.pageNumber, text: footer.text });
}
}
return missing;
}
function nativePdfFooters(pages) {
return pages.flatMap(page => {
if (!Number.isFinite(page.height) || page.height <= 0) return [];
return (page.lines || []).flatMap(line => {
if (!Number.isFinite(line.y) || line.y < page.height * 0.88 || line.y > page.height) return [];
const text = String(line.text || '').normalize('NFKC').replace(/\s/gu, '');
const match = /^([\p{P}\p{S}]+)(\d{1,6})([\p{P}\p{S}]+)$/u.exec(text);
return match ? [{ pageNumber: page.pageNumber, text, skeleton: match[1] + match[3] }] : [];
});
});
}
function pdfCoverageSegments(page) {
if (!page.lines?.length || !page.lines.every(line => line.items?.length
&& line.items.every(item => typeof item.text === "string" && [item.x, item.end, item.height].every(Number.isFinite)))) {
return (page.rows || []).flatMap(row => row);
}
// A line can cross several table cells. DOCX correctly serializes all lines
// of one cell before the next cell; comparing a whole displayed row would
// falsely call those preserved words missing. Adjacent glyphs remain joined
// so a missing character in a per-glyph text run is still rejected.
return page.lines.flatMap(line => {
const segments = [];
let current = "", previous;
for (const item of line.items) {
const gap = previous ? item.x - previous.end : 0;
if (previous && gap > Math.max(1, Math.min(previous.height, item.height) * 0.5)) {
segments.push(current); current = "";
}
current += item.text;
previous = item;
}
if (current) segments.push(current);
return segments;
});
}
async function sourcePdfPages(inputPath, options = {}) {
return options.pdfTextPages || (options.extractPdfRowsByPage || extractPdfRowsByPage)(inputPath);
}
function pdfPageNeedsOcr(page) {
return !page.ocr && page.blank !== true && (
!page.rows?.some((row) => row.some((cell) => String(cell).trim()))
|| (page.ocrImageCoverage ?? page.imageCoverage) > 0
);
}
function mergeOcrLineSpaces(value) {
// Chinese intra-line spacing can be normalized, but a newline is paragraph
// structure: never join the scan heading to its following order-number row.
return String(value || '').split(/\r?\n/).map(line => String(mergeCnSpaces(line) || '').trim()).join('\n').trim();
}
function nativeOcrMergeError(pageNumber) {
return structureError('PDF_OCR_NATIVE_MERGE_UNVERIFIED',
`第 ${pageNumber} 页的原生文字与 OCR 结果无法可靠对应,已停止导出以避免重复或错误的正文。`,
`Native text and OCR could not be reliably aligned on page ${pageNumber}. Export was stopped to avoid duplicate or incorrect content.`);
}
function mergeNativeOcrGeometry(page, result) {
const geometry = result.geometry;
if (!geometry || result.orientation !== 0 || result.deskewAngle !== 0 || !Array.isArray(page.lines)
|| !(page.width > 0 && page.height > 0 && geometry.width > 0 && geometry.height > 0)) return null;
const validBox = box => Array.isArray(box) && box.length === 4 && box.every(Number.isFinite)
&& box[2] > box[0] && box[3] > box[1];
const nativeLines = page.lines.filter(line => String(line.text || '').trim());
if (nativeLines.some(line => !validBox(line.bbox) || !Array.isArray(line.cells))) return null;
const nativeBoxes = nativeLines.flatMap(line => line.items?.length ? line.items.map(item => item.bbox) : [line.bbox]);
if (nativeBoxes.some(box => !validBox(box))) return null;
const compact = text => String(text || '').replace(/\s/gu, '');
const ocrLines = geometry.lines;
if (!Array.isArray(ocrLines) || ocrLines.some(line => !Array.isArray(line.words) || line.words.some(word => !validBox(word.bbox)))
|| compact(ocrLines.flatMap(line => line.words.map(word => word.text)).join('')) !== compact(result.text)) return null;
const blocks = nativeLines.map(line => ({ bbox: line.bbox, rows: [line.cells] }));
for (const line of ocrLines) {
let words = [], boxes = [];
const flush = () => {
if (words.length) blocks.push({ bbox: [Math.min(...boxes.map(box => box[0])), Math.min(...boxes.map(box => box[1])),
Math.max(...boxes.map(box => box[2])), Math.max(...boxes.map(box => box[3]))], rows: [[mergeOcrLineSpaces(words.join(' '))]] });
words = []; boxes = [];
};
for (const word of line.words) {
const box = word.bbox.map((coordinate, index) => coordinate*(index%2 ? page.height/geometry.height : page.width/geometry.width));
if (box[0] < 0 || box[1] < 0 || box[2] > page.width || box[3] > page.height) return null;
const overlaps = nativeBoxes.filter(native => Math.min(native[2], box[2])-Math.max(native[0], box[0]) > 0
&& Math.min(native[3], box[3])-Math.max(native[1], box[1]) > 0);
if (overlaps.length) {
// Suppress an OCR version of native glyphs only when its full word
// lies within the covered source text region. A word spanning a scan and native
// text cannot be split safely by guessing at similar characters.
const intervals = overlaps.flatMap(native => {
// PDF.js item boxes end at the baseline; rendered descenders may
// extend below it. Keep horizontal containment tight, with a font-
// relative vertical allowance for those visible glyph pixels.
const horizontal = Math.min(2, (native[3]-native[1])*.2);
const vertical = Math.min(5, (native[3]-native[1])*.35);
return box[1] >= native[1]-vertical && box[3] <= native[3]+vertical
? [[native[0]-horizontal, native[2]+horizontal]] : [];
}).sort((left, right) => left[0]-right[0]);
// PDFs commonly split one word into per-glyph text items. The union
// of their bounded intervals must cover the whole OCR word; a real
// uncovered gap toward scanned text still fails rather than guessing.
let covered = box[0];
for (const [left, right] of intervals) {
if (left > covered) break;
covered = Math.max(covered, right);
}
if (covered < box[2]) throw nativeOcrMergeError(page.pageNumber);
flush();
} else { words.push(word.text); boxes.push(box); }
}
flush();
}
blocks.sort((a, b) => a.bbox[1]-b.bbox[1] || a.bbox[0]-b.bbox[0]);
return blocks.flatMap(block => block.rows);
}
async function fillMissingPdfPageText(inputPath, pages, options = {}) {
throwIfCanceled(options.signal);
// A digital header does not make a raster body searchable. Empty pages alone
// need no OCR. Coverage also catches a scan behind a searchable stamp.
const missing = pages.filter(pdfPageNeedsOcr);
if (!missing.length) return pages;
if (!(options.ocrAvailable || ocrAvailable)()) {
throw structureError("PDF_OCR_REQUIRED", "PDF 中有缺少文字层的页面,需要启用 OCR 引擎才能完整转换。",
"Some PDF pages have no text layer. OCR is required for a complete conversion.");
}
assertPdfPages(pages.length, { ocr: true });
reportConversionProgress({ stage: "recognizing", completed: 0, total: missing.length, unit: "pages" });
const workspace = await createPdfRenderWorkspace(inputPath, options);
const { tempDir } = workspace;
let worker;
try {
worker = await (options.createOcrWorker || createOcrWorker)();
const completed = new Map();
// A rendered page can squash a scan's glyphs and let readable digital text
// hide its low OCR quality. Recover non-overlapping, fully visible raw scans
// at their original aspect ratio and judge each region separately.
const scanRegions = !options.renderPdfTablePage && missing.every(page => Number.isInteger(page.pageNumber) && Array.isArray(page.lines))
? await extractPdfScanRegions(workspace.inputPath, missing, tempDir) : new Map();
for (const page of missing) {
throwIfCanceled(options.signal);
const pageNumber = page.pageNumber || pages.indexOf(page) + 1;
const pageOptions = { ...options, pageNumber };
const regions = scanRegions.get(pageNumber);
if (regions?.length) {
const blocks = (page.lines || []).map(line => ({ bbox: line.bbox, rows: [line.cells] }));
const warnings = [];
for (const region of regions) {
throwIfCanceled(options.signal);
const result = options.recognizeImageTextWithWorker
? { text: await options.recognizeImageTextWithWorker(worker, region.outputPath, pageOptions), warnings: [] }
: await (options.recognizeImageResultWithWorker || recognizeImageResultWithWorker)(worker, region.outputPath, pageOptions);
const text = mergeOcrLineSpaces(result.text);
if (text) blocks.push({ bbox: region.bbox, rows: text.split(/\r?\n/).filter(line=>line.trim()).map(line=>[line]) });
warnings.push(...(result.warnings || []));
}
blocks.sort((a,b)=>a.bbox[1]-b.bbox[1] || a.bbox[0]-b.bbox[0]);
warnings.push({ code:'PDF_OCR_ORIGINAL_IMAGE', messages: {
zhCN:'已按原始扫描图的像素和比例分区识别,避免 PDF 拉伸造成乱码;请核对文字、金额和阅读顺序。',
enUS:'Visible scan regions were recognized at their original pixel size and aspect ratio to avoid PDF stretching. Review text, amounts and reading order.'
} });
completed.set(page,{...page,ocr:true,ocrWarnings:warnings,rows:blocks.flatMap(block=>block.rows)});
throwIfCanceled(options.signal);
reportConversionProgress({ stage: "recognizing", completed: completed.size, total: missing.length, unit: "pages" });
continue;
}
const rendered = await (options.renderPdfTablePage || renderPdfTablePage)(workspace.inputPath, pageNumber, tempDir, 200, options);
const result = options.recognizeImageTextWithWorker
? { text: await options.recognizeImageTextWithWorker(worker, rendered.outputPath, pageOptions), warnings: [] }
: await (options.recognizeImageResultWithWorker || recognizeImageResultWithWorker)(worker, rendered.outputPath,
{ ...pageOptions, includeGeometry: (page.rows || []).some(row => row.some(cell => String(cell).trim())) });
const text = mergeOcrLineSpaces(result.text);
const geometricRows = mergeNativeOcrGeometry(page, result);
if (geometricRows) {
completed.set(page, { ...page, ocr: true, ocrWarnings: result.warnings || [], rows: geometricRows });
throwIfCanceled(options.signal);
reportConversionProgress({ stage: "recognizing", completed: completed.size, total: missing.length, unit: "pages" });
continue;
}
const rows = text ? text.split(/\r?\n/).filter((line) => line.trim()).map((line) => [line]) : [];
const omittedNative = [];
const matchedRows = new Set();
for (const nativeRow of page.rows || []) {
const native = normalizedPdfText(nativeRow.join(' '));
if (!native) continue;
const index = rows.findIndex((row, index) => !matchedRows.has(index) && normalizedPdfText(row.join(' ')) === native);
if (index >= 0) { rows[index] = nativeRow; matchedRows.add(index); }
else {
let restored = false;
for (const [rowIndex, row] of rows.entries()) {
if (matchedRows.has(rowIndex)) continue;
const value = row.join(' ');
const normalized = [];
const spans = [];
let offset = 0;
for (const character of value) {
for (const letter of normalizedPdfText(character).split('')) {
normalized.push(letter);
spans.push([offset, offset + character.length]);
}
offset += character.length;
}
const at = normalized.join('').indexOf(native);
if (native.length > 1 && at >= 0) {
// Canonical matching locates a span only. Restore the exact native
// spelling and punctuation: 118600 must never replace 1186.00.
row.splice(0, row.length, value.slice(0, spans[at][0]) + nativeRow.join(' ') + value.slice(spans[at + native.length - 1][1]));
restored = true;
matchedRows.add(rowIndex);
break;
}
}
if (!restored) omittedNative.push(nativeRow);
}
}
if (omittedNative.length) throw nativeOcrMergeError(pageNumber);
completed.set(page, { ...page, ocr: true, ocrWarnings: result.warnings || [], rows });
throwIfCanceled(options.signal);
reportConversionProgress({ stage: "recognizing", completed: completed.size, total: missing.length, unit: "pages" });
}
const result = pages.map((page) => completed.get(page) || page);
if (!result.some((page) => page.rows.length)) {
throw structureError("PDF_OCR_NO_TEXT", "OCR 没有识别出文字,请确认扫描页清晰、方向正确。",
"OCR found no text. Check that the scanned pages are clear and correctly oriented.");
}
return result;
} finally {
if (worker) await worker.terminate().catch(() => {});
await workspace.cleanup().catch(() => {});
}
}
function restoreNativeStructureText(manifest, nativePages) {
let restored = 0;
for (const page of manifest.pages || []) {
const native = nativePages.find((candidate, index) => (candidate.pageNumber || index + 1) === page.pageNumber);
if (!native?.lines?.length) continue;
const sx = page.width / native.width;
const sy = page.height / native.height;
const editable = () => (page.blocks || []).map((block) => block.text || "")
.concat((page.tables || []).flatMap((table) => (table.cells || []).map((cell) => cell.text || ""))).join(" ");
for (const line of native.lines) {
if (!missingPdfText([{ rows: [line.cells] }], editable()).length) continue;
const bbox = line.bbox.map((value, index) => Math.max(0,
Math.min(index % 2 ? page.height : page.width, value * (index % 2 ? sy : sx))));
// Replace a single OCR line in the same location when its text was corrupted.
// Never remove a table, figure, or a larger paragraph just to insert native text.
const overlapping = (page.blocks || []).filter((block) =>
["paragraph", "heading"].includes(block.type) && Array.isArray(block.bbox)
&& block.bbox[3] - block.bbox[1] <= (bbox[3] - bbox[1]) * 2
&& Math.abs((block.bbox[1] + block.bbox[3] - bbox[1] - bbox[3]) / 2) < (bbox[3] - bbox[1])
&& Math.min(block.bbox[2], bbox[2]) > Math.max(block.bbox[0], bbox[0]));
if (overlapping.length === 1) {
overlapping[0].text = line.text;
overlapping[0].confidence = 1;
} else {
page.blocks = [...(page.blocks || []), { type: "paragraph", bbox, text: line.text, confidence: 1 }];
page.blocks.sort((a, b) => (a.bbox?.[1] || 0) - (b.bbox?.[1] || 0)
|| (a.bbox?.[0] || 0) - (b.bbox?.[0] || 0));
}
restored += 1;
}
}
return restored;
}
function pdfLayoutFallbackWarning(reason) {
return { code: "PDF_DOCX_LAYOUT_FALLBACK", messages: {
zhCN: reason === "images" ? "尚不能确认图片内容已完整保留,已改用文字提取和 OCR 重建;插图和复杂版式需对照原 PDF 复核。"
: reason === "content" ? "版式引擎输出存在缺字,已改用原生文字重建可编辑文档;复杂版式可能变化。"
: "版式引擎不可用,已重建可编辑文字及简单表格;复杂版式可能变化。",
enUS: reason === "images" ? "Image preservation could not be verified. Text extraction and OCR were used instead; compare illustrations and complex layout with the PDF."
: reason === "content" ? "The layout engine omitted source text. Editable text was rebuilt; complex layout may change."
: "The layout engine is unavailable. Editable text and simple tables were rebuilt; complex layout may change."
} };
}
function pdfOcrWarnings(pages) {
const recognized = pages.filter((page) => page.ocr).map((page, index) => page.pageNumber || index + 1);
if (!recognized.length) return [];
return [{ code: "PDF_PAGES_OCR", messages: {
zhCN: `已对 ${recognized.length} 个文字层缺失或不完整的页面进行 OCR;识别出的字符、标点需要复核。`,
enUS: `OCR was applied to ${recognized.length} pages with missing or incomplete text layers. Review recognized characters and punctuation.`
} }, ...new Map(pages.flatMap(page => page.ocrWarnings || []).map(warning => [warning.code, warning])).values()];
}
function selectedStructureManifest(manifest) {
const copy = structuredClone(manifest);
copy.pages = (copy.pages || []).map((page) => {
if (!Array.isArray(page.tableCandidates)) return page;
const selected = chooseTableCandidate(page.tableCandidates).table;
const copyPage = { ...page, tables: [structuredClone(selected)] };
delete copyPage.tableCandidates;
return copyPage;
});
return copy;
}
function tableNotDetectedError() {
return structureError(
"PDF_TABLE_NOT_DETECTED",
"未检测到可可靠编辑的表格,无法生成 Excel。",
"No reliably editable table was detected, so an Excel workbook cannot be created."
);
}
async function outputInfo(outputPath) {
try {
return await fsp.lstat(outputPath);
} catch (error) {
if (error?.code === "ENOENT") return null;
throw error;
}
}
async function publishAttempt(attemptPath, outputPath) {
const existing = await outputInfo(outputPath);
if (existing && (!existing.isFile() || existing.isSymbolicLink())) {
throw new Error("unsafe output target");
}
if (!existing) {
await fsp.rename(attemptPath, outputPath);
return;
}
const backupPath = `${outputPath}.backup-${crypto.randomUUID()}`;
await fsp.rename(outputPath, backupPath);
try {
await fsp.rename(attemptPath, outputPath);
} catch (error) {
try {
await fsp.rename(backupPath, outputPath);
} catch {
await fsp.copyFile(backupPath, outputPath).catch(() => {});
}
throw error;
}
await fsp.rm(backupPath, { force: true }).catch(() => {});
}
async function withAttemptOutput(outputPath, produce, signal) {
const attemptPath = `${outputPath}.attempt-${crypto.randomUUID()}`;
try {
const result = await produce(attemptPath);
const info = await fsp.lstat(attemptPath);
if (!info.isFile() || info.isSymbolicLink() || info.size < 1) throw new Error("invalid attempt output");
throwIfCanceled(signal);
await publishAttempt(attemptPath, outputPath);
return result;
} finally {
await fsp.rm(attemptPath, { force: true }).catch(() => {});
}
}
async function convertStructuredPdf({ inputPath, outputPath, target, options = {} }) {
const boundary = options.withStructuredPdf || withStructuredPdf;
return boundary(inputPath, options, async (manifest, assetRoot) => {
const initial = selectedStructureManifest(manifest);
const columns = await (options.repairScanColumnLayout || require('./pdf-scan-columns').repairScanColumnLayout)(initial, assetRoot, options);
const selected = columns.manifest === initial ? initial
: structuredClone(validateStructureManifest(columns.manifest, assetRoot));
const columnWarnings = Array.isArray(columns.warnings) ? columns.warnings : [];
if (target === "xlsx") {
const tables = selected.pages.reduce((total, page) => total + (page.tables || []).length, 0);
if (tables === 0) throw tableNotDetectedError();
const result = await withAttemptOutput(outputPath, (attemptPath) =>
(options.writePdfOfficeXlsx || writePdfOfficeXlsx)({
manifest: selected, assetRoot, outputPath: attemptPath
}), options.signal);
return { ...result, warnings: [...columnWarnings, ...(result?.warnings || [])] };
}
if (target === "docx") {
let math = { pageNumbers: [] };
const nativePages = await sourcePdfPages(inputPath, options);
const restored = restoreNativeStructureText(selected, nativePages);
const repaired = restored ? validateStructureManifest(selected, assetRoot) : selected;
const result = await withAttemptOutput(outputPath, async (attemptPath) => {
const written = await (options.writePdfOfficeDocx || writePdfOfficeDocx)({
manifest: repaired, assetRoot, outputPath: attemptPath
});
// The writer already validates assets and tables. Also compare editable
// text with the actual PDF text layer so a reference image cannot hide lost text.
if (!options.writePdfOfficeDocx) {
math = await repairNativePdfDocx(attemptPath, nativePages, { ...options, inputPath, repairLayout: false });
const validation = await validateNativePdfDocx(attemptPath);
if (missingPdfText(nativePages, validation.editableText).length) {
throw structureError("PDF_DOCX_TEXT_COVERAGE_FAILED", "生成的 Word 缺少原生文字,已阻止不完整输出。",
"The generated Word document omitted native text; incomplete output was rejected.");
}
}
return written;
}, options.signal);
return { ...result, warnings: [...columnWarnings, ...(result?.warnings || []), ...nativeMathWarnings(math), ...(restored ? [{ code: "PDF_NATIVE_TEXT_RESTORED", messages: {
zhCN: "已使用 PDF 原生文字补回结构识别遗漏的内容。", enUS: "Native PDF text was restored where structure recognition omitted it."
} }] : [])] };
}
throw structureError("PDF_STRUCTURE_TARGET_UNSUPPORTED",
"不支持该结构化输出格式。", "Unsupported structured PDF target.");
});
}
function assertPdfTableOcrQuality(model) {
const ocrPages = (model?.summary || []).filter((page) => page.source === "ocr" && page.tableCount > 0);
if (!ocrPages.length) return;
const worst = Math.min(...ocrPages.map((page) => page.confidence));
if (worst >= OCR_QUALITY_THRESHOLD) return;
const percent = Math.round(worst * 100);
const error = new Error(
`扫描件 OCR 识别质量过低(最低置信度 ${percent}%),无法准确转换表格。可能原因是图片模糊、倾斜、阴影或分辨率不足;请提供更清晰的扫描件后重试。`
);
error.code = "PDF_TABLE_OCR_LOW_QUALITY";
error.messages = {
zhCN: `扫描件 OCR 识别质量过低(置信度 ${percent}%),可能因模糊、倾斜或阴影导致,无法准确转换表格。`,
enUS: `Scanned PDF OCR quality is too low (confidence ${percent}%). The page may be blurry, skewed, or shadowed, so the table cannot be converted accurately.`
};
throw error;
}
async function convertPdf(inputPath, outputPath, target, options = {}) {
throwIfCanceled(options.signal);
if (target === "pdf") {
if (options.pdfAction === "encrypt") {
await convertPdfEncrypt(inputPath, outputPath, options.password);
} else if (options.pdfAction === "decrypt") {
await convertPdfDecrypt(inputPath, outputPath, options.password || "");
} else {
await splitPdfToZip(inputPath, outputPath, options);
}
return;
}
if (pdfImageTargets.includes(target)) {
await convertPdfPagesToImagesZip(inputPath, outputPath, target, options);
return;
}
let classification;
if (target === "docx" || target === "xlsx") {
classification = await (options.classifyPdf || classifyPdf)(inputPath);
if (classification.kind !== "native") {
try {
return await (options.convertStructuredPdf || convertStructuredPdf)({
inputPath,
outputPath,
target,
classification,
options
});
} catch (error) {
// 图片型 PDF(无文字层,含「图片→PDF」的产物)走结构化引擎可能失败/崩溃。
// docx 回落纯 OCR 段落(与 txt/html 的扫描件链路同源),不阻断转换;
// xlsx 无可靠回落(宁可不给也不给错表),只补一条可行动的指引文案。
if (target === "docx" && ["PDF_STRUCTURE_PARSE_FAILED", "PDF_STRUCTURE_ENGINE_MISSING",
"PDF_STRUCTURE_MODEL_MISSING", "PDF_DOCX_NO_EDITABLE_CONTENT", "PDF_DOCX_TEXT_COVERAGE_FAILED"].includes(error?.code)) {
logger.warn(`扫描件结构化 docx 失败,回落 OCR 段落:${inputPath}`, error);
return (options.convertScannedPdfToOcrDocx || convertScannedPdfToOcrDocx)(inputPath, outputPath,
{ ...options, skipTableRebuild: true });
}
if (target === "xlsx" && error?.code === "PDF_TABLE_NOT_DETECTED") {
throw structureError(
"PDF_TABLE_NOT_DETECTED",
"未在该 PDF 中检测到表格,无法生成 Excel。若它是由图片合成的 PDF 或扫描件,请改用「PDF 转 Word」或「PDF 转 TXT」(走 OCR 识别文字)。",
"No editable table was detected in this PDF. If it was assembled from images or is a scan, convert it to Word or TXT instead (OCR path)."
);
}
throw error;
}
return;
}
}
if (target === "xlsx") {
const model = await extractComplexPdfTableModel(inputPath, { ...options, classification });
assertPdfTableOcrQuality(model);
reportConversionProgress({ stage: "converting" });
await writePdfTableWorkbook(model, outputPath);
return;
}
const pages = await sourcePdfPages(inputPath, options);
const hasExtractableRows = pages.some((page) => page.rows.length);
if (target === "md") {
const completePages = await fillMissingPdfPageText(inputPath, pages, options);
await fsp.writeFile(outputPath, pdfPagesToMarkdown(completePages), "utf8");
return { warnings: [...pdfOcrWarnings(completePages), { code: "PDF_MARKDOWN_REFLOW", messages: {
zhCN: "已提取文字、可辨认的标题和简单表格;Markdown 会重排版式,插图和复杂表格需对照原 PDF 复核。",
enUS: "Text, recognizable headings and simple tables were extracted. Markdown reflows the layout; check illustrations and complex tables against the PDF."
} }] };
}
if (!hasExtractableRows) {
if (target === "txt") {
return convertScannedPdfToOcrText(inputPath, outputPath, options);
}
if (target === "docx") {
return convertScannedPdfToOcrDocx(inputPath, outputPath, options);
}
if (target === "html") {
return convertScannedPdfToOcrHtml(inputPath, outputPath, options);
}
throw new Error("这个 PDF 没有可提取的文字,可能是扫描版图片 PDF。");
}
if (target === "txt") {
const completePages = await fillMissingPdfPageText(inputPath, pages, options);
const text = completePages
.map((page) => [`## ${page.name}`, ...page.rows.map((row) => row.join("\t"))].join("\n"))
.join("\n\n");
await fsp.writeFile(outputPath, text, "utf8");
return { warnings: pdfOcrWarnings(completePages) };
}
if (target === "html") {
const completePages = await fillMissingPdfPageText(inputPath, pages, options);
const body = completePages.map((page) => {
const rows = page.rows.map((row) => row.length > 1
? `<table><tr>${row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join("")}</tr></table>`
: `<p>${escapeHtml(row[0] || "")}</p>`).join("\n");
return `<h2>${escapeHtml(page.name)}</h2>${rows}`;
}).join("\n");
await fsp.writeFile(outputPath, `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>PDF table export</title>
<style>
body{font-family:Arial,"Microsoft YaHei",sans-serif;margin:24px}
table{border-collapse:collapse;margin-bottom:24px}
td{border:1px solid #999;padding:4px 8px;vertical-align:top}
</style>
</head>
<body>${body}</body>
</html>`, "utf8");
return { warnings: pdfOcrWarnings(completePages) };
}
if (target === "docx") {
return convertPdfToDocx(inputPath, outputPath, pages, options);
}
throw new Error("PDF 暂时只支持转换为 XLSX、TXT、HTML、DOCX、PNG、JPG,或拆分为单页 PDF。");
}
function pdfPagesToMarkdown(pages) {
const escape = value => String(value ?? '').replace(/([\\`*_\[\]<>|#])/g, '\\$1').replace(/\r?\n/g, '<br>');
return pages.map(page => {
const heights = (page.lines || []).map(line => line.height).filter(Number.isFinite).sort((a, b) => a - b);
const bodyHeight = heights[Math.floor(heights.length / 2)] || 12;
const chunks = [];
for (let index = 0; index < page.rows.length; index += 1) {
const row = page.rows[index];
if (row.length > 1) {
const table = [row];
while (page.rows[index + 1]?.length === row.length) table.push(page.rows[++index]);
chunks.push(`| ${table[0].map(escape).join(' | ')} |\n| ${row.map(() => '---').join(' | ')} |\n`
+ table.slice(1).map(cells => `| ${cells.map(escape).join(' | ')} |`).join('\n'));
} else {
const heading = !page.ocr && row[0]?.length < 160 && (page.lines?.[index]?.height || 0) >= bodyHeight * 1.35;
chunks.push(`${heading ? '## ' : ''}${escape(row[0])}`);
}
}
return chunks.join('\n\n');
}).join('\n\n---\n\n') + '\n';
}
function xmlDocxText(value) {
return String(value ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function xmlDocxParagraph(text, bold = false) {
const run = bold ? `<w:rPr><w:b/></w:rPr>` : "";
return `<w:p><w:r>${run}<w:t xml:space="preserve">${xmlDocxText(text)}</w:t></w:r></w:p>`;
}
function writeDocxZip(outputPath, entries) {
return new Promise((resolve, reject) => {
const archive = new yazl.ZipFile();
for (const entry of entries) {
archive.addBuffer(Buffer.from(entry.content, "utf8"), entry.path);
}
const output = fs.createWriteStream(outputPath);
archive.outputStream.pipe(output);
output.on("close", resolve);
output.on("error", reject);
archive.end();
});
}
// 物理天花板(Node 单个 Buffer 上限约 2GB),不是业务限制:
// 正常 DOCX 包与单个 XML part 远小于此值;此阈值仅用于在解压前拦截声明了超大量
// uncompressedSize 的恶意 ZIP 炸弹条目,避免实际解压导致 OOM。任何正常文档都不会触及。
const MAX_NATIVE_DOCX_PACKAGE_BYTES = 2 * 1024 * 1024 * 1024;
const MAX_NATIVE_DOCX_XML_BYTES = 2 * 1024 * 1024 * 1024;
const NATIVE_DOCX_PARTS = new Set([
"[Content_Types].xml", "_rels/.rels", "word/document.xml", "word/_rels/document.xml.rels"
]);
function safePackageEntry(name) {
if (typeof name !== "string" || !name || name.includes("\\") || name.startsWith("/")) return false;
const candidate = name.endsWith("/") ? name.slice(0, -1) : name;
return Boolean(candidate) && candidate.split("/").every((piece) => piece && piece !== "." && piece !== "..");
}
async function inspectNativeDocxPackage(zipPath, includeAll = false) {
// Read the whole package into memory and drive yauzl via fromBuffer: yauzl.open's
// fd_slicer path can silently stall on a valid deflate stream (see openZipEntriesFromBuffer).
let buffer;
try {
const stats = await fsp.stat(zipPath);
if (!stats.isFile() || stats.isSymbolicLink() || stats.size < 1) {
throw new Error("unsafe DOCX package file");
}
if (stats.size > MAX_NATIVE_DOCX_PACKAGE_BYTES) {
throw new Error("DOCX package is too large");
}
buffer = await fsp.readFile(zipPath);
} catch (error) {
if (error?.message === "DOCX package is too large") throw error;
throw new Error("unsafe DOCX package file");
}
const zipfile = await openZipEntriesFromBuffer(buffer);
return new Promise((resolve, reject) => {
let settled = false;
const names = new Set();
const buffers = new Map();
let total = 0;
const finish = (error, value) => {
if (settled) return;
settled = true;
try { zipfile.close(); } catch {}
error ? reject(error) : resolve(value);
};
zipfile.on("entry", (entry) => {
const size = Number(entry.uncompressedSize) || 0;
if (!safePackageEntry(entry.fileName) || names.has(entry.fileName) || size < 0) {
return finish(new Error("unsafe DOCX package entry"));
}
names.add(entry.fileName);
if (entry.fileName.endsWith('/') || (!(includeAll === true || includeAll instanceof Set && includeAll.has(entry.fileName))
&& !NATIVE_DOCX_PARTS.has(entry.fileName))) return zipfile.readEntry();
if (includeAll instanceof Set && includeAll.has(entry.fileName) && size > 200_000_000) {
return finish(new Error("DOCX image part is too large"));
}
if (size > MAX_NATIVE_DOCX_XML_BYTES) return finish(new Error("DOCX XML part is too large"));
total += size;
if (includeAll instanceof Set && total > 200_000_000) return finish(new Error("DOCX selected images are too large"));
if (total > MAX_NATIVE_DOCX_PACKAGE_BYTES) return finish(new Error("DOCX expanded package is too large"));
zipfile.openReadStream(entry, (error, stream) => {
if (error) return finish(error);
const chunks = [];
let length = 0;
stream.on("data", (chunk) => {
length += chunk.length;
if (length > MAX_NATIVE_DOCX_XML_BYTES) {
stream.destroy(new Error("DOCX document part is too large"));
return;
}
chunks.push(chunk);
});
stream.on("error", finish);
stream.on("end", () => {
if (settled) return;
buffers.set(entry.fileName, Buffer.concat(chunks));
zipfile.readEntry();
});
});
});
zipfile.on("end", () => finish(null, { names, buffers }));
zipfile.on("error", finish);
zipfile.readEntry();
});
}
const OPC_CONTENT_TYPES_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/content-types";
const OPC_RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/relationships";
const WORDPROCESSING_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const DRAWINGML_NAMESPACE = "http://schemas.openxmlformats.org/drawingml/2006/main";
const OFFICE_RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
function qualifiedName(name) {
const separator = name.indexOf(":");
return separator < 0
? { prefix: "", localName: name }
: { prefix: name.slice(0, separator), localName: name.slice(separator + 1) };
}
function namespaceElements(parsed) {
const elements = [];
function visit(name, value, inheritedNamespaces, parentIndex = -1) {
const namespaces = new Map(inheritedNamespaces);
if (value && typeof value === "object" && !Array.isArray(value)) {
for (const [key, declaration] of Object.entries(value)) {
if (key === "@xmlns") namespaces.set("", declaration);
else if (key.startsWith("@xmlns:")) namespaces.set(key.slice(7), declaration);
}
}
const qname = qualifiedName(name);
const attributes = [];
if (value && typeof value === "object" && !Array.isArray(value)) {
for (const [key, attributeValue] of Object.entries(value)) {
if (!key.startsWith("@") || key === "@xmlns" || key.startsWith("@xmlns:")) continue;
const attributeName = qualifiedName(key.slice(1));
attributes.push({
namespaceURI: attributeName.prefix ? namespaces.get(attributeName.prefix) || "" : "",
localName: attributeName.localName,
value: attributeValue
});
}
}
const elementIndex = elements.length;
elements.push({
parentIndex,
namespaceURI: namespaces.get(qname.prefix) || "",
localName: qname.localName,
text: typeof value === "string" ? value : value?.["#text"] || "",
attributes
});
if (!value || typeof value !== "object" || Array.isArray(value)) return;
for (const [childName, childValue] of Object.entries(value)) {
if (childName.startsWith("@") || childName === "#text") continue;
for (const child of Array.isArray(childValue) ? childValue : [childValue]) {
visit(childName, child, namespaces, elementIndex);
}
}
}
for (const [rootName, rootValue] of Object.entries(parsed)) visit(rootName, rootValue, new Map());
return elements;
}
function parseNamespaceDocument(xml) {
const elements = namespaceElements(parseXmlToJson(xml));
if (elements.length === 0) throw nativeDocxInvalid();
return { root: elements[0], elements };
}
function orderedNamespaceElements(xml) {
// The legacy JSON projection groups equal tag names and trims text. Keep it
// unchanged for existing consumers; this projection is only for the narrow
// inline-image writer's exact, ordered content contract.
if (/<!DOCTYPE\b/i.test(xml)) throw nativeDocxInvalid();
const { XMLParser } = require('fast-xml-parser');
// An empty entity map enables numeric XML references without HTML names.
const parsed = new XMLParser({ preserveOrder: true, ignoreAttributes: false,
attributeNamePrefix: '@', trimValues: false, parseTagValue: false,
parseAttributeValue: false, htmlEntities: {}, ignoreDeclaration: true, ignorePiTags: true }).parse(xml);
const elements = [];
function visit(nodes, inheritedNamespaces, parentIndex = -1) {
for (const node of nodes) {
const name = Object.keys(node).find(key => key !== ':@' && key !== '#text');
if (!name) continue;
const namespaces = new Map(inheritedNamespaces), rawAttributes = node[':@'] || {};
for (const [key, value] of Object.entries(rawAttributes)) {
if (key === '@xmlns') namespaces.set('', value);
else if (key.startsWith('@xmlns:')) namespaces.set(key.slice(7), value);
}
const attributes = [];
for (const [key, value] of Object.entries(rawAttributes)) {
if (key === '@xmlns' || key.startsWith('@xmlns:')) continue;
const attribute = qualifiedName(key.slice(1));
attributes.push({ namespaceURI: attribute.prefix ? namespaces.get(attribute.prefix) || '' : '',
localName: attribute.localName, value });
}
const qname = qualifiedName(name), children = node[name], index = elements.length;
if (!Array.isArray(children)) throw nativeDocxInvalid();
elements.push({ parentIndex, namespaceURI: namespaces.get(qname.prefix) || '',
localName: qname.localName, attributes,
text: children.filter(child => Object.hasOwn(child, '#text')).map(child => String(child['#text'])).join('') });
visit(children, namespaces, index);
}
}
visit(parsed, new Map());
return elements;
}
function nativeInlineParagraphs(documentXml, imageHashes) {
const elements = orderedNamespaceElements(documentXml), paragraphs = [], paragraphByIndex = new Map();
const word = (element, name) => element?.namespaceURI === WORDPROCESSING_NAMESPACE && element.localName === name;
elements.forEach((element, index) => {
if (word(element, 'p')) {
let ancestor = elements[element.parentIndex];
while (ancestor && !word(ancestor, 'body')) ancestor = elements[ancestor.parentIndex];
if (ancestor) { const tokens = []; paragraphs.push(tokens); paragraphByIndex.set(index, tokens); }
}
});
for (const element of elements) {
let token;
const parent = elements[element.parentIndex];
if (word(element, 't') && word(parent, 'r')) token = { text: String(element.text) };
else if (word(element, 'tab') && word(parent, 'r')) token = { text: '\t' };
else if ((word(element, 'br') || word(element, 'cr')) && word(parent, 'r')) token = { text: '\n' };
else if (element.namespaceURI === DRAWINGML_NAMESPACE && element.localName === 'blip') {
const hash = imageHashes.get(elementAttribute(element, OFFICE_RELATIONSHIPS_NAMESPACE, 'embed'));
if (!hash) throw nativeDocxInvalid();
token = { imageSha256: hash };
} else continue;
let parentIndex = element.parentIndex;
while (parentIndex >= 0 && !paragraphByIndex.has(parentIndex)) parentIndex = elements[parentIndex].parentIndex;
if (parentIndex < 0) throw nativeDocxInvalid();
const tokens = paragraphByIndex.get(parentIndex);
if (Object.hasOwn(token, 'text') && Object.hasOwn(tokens.at(-1) || {}, 'text')) tokens.at(-1).text += token.text;
else tokens.push(token);
}
// docx inserts empty paragraphs to carry section breaks. Empty body
// paragraphs contain no content tokens and do not affect this contract.
return paragraphs.filter(tokens => tokens.some(token => token.imageSha256 || token.text.length));
}
function inlineParagraphsEqual(actual, expected) {
if (!Array.isArray(expected) || !Array.isArray(actual) || actual.length !== expected.length) return false;
return expected.every((paragraph, index) => Array.isArray(paragraph) && paragraph.length === actual[index].length
&& paragraph.every((token, tokenIndex) => {
const received = actual[index][tokenIndex];
if (!token || typeof token !== 'object' || Object.keys(token).length !== 1) return false;
return typeof token.text === 'string' ? received.text === token.text
: typeof token.imageSha256 === 'string' && /^[a-f0-9]{64}$/.test(token.imageSha256)
&& received.imageSha256 === token.imageSha256;
}));
}
function elementsNamed(elements, namespaceURI, localName) {
return elements.filter((element) =>
element.namespaceURI === namespaceURI && element.localName === localName);
}
function rootNamed(document, namespaceURI, localName) {
return document.root.namespaceURI === namespaceURI && document.root.localName === localName;
}
function elementAttribute(element, namespaceURI, localName) {
return element.attributes.find((attribute) =>
attribute.namespaceURI === namespaceURI && attribute.localName === localName)?.value || "";
}
function nativeDocxInvalid() {
const error = new Error("Native PDF conversion produced an invalid DOCX package.");
error.code = "PDF_OFFICE_OUTPUT_INVALID";
return error;
}
const OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math";
function visibleFractionText(element, elements, children) {
if (element.namespaceURI !== OFFICE_MATH_NAMESPACE || element.localName !== "t") return false;
const run = elements[element.parentIndex];
if (!run || run.namespaceURI !== OFFICE_MATH_NAMESPACE || run.localName !== "r") return false;
const runIndex = element.parentIndex;
const properties = (children.get(runIndex) || []).filter(index => elements[index].namespaceURI === WORDPROCESSING_NAMESPACE
&& elements[index].localName === "rPr");
if (properties.flatMap(index => children.get(index) || []).map(index => elements[index]).some(item => item.namespaceURI === WORDPROCESSING_NAMESPACE
&& (item.localName === "rStyle" || ["vanish", "webHidden", "specVanish"].includes(item.localName)
&& !["0", "false", "off"].includes(String(elementAttribute(item, WORDPROCESSING_NAMESPACE, "val")).toLowerCase())))) return false;
// Only count the supported, visible fraction tree; property text or a
// similarly named foreign element must not satisfy source coverage.
const allowed = new Set(["r", "num", "den", "f"]);
let current = run;
while (current?.namespaceURI === OFFICE_MATH_NAMESPACE && allowed.has(current.localName)) current = elements[current.parentIndex];
if (current?.namespaceURI !== OFFICE_MATH_NAMESPACE || current.localName !== "oMath") return false;
current = elements[current.parentIndex];
if (current?.namespaceURI === OFFICE_MATH_NAMESPACE && current.localName === "oMathPara") current = elements[current.parentIndex];
if (current?.namespaceURI !== WORDPROCESSING_NAMESPACE || current.localName !== "p") return false;
current = elements[current.parentIndex];
if (current?.namespaceURI !== WORDPROCESSING_NAMESPACE || current.localName !== "body") return false;
return true;
}
async function validateNativePdfDocx(outputPath, options = {}) {
try {
const inspected = await inspectNativeDocxPackage(outputPath);
const contentTypes = inspected.buffers.get("[Content_Types].xml")?.toString("utf8");
const rootRelationships = inspected.buffers.get("_rels/.rels")?.toString("utf8");
const documentXml = inspected.buffers.get("word/document.xml")?.toString("utf8");
if (!contentTypes || !rootRelationships || !documentXml) throw nativeDocxInvalid();
const contentTypeDocument = parseNamespaceDocument(contentTypes);
const rootRelationshipDocument = parseNamespaceDocument(rootRelationships);
const wordDocument = parseNamespaceDocument(documentXml);
if (!rootNamed(contentTypeDocument, OPC_CONTENT_TYPES_NAMESPACE, "Types")
|| !rootNamed(rootRelationshipDocument, OPC_RELATIONSHIPS_NAMESPACE, "Relationships")
|| !rootNamed(wordDocument, WORDPROCESSING_NAMESPACE, "document")) {
throw nativeDocxInvalid();
}