@yudaocode/univer-pdfs 1.6.218 → 1.6.219

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.
@@ -296,6 +296,22 @@ var PDF_PAGE_PRESETS = {
296
296
  INVOICE_240_93: { width: mmToPt(240), height: mmToPt(93), preset: "INVOICE_240_93" },
297
297
  CUSTOM: { width: 595.28, height: 841.89, preset: "CUSTOM" }
298
298
  };
299
+ function resolvePdfCropBoxPt(cropBox) {
300
+ if (!cropBox) return null;
301
+ const rawLeft = cropBox.left ?? cropBox.leftPt;
302
+ const rawTop = cropBox.top ?? cropBox.topPt;
303
+ const rawWidth = cropBox.width ?? cropBox.widthPt;
304
+ const rawHeight = cropBox.height ?? cropBox.heightPt;
305
+ if (rawLeft === void 0 && rawTop === void 0 && rawWidth === void 0 && rawHeight === void 0) {
306
+ return null;
307
+ }
308
+ return {
309
+ left: Math.max(0, Number(rawLeft) || 0),
310
+ top: Math.max(0, Number(rawTop) || 0),
311
+ width: Math.max(8, Number(rawWidth) || 8),
312
+ height: Math.max(8, Number(rawHeight) || 8)
313
+ };
314
+ }
299
315
  var PdfElementType = /* @__PURE__ */ ((PdfElementType2) => {
300
316
  PdfElementType2["TEXT"] = "text";
301
317
  PdfElementType2["LIST"] = "list";
@@ -2712,10 +2728,148 @@ function fromPdfmeTemplate(template, options) {
2712
2728
  }
2713
2729
 
2714
2730
  // src/exporter/pdf-exporter.ts
2715
- var import_core3 = require("@univerjs/core");
2731
+ var import_core4 = require("@univerjs/core");
2716
2732
  var import_pdf_lib4 = require("pdf-lib");
2717
2733
  var import_qrcode2 = __toESM(require("qrcode"));
2718
2734
 
2735
+ // src/exporter/pdf-stamps.ts
2736
+ var PDF_STANDARD_STAMP_PRESETS = [
2737
+ {
2738
+ id: "approved",
2739
+ title: "\u5DF2\u6279\u51C6",
2740
+ subtitle: "APPROVED",
2741
+ color: "#16A34A",
2742
+ shape: "rect"
2743
+ },
2744
+ {
2745
+ id: "rejected",
2746
+ title: "\u5DF2\u9A73\u56DE",
2747
+ subtitle: "REJECTED",
2748
+ color: "#DC2626",
2749
+ shape: "rect"
2750
+ },
2751
+ {
2752
+ id: "confidential",
2753
+ title: "\u673A\u5BC6\u6587\u4EF6",
2754
+ subtitle: "CONFIDENTIAL",
2755
+ color: "#B91C1C",
2756
+ shape: "pill"
2757
+ },
2758
+ {
2759
+ id: "draft",
2760
+ title: "\u8349\u7A3F\u4EC5\u4F9B\u53C2\u8003",
2761
+ subtitle: "DRAFT ONLY",
2762
+ color: "#2563EB",
2763
+ shape: "pill"
2764
+ },
2765
+ {
2766
+ id: "reviewed",
2767
+ title: "\u5DF2\u5BA1\u6838",
2768
+ subtitle: "REVIEWED",
2769
+ color: "#0D9488",
2770
+ shape: "rect"
2771
+ },
2772
+ {
2773
+ id: "urgent",
2774
+ title: "\u7279\u6025\u529E\u7406",
2775
+ subtitle: "URGENT",
2776
+ color: "#EA580C",
2777
+ shape: "pill"
2778
+ },
2779
+ {
2780
+ id: "void",
2781
+ title: "\u5DF2\u4F5C\u5E9F",
2782
+ subtitle: "VOID",
2783
+ color: "#64748B",
2784
+ shape: "rect"
2785
+ },
2786
+ {
2787
+ id: "archived",
2788
+ title: "\u5DF2\u5F52\u6863",
2789
+ subtitle: "ARCHIVED",
2790
+ color: "#4F46E5",
2791
+ shape: "circle"
2792
+ }
2793
+ ];
2794
+ var PDF_STANDARD_STAMP_PRESET_MAP = PDF_STANDARD_STAMP_PRESETS.reduce(
2795
+ (acc, item) => {
2796
+ acc[item.id] = item;
2797
+ return acc;
2798
+ },
2799
+ {}
2800
+ );
2801
+ function unescapeXmlEntities(raw) {
2802
+ return raw.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
2803
+ }
2804
+ function extractSvgTextDescriptors(svgXml, boxWidthPt, boxHeightPt) {
2805
+ if (!svgXml || boxWidthPt <= 0 || boxHeightPt <= 0) return [];
2806
+ const vbMatch = /viewBox\s*=\s*["']([^"']+)["']/i.exec(svgXml);
2807
+ let vbX = 0;
2808
+ let vbY = 0;
2809
+ let vbW = boxWidthPt;
2810
+ let vbH = boxHeightPt;
2811
+ if (vbMatch) {
2812
+ const nums = vbMatch[1].trim().split(/[\s,]+/).map(Number);
2813
+ if (nums.length >= 4 && nums[2] > 0 && nums[3] > 0) {
2814
+ vbX = nums[0];
2815
+ vbY = nums[1];
2816
+ vbW = nums[2];
2817
+ vbH = nums[3];
2818
+ }
2819
+ }
2820
+ const scale = Math.min(boxWidthPt / vbW, boxHeightPt / vbH);
2821
+ const offsetX = (boxWidthPt - vbW * scale) / 2 - vbX * scale;
2822
+ const offsetY = (boxHeightPt - vbH * scale) / 2 - vbY * scale;
2823
+ const out = [];
2824
+ const textRe = /<text\b([^>]*)>([\s\S]*?)<\/text>/gi;
2825
+ let m;
2826
+ while ((m = textRe.exec(svgXml)) !== null) {
2827
+ const attrStr = m[1] ?? "";
2828
+ const inner = unescapeXmlEntities((m[2] ?? "").replace(/<[^>]+>/g, "").trim());
2829
+ if (!inner) continue;
2830
+ const getAttr = (name) => {
2831
+ const re = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i");
2832
+ const hit = re.exec(attrStr);
2833
+ return hit ? hit[1] ?? hit[2] : void 0;
2834
+ };
2835
+ const rawX = parseFloat(getAttr("x") ?? "0") || 0;
2836
+ const rawY = parseFloat(getAttr("y") ?? "0") || 0;
2837
+ const rawFs = parseFloat(getAttr("font-size") ?? "12") || 12;
2838
+ const anchor = (getAttr("text-anchor") ?? "start").toLowerCase();
2839
+ const weight = (getAttr("font-weight") ?? "normal").toLowerCase();
2840
+ const fill = getAttr("fill") ?? "#1B1C1F";
2841
+ const fontSizePt = Math.max(5, Math.round(rawFs * scale * 100) / 100);
2842
+ const xPt = offsetX + rawX * scale;
2843
+ const baselineYPt = offsetY + rawY * scale;
2844
+ const heightPt = Math.max(fontSizePt * 1.35, 8);
2845
+ const topPt = Math.max(0, baselineYPt - fontSizePt * 0.88);
2846
+ let align = "left";
2847
+ let leftPt = xPt;
2848
+ let widthPt = Math.max(24, boxWidthPt - xPt);
2849
+ if (anchor === "middle") {
2850
+ align = "center";
2851
+ widthPt = boxWidthPt;
2852
+ leftPt = 0;
2853
+ } else if (anchor === "end") {
2854
+ align = "right";
2855
+ widthPt = Math.max(24, xPt);
2856
+ leftPt = 0;
2857
+ }
2858
+ out.push({
2859
+ text: inner,
2860
+ leftPt,
2861
+ topPt,
2862
+ widthPt,
2863
+ heightPt,
2864
+ fontSizePt,
2865
+ bold: weight === "bold" || Number(weight) >= 600,
2866
+ color: fill,
2867
+ align
2868
+ });
2869
+ }
2870
+ return out;
2871
+ }
2872
+
2719
2873
  // src/exporter/pdf-2d-barcodes.ts
2720
2874
  function collapseRowToRuns(row) {
2721
2875
  const runs = [];
@@ -4187,1705 +4341,1708 @@ function encodeBarcodeByFormat(format, raw) {
4187
4341
  }
4188
4342
 
4189
4343
  // src/exporter/pdf-native-text.ts
4344
+ var import_core3 = require("@univerjs/core");
4345
+ var import_pdf_lib2 = require("pdf-lib");
4346
+
4347
+ // src/exporter/pdf-security.ts
4190
4348
  var import_pdf_lib = require("pdf-lib");
4191
- var WIN_ANSI_EXTENDED = {
4192
- 128: 8364,
4193
- 130: 8218,
4194
- 131: 402,
4195
- 132: 8222,
4196
- 133: 8230,
4197
- 134: 8224,
4198
- 135: 8225,
4199
- 136: 710,
4200
- 137: 8240,
4201
- 138: 352,
4202
- 139: 8249,
4203
- 140: 338,
4204
- 142: 381,
4205
- 145: 8216,
4206
- 146: 8217,
4207
- 147: 8220,
4208
- 148: 8221,
4209
- 149: 8226,
4210
- 150: 8211,
4211
- 151: 8212,
4212
- 152: 732,
4213
- 153: 8482,
4214
- 154: 353,
4215
- 155: 8250,
4216
- 156: 339,
4217
- 158: 382,
4218
- 159: 376
4349
+ var PdfSecurityError = class extends Error {
4350
+ constructor(code, message) {
4351
+ super(message);
4352
+ this.name = "PdfSecurityError";
4353
+ this.code = code;
4354
+ }
4219
4355
  };
4220
- function multiplyPdfMatrix(m1, m2) {
4221
- return [
4222
- m1[0] * m2[0] + m1[1] * m2[2],
4223
- m1[0] * m2[1] + m1[1] * m2[3],
4224
- m1[2] * m2[0] + m1[3] * m2[2],
4225
- m1[2] * m2[1] + m1[3] * m2[3],
4226
- m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
4227
- m1[4] * m2[1] + m1[5] * m2[3] + m2[5]
4228
- ];
4229
- }
4230
- function decodeSingleStreamObject(doc, objOrRef) {
4231
- const resolved = objOrRef instanceof import_pdf_lib.PDFRef ? doc.context.lookup(objOrRef) : objOrRef;
4232
- if (!resolved) return new Uint8Array(0);
4233
- if (resolved instanceof import_pdf_lib.PDFRawStream) {
4234
- try {
4235
- const decoded = (0, import_pdf_lib.decodePDFRawStream)(resolved).decode();
4236
- return decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded);
4237
- } catch {
4238
- return resolved.contents;
4239
- }
4356
+ var PDF_PASSWORD_PADDING = new Uint8Array([
4357
+ 40,
4358
+ 191,
4359
+ 78,
4360
+ 94,
4361
+ 78,
4362
+ 117,
4363
+ 138,
4364
+ 65,
4365
+ 100,
4366
+ 0,
4367
+ 78,
4368
+ 86,
4369
+ 255,
4370
+ 250,
4371
+ 1,
4372
+ 8,
4373
+ 46,
4374
+ 46,
4375
+ 0,
4376
+ 182,
4377
+ 208,
4378
+ 104,
4379
+ 62,
4380
+ 128,
4381
+ 47,
4382
+ 12,
4383
+ 169,
4384
+ 254,
4385
+ 100,
4386
+ 83,
4387
+ 105,
4388
+ 122
4389
+ ]);
4390
+ var DEFAULT_ALL_PERMISSIONS = Object.freeze({
4391
+ print: true,
4392
+ highResPrint: true,
4393
+ modify: true,
4394
+ copy: true,
4395
+ annotate: true,
4396
+ fillForms: true,
4397
+ assemble: true
4398
+ });
4399
+ var MD5_SHIFTS = [
4400
+ 7,
4401
+ 12,
4402
+ 17,
4403
+ 22,
4404
+ 7,
4405
+ 12,
4406
+ 17,
4407
+ 22,
4408
+ 7,
4409
+ 12,
4410
+ 17,
4411
+ 22,
4412
+ 7,
4413
+ 12,
4414
+ 17,
4415
+ 22,
4416
+ 5,
4417
+ 9,
4418
+ 14,
4419
+ 20,
4420
+ 5,
4421
+ 9,
4422
+ 14,
4423
+ 20,
4424
+ 5,
4425
+ 9,
4426
+ 14,
4427
+ 20,
4428
+ 5,
4429
+ 9,
4430
+ 14,
4431
+ 20,
4432
+ 4,
4433
+ 11,
4434
+ 16,
4435
+ 23,
4436
+ 4,
4437
+ 11,
4438
+ 16,
4439
+ 23,
4440
+ 4,
4441
+ 11,
4442
+ 16,
4443
+ 23,
4444
+ 4,
4445
+ 11,
4446
+ 16,
4447
+ 23,
4448
+ 6,
4449
+ 10,
4450
+ 15,
4451
+ 21,
4452
+ 6,
4453
+ 10,
4454
+ 15,
4455
+ 21,
4456
+ 6,
4457
+ 10,
4458
+ 15,
4459
+ 21,
4460
+ 6,
4461
+ 10,
4462
+ 15,
4463
+ 21
4464
+ ];
4465
+ var MD5_K = (() => {
4466
+ const table = new Uint32Array(64);
4467
+ for (let i = 0; i < 64; i++) {
4468
+ table[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
4240
4469
  }
4241
- if (resolved instanceof import_pdf_lib.PDFStream) {
4242
- const anyStream = resolved;
4243
- if (typeof anyStream.getUnencodedContents === "function") {
4244
- return anyStream.getUnencodedContents();
4470
+ return table;
4471
+ })();
4472
+ function rotl32(x, n) {
4473
+ return (x << n | x >>> 32 - n) >>> 0;
4474
+ }
4475
+ function md5Bytes(data) {
4476
+ const msgLen = data.byteLength;
4477
+ const rem = (msgLen + 9) % 64;
4478
+ const padZeroes = rem === 0 ? 0 : 64 - rem;
4479
+ const totalLen = msgLen + 9 + padZeroes;
4480
+ const buf = new Uint8Array(totalLen);
4481
+ buf.set(data, 0);
4482
+ buf[msgLen] = 128;
4483
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
4484
+ const bitLenLow = msgLen * 8 >>> 0;
4485
+ const bitLenHigh = Math.floor(msgLen * 8 / 4294967296) >>> 0;
4486
+ view.setUint32(totalLen - 8, bitLenLow, true);
4487
+ view.setUint32(totalLen - 4, bitLenHigh, true);
4488
+ let a0 = 1732584193;
4489
+ let b0 = 4023233417;
4490
+ let c0 = 2562383102;
4491
+ let d0 = 271733878;
4492
+ const M = new Uint32Array(16);
4493
+ for (let offset = 0; offset < totalLen; offset += 64) {
4494
+ for (let j = 0; j < 16; j++) {
4495
+ M[j] = view.getUint32(offset + j * 4, true);
4245
4496
  }
4246
- if (typeof anyStream.getContents === "function") {
4247
- return anyStream.getContents();
4497
+ let A = a0;
4498
+ let B = b0;
4499
+ let C = c0;
4500
+ let D = d0;
4501
+ for (let i = 0; i < 64; i++) {
4502
+ let F;
4503
+ let g;
4504
+ if (i < 16) {
4505
+ F = B & C | ~B & D;
4506
+ g = i;
4507
+ } else if (i < 32) {
4508
+ F = D & B | ~D & C;
4509
+ g = (5 * i + 1) % 16;
4510
+ } else if (i < 48) {
4511
+ F = B ^ C ^ D;
4512
+ g = (3 * i + 5) % 16;
4513
+ } else {
4514
+ F = C ^ (B | ~D);
4515
+ g = 7 * i % 16;
4516
+ }
4517
+ const sum = A + F + MD5_K[i] + M[g] >>> 0;
4518
+ A = D;
4519
+ D = C;
4520
+ C = B;
4521
+ B = B + rotl32(sum, MD5_SHIFTS[i]) >>> 0;
4248
4522
  }
4523
+ a0 = a0 + A >>> 0;
4524
+ b0 = b0 + B >>> 0;
4525
+ c0 = c0 + C >>> 0;
4526
+ d0 = d0 + D >>> 0;
4249
4527
  }
4250
- return new Uint8Array(0);
4528
+ const out = new Uint8Array(16);
4529
+ const outView = new DataView(out.buffer);
4530
+ outView.setUint32(0, a0, true);
4531
+ outView.setUint32(4, b0, true);
4532
+ outView.setUint32(8, c0, true);
4533
+ outView.setUint32(12, d0, true);
4534
+ return out;
4251
4535
  }
4252
- function decodeContentsEntry(doc, contentsEntry) {
4253
- const resolved = contentsEntry instanceof import_pdf_lib.PDFRef ? doc.context.lookup(contentsEntry) : contentsEntry;
4254
- if (!resolved) return new Uint8Array(0);
4255
- if (resolved instanceof import_pdf_lib.PDFArray) {
4256
- const parts = [];
4257
- let total = 0;
4258
- for (let i = 0; i < resolved.size(); i++) {
4259
- const part = decodeSingleStreamObject(doc, resolved.get(i));
4260
- if (part.byteLength > 0) {
4261
- parts.push(part);
4262
- total += part.byteLength + 1;
4263
- }
4264
- }
4265
- const merged = new Uint8Array(total);
4266
- let offset = 0;
4267
- for (const part of parts) {
4268
- merged.set(part, offset);
4269
- offset += part.byteLength;
4270
- merged[offset++] = 10;
4271
- }
4272
- return merged;
4536
+ function rc4Bytes(key, data) {
4537
+ const keyLen = key.byteLength;
4538
+ if (keyLen === 0) return data.slice();
4539
+ const S = new Uint8Array(256);
4540
+ for (let i2 = 0; i2 < 256; i2++) {
4541
+ S[i2] = i2;
4273
4542
  }
4274
- return decodeSingleStreamObject(doc, resolved);
4275
- }
4276
- function bytesToLatin1String(bytes) {
4277
- let out = "";
4278
- const chunk = 16384;
4279
- for (let i = 0; i < bytes.length; i += chunk) {
4280
- out += String.fromCharCode(...bytes.subarray(i, i + chunk));
4543
+ let j = 0;
4544
+ for (let i2 = 0; i2 < 256; i2++) {
4545
+ j = j + S[i2] + key[i2 % keyLen] & 255;
4546
+ const tmp = S[i2];
4547
+ S[i2] = S[j];
4548
+ S[j] = tmp;
4549
+ }
4550
+ const out = new Uint8Array(data.byteLength);
4551
+ let i = 0;
4552
+ j = 0;
4553
+ for (let k = 0; k < data.byteLength; k++) {
4554
+ i = i + 1 & 255;
4555
+ j = j + S[i] & 255;
4556
+ const tmp = S[i];
4557
+ S[i] = S[j];
4558
+ S[j] = tmp;
4559
+ out[k] = data[k] ^ S[S[i] + S[j] & 255];
4281
4560
  }
4282
4561
  return out;
4283
4562
  }
4284
- function decodeUtf16BeHex(hex) {
4285
- const cleaned = hex.replace(/\s+/g, "");
4286
- if (!cleaned) return "";
4287
- if (cleaned.length <= 2) {
4288
- return String.fromCodePoint(parseInt(cleaned, 16) || 32);
4563
+ function bytesToHex(bytes) {
4564
+ let hex = "";
4565
+ for (let i = 0; i < bytes.byteLength; i++) {
4566
+ hex += bytes[i].toString(16).padStart(2, "0").toUpperCase();
4289
4567
  }
4290
- const codeUnits = [];
4291
- for (let i = 0; i + 3 < cleaned.length; i += 4) {
4292
- codeUnits.push(parseInt(cleaned.slice(i, i + 4), 16));
4568
+ return hex;
4569
+ }
4570
+ function hexToBytes(hexRaw) {
4571
+ const cleaned = hexRaw.replace(/\s+/g, "");
4572
+ const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
4573
+ const out = new Uint8Array(padded.length / 2);
4574
+ for (let i = 0; i < out.byteLength; i++) {
4575
+ out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16) || 0;
4293
4576
  }
4294
- return String.fromCharCode(...codeUnits);
4577
+ return out;
4295
4578
  }
4296
- function parseToUnicodeCMap(cmapText) {
4297
- const map = /* @__PURE__ */ new Map();
4298
- let bytesPerCode = 1;
4299
- const bfCharRe = /beginbfchar([\s\S]*?)endbfchar/g;
4300
- let blockMatch;
4301
- while ((blockMatch = bfCharRe.exec(cmapText)) !== null) {
4302
- const body = blockMatch[1];
4303
- const pairRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
4304
- let m;
4305
- while ((m = pairRe.exec(body)) !== null) {
4306
- if (m[1].length >= 4) bytesPerCode = 2;
4307
- const srcCode = parseInt(m[1], 16);
4308
- const dstStr = decodeUtf16BeHex(m[2]);
4309
- if (!Number.isNaN(srcCode) && dstStr) {
4310
- map.set(srcCode, dstStr);
4311
- }
4579
+ function encodePasswordToBytes(password) {
4580
+ if (!password) return new Uint8Array(0);
4581
+ let hasHighCodePoint = false;
4582
+ for (let i = 0; i < password.length; i++) {
4583
+ if (password.charCodeAt(i) > 255) {
4584
+ hasHighCodePoint = true;
4585
+ break;
4312
4586
  }
4313
4587
  }
4314
- const bfRangeRe = /beginbfrange([\s\S]*?)endbfrange/g;
4315
- while ((blockMatch = bfRangeRe.exec(cmapText)) !== null) {
4316
- const body = blockMatch[1];
4317
- const arrayRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([^\]]*)\]/g;
4318
- let am;
4319
- while ((am = arrayRangeRe.exec(body)) !== null) {
4320
- if (am[1].length >= 4) bytesPerCode = 2;
4321
- const start = parseInt(am[1], 16);
4322
- const end = parseInt(am[2], 16);
4323
- const targets = Array.from(am[3].matchAll(/<([0-9A-Fa-f]+)>/g)).map((x) => decodeUtf16BeHex(x[1]));
4324
- for (let code = start; code <= end && code - start < targets.length; code++) {
4325
- if (targets[code - start]) {
4326
- map.set(code, targets[code - start]);
4327
- }
4328
- }
4329
- }
4330
- const directRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
4331
- let dm;
4332
- while ((dm = directRangeRe.exec(body)) !== null) {
4333
- if (dm[1].length >= 4) bytesPerCode = 2;
4334
- const start = parseInt(dm[1], 16);
4335
- const end = parseInt(dm[2], 16);
4336
- const baseStr = decodeUtf16BeHex(dm[3]);
4337
- const baseCp = baseStr.codePointAt(0) ?? 32;
4338
- if (end >= start && end - start <= 16384) {
4339
- for (let code = start; code <= end; code++) {
4340
- map.set(code, String.fromCodePoint(baseCp + (code - start)));
4341
- }
4342
- }
4343
- }
4588
+ if (hasHighCodePoint) {
4589
+ return new TextEncoder().encode(password);
4344
4590
  }
4345
- return { map, bytesPerCode };
4346
- }
4347
- function extractResourcesFontMap(doc, resourcesDict) {
4348
- const fonts = /* @__PURE__ */ new Map();
4349
- if (!resourcesDict) return fonts;
4350
- const fontObj = resourcesDict.get(import_pdf_lib.PDFName.of("Font"));
4351
- const fontDict = doc.context.lookupMaybe(fontObj, import_pdf_lib.PDFDict);
4352
- if (!fontDict) return fonts;
4353
- for (const [keyObj, valObj] of fontDict.entries()) {
4354
- const cleanKey = keyObj.decodeText ? keyObj.decodeText() : keyObj.asString().replace(/^\//, "");
4355
- const fDict = doc.context.lookupMaybe(valObj, import_pdf_lib.PDFDict);
4356
- if (!fDict) continue;
4357
- const subtypeObj = fDict.get(import_pdf_lib.PDFName.of("Subtype"));
4358
- const subtype = subtypeObj instanceof import_pdf_lib.PDFName ? subtypeObj.decodeText() : "";
4359
- const encObj = fDict.get(import_pdf_lib.PDFName.of("Encoding"));
4360
- const encoding = encObj instanceof import_pdf_lib.PDFName ? encObj.decodeText() : "";
4361
- const isUtf16Cid = /UTF16|UCS2/i.test(encoding);
4362
- let toUnicode = /* @__PURE__ */ new Map();
4363
- let bytesPerCode = subtype === "Type0" ? 2 : 1;
4364
- const toUniEntry = fDict.get(import_pdf_lib.PDFName.of("ToUnicode"));
4365
- if (toUniEntry) {
4366
- const cmapBytes = decodeSingleStreamObject(doc, toUniEntry);
4367
- if (cmapBytes.byteLength > 0) {
4368
- const parsed = parseToUnicodeCMap(bytesToLatin1String(cmapBytes));
4369
- toUnicode = parsed.map;
4370
- if (parsed.bytesPerCode === 2 || subtype === "Type0") {
4371
- bytesPerCode = 2;
4372
- }
4373
- }
4374
- }
4375
- fonts.set(cleanKey, {
4376
- subtype,
4377
- encoding,
4378
- isUtf16Cid,
4379
- bytesPerCode,
4380
- toUnicode
4381
- });
4591
+ const out = new Uint8Array(password.length);
4592
+ for (let i = 0; i < password.length; i++) {
4593
+ out[i] = password.charCodeAt(i) & 255;
4382
4594
  }
4383
- return fonts;
4595
+ return out;
4384
4596
  }
4385
- function decodeWinAnsiBytes(bytes) {
4386
- let out = "";
4387
- for (let i = 0; i < bytes.length; i++) {
4388
- const b = bytes[i];
4389
- if (b in WIN_ANSI_EXTENDED) {
4390
- out += String.fromCharCode(WIN_ANSI_EXTENDED[b]);
4391
- } else if (b >= 32 || b === 9 || b === 10 || b === 13) {
4392
- out += String.fromCharCode(b);
4393
- }
4597
+ function padPdfPassword(password) {
4598
+ const raw = password instanceof Uint8Array ? password : encodePasswordToBytes(password);
4599
+ const out = new Uint8Array(32);
4600
+ const copyLen = Math.min(32, raw.byteLength);
4601
+ out.set(raw.subarray(0, copyLen), 0);
4602
+ if (copyLen < 32) {
4603
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 32 - copyLen), copyLen);
4394
4604
  }
4395
4605
  return out;
4396
4606
  }
4397
- function decodeUtf16BeBytes(bytes, startOffset = 0) {
4398
- const units = [];
4399
- for (let i = startOffset; i + 1 < bytes.length; i += 2) {
4400
- const u = bytes[i] << 8 | bytes[i + 1];
4401
- if (u !== 65279 && u > 0) {
4402
- units.push(u);
4403
- }
4607
+ function encodePdfPermissionFlags(permissions, revision = 3) {
4608
+ const allowPrint = permissions?.print !== false;
4609
+ const allowModify = permissions?.modify !== false;
4610
+ const allowCopy = permissions?.copy !== false;
4611
+ const allowAnnotate = permissions?.annotate !== false;
4612
+ const allowFillForms = permissions?.fillForms !== false;
4613
+ const allowAssemble = permissions?.assemble !== false;
4614
+ const allowHighResPrint = permissions?.highResPrint !== void 0 ? Boolean(permissions.highResPrint) : allowPrint;
4615
+ let mask = 4294963392 | 1 << 9;
4616
+ if (allowPrint) mask |= 1 << 2;
4617
+ if (allowModify) mask |= 1 << 3;
4618
+ if (allowCopy) mask |= 1 << 4;
4619
+ if (allowAnnotate) mask |= 1 << 5;
4620
+ if (revision >= 3) {
4621
+ if (allowFillForms) mask |= 1 << 8;
4622
+ if (allowAssemble) mask |= 1 << 10;
4623
+ if (allowHighResPrint && allowPrint) mask |= 1 << 11;
4624
+ } else {
4625
+ mask |= 1 << 8 | 1 << 10 | 1 << 11;
4404
4626
  }
4405
- return String.fromCharCode(...units);
4627
+ return mask | 0;
4406
4628
  }
4407
- function decodePdfStringBytes(bytes, fontInfo) {
4408
- if (bytes.length === 0) return { text: "", glyphCount: 0 };
4409
- if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) {
4410
- const text2 = decodeUtf16BeBytes(bytes, 2);
4411
- return { text: text2, glyphCount: text2.length };
4629
+ function decodePdfPermissionFlags(pMask, revision = 3) {
4630
+ const print = (pMask & 1 << 2) !== 0;
4631
+ const modify = (pMask & 1 << 3) !== 0;
4632
+ const copy = (pMask & 1 << 4) !== 0;
4633
+ const annotate = (pMask & 1 << 5) !== 0;
4634
+ const fillForms = revision >= 3 ? (pMask & 1 << 8) !== 0 : annotate;
4635
+ const assemble = revision >= 3 ? (pMask & 1 << 10) !== 0 : modify;
4636
+ const highResPrint = revision >= 3 ? print && (pMask & 1 << 11) !== 0 : print;
4637
+ return {
4638
+ print,
4639
+ highResPrint,
4640
+ modify,
4641
+ copy,
4642
+ annotate,
4643
+ fillForms,
4644
+ assemble
4645
+ };
4646
+ }
4647
+ function isPdfSecurityActive(security) {
4648
+ if (!security || security.enabled === false) return false;
4649
+ if (security.enabled === true) return true;
4650
+ if (security.userPassword && security.userPassword.length > 0) return true;
4651
+ if (security.ownerPassword && security.ownerPassword.length > 0) return true;
4652
+ if (security.permissions && Object.keys(security.permissions).length > 0) return true;
4653
+ return false;
4654
+ }
4655
+ function computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLengthBits) {
4656
+ const effectiveOwner = ownerPassword || userPassword || "";
4657
+ const ownerPad = padPdfPassword(effectiveOwner);
4658
+ let hash = md5Bytes(ownerPad);
4659
+ if (revision >= 3) {
4660
+ for (let i = 0; i < 50; i++) {
4661
+ hash = md5Bytes(hash);
4662
+ }
4412
4663
  }
4413
- if (fontInfo && fontInfo.toUnicode.size > 0) {
4414
- if (fontInfo.bytesPerCode === 2 && bytes.length >= 2) {
4415
- let out2 = "";
4416
- let count = 0;
4417
- for (let i = 0; i + 1 < bytes.length; i += 2) {
4418
- const code = bytes[i] << 8 | bytes[i + 1];
4419
- count++;
4420
- const mapped = fontInfo.toUnicode.get(code);
4421
- if (mapped !== void 0) {
4422
- out2 += mapped;
4423
- } else if (code >= 32 && code !== 65279) {
4424
- out2 += String.fromCharCode(code);
4425
- }
4664
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
4665
+ const userPad = padPdfPassword(userPassword);
4666
+ let encrypted = rc4Bytes(hash.subarray(0, keyByteLen), userPad);
4667
+ if (revision >= 3) {
4668
+ const derivedKey = new Uint8Array(keyByteLen);
4669
+ for (let iter = 1; iter <= 19; iter++) {
4670
+ for (let k = 0; k < keyByteLen; k++) {
4671
+ derivedKey[k] = hash[k] ^ iter;
4426
4672
  }
4427
- return { text: out2, glyphCount: count };
4673
+ encrypted = rc4Bytes(derivedKey, encrypted);
4428
4674
  }
4429
- let out = "";
4430
- for (let i = 0; i < bytes.length; i++) {
4431
- const code = bytes[i];
4432
- const mapped = fontInfo.toUnicode.get(code);
4433
- if (mapped !== void 0) {
4434
- out += mapped;
4435
- } else if (code in WIN_ANSI_EXTENDED) {
4436
- out += String.fromCharCode(WIN_ANSI_EXTENDED[code]);
4437
- } else if (code >= 32) {
4438
- out += String.fromCharCode(code);
4439
- }
4675
+ }
4676
+ return encrypted;
4677
+ }
4678
+ function computeFileEncryptionKeyFromPadded(paddedUserPassword, oValue, pFlagsSigned, fileId, revision, keyLengthBits) {
4679
+ const buf = new Uint8Array(32 + oValue.byteLength + 4 + fileId.byteLength);
4680
+ let offset = 0;
4681
+ buf.set(paddedUserPassword.subarray(0, 32), offset);
4682
+ offset += 32;
4683
+ buf.set(oValue, offset);
4684
+ offset += oValue.byteLength;
4685
+ buf[offset++] = pFlagsSigned & 255;
4686
+ buf[offset++] = pFlagsSigned >>> 8 & 255;
4687
+ buf[offset++] = pFlagsSigned >>> 16 & 255;
4688
+ buf[offset++] = pFlagsSigned >>> 24 & 255;
4689
+ buf.set(fileId, offset);
4690
+ let hash = md5Bytes(buf);
4691
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
4692
+ if (revision >= 3) {
4693
+ for (let i = 0; i < 50; i++) {
4694
+ hash = md5Bytes(hash.subarray(0, keyByteLen));
4440
4695
  }
4441
- return { text: out, glyphCount: bytes.length };
4442
4696
  }
4443
- if (fontInfo?.isUtf16Cid || fontInfo?.subtype === "Type0" && bytes.length % 2 === 0) {
4444
- const text2 = decodeUtf16BeBytes(bytes, 0);
4445
- return { text: text2, glyphCount: Math.floor(bytes.length / 2) };
4697
+ return hash.subarray(0, keyByteLen);
4698
+ }
4699
+ function computeUserPasswordValue(encryptionKey, fileId, revision) {
4700
+ if (revision === 2) {
4701
+ return rc4Bytes(encryptionKey, PDF_PASSWORD_PADDING);
4446
4702
  }
4447
- const text = decodeWinAnsiBytes(bytes);
4448
- return { text, glyphCount: bytes.length };
4703
+ const hashInput = new Uint8Array(32 + fileId.byteLength);
4704
+ hashInput.set(PDF_PASSWORD_PADDING, 0);
4705
+ hashInput.set(fileId, 32);
4706
+ let check = rc4Bytes(encryptionKey, md5Bytes(hashInput));
4707
+ const keyLen = encryptionKey.byteLength;
4708
+ const derivedKey = new Uint8Array(keyLen);
4709
+ for (let iter = 1; iter <= 19; iter++) {
4710
+ for (let k = 0; k < keyLen; k++) {
4711
+ derivedKey[k] = encryptionKey[k] ^ iter;
4712
+ }
4713
+ check = rc4Bytes(derivedKey, check);
4714
+ }
4715
+ const out = new Uint8Array(32);
4716
+ out.set(check.subarray(0, 16), 0);
4717
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 16), 16);
4718
+ return out;
4449
4719
  }
4450
- function isPdfWhitespace(ch) {
4451
- return ch === 0 || ch === 9 || ch === 10 || ch === 12 || ch === 13 || ch === 32;
4720
+ function authenticatePaddedUserPassword(paddedPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
4721
+ const candidateKey = computeFileEncryptionKeyFromPadded(
4722
+ paddedPassword,
4723
+ oValue,
4724
+ pFlagsSigned,
4725
+ fileId,
4726
+ revision,
4727
+ keyLengthBits
4728
+ );
4729
+ const expectedU = computeUserPasswordValue(candidateKey, fileId, revision);
4730
+ const compareLen = revision >= 3 ? 16 : 32;
4731
+ if (uValue.byteLength < compareLen) return null;
4732
+ let diff = 0;
4733
+ for (let i = 0; i < compareLen; i++) {
4734
+ diff |= expectedU[i] ^ uValue[i];
4735
+ }
4736
+ return diff === 0 ? candidateKey : null;
4452
4737
  }
4453
- function isPdfDelimiter(ch) {
4454
- return ch === 40 || // (
4455
- ch === 41 || // )
4456
- ch === 60 || // <
4457
- ch === 62 || // >
4458
- ch === 91 || // [
4459
- ch === 93 || // ]
4460
- ch === 123 || // {
4461
- ch === 125 || // }
4462
- ch === 47 || // /
4463
- ch === 37;
4738
+ function authenticateOwnerPassword(ownerPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
4739
+ const ownerPad = padPdfPassword(ownerPassword);
4740
+ let hash = md5Bytes(ownerPad);
4741
+ if (revision >= 3) {
4742
+ for (let i = 0; i < 50; i++) {
4743
+ hash = md5Bytes(hash);
4744
+ }
4745
+ }
4746
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
4747
+ let recoveredUserPad;
4748
+ if (revision >= 3) {
4749
+ recoveredUserPad = oValue.slice(0, 32);
4750
+ const derivedKey = new Uint8Array(keyByteLen);
4751
+ for (let iter = 19; iter >= 0; iter--) {
4752
+ for (let k = 0; k < keyByteLen; k++) {
4753
+ derivedKey[k] = hash[k] ^ iter;
4754
+ }
4755
+ recoveredUserPad = rc4Bytes(derivedKey, recoveredUserPad);
4756
+ }
4757
+ } else {
4758
+ recoveredUserPad = rc4Bytes(hash.subarray(0, 5), oValue.subarray(0, 32));
4759
+ }
4760
+ return authenticatePaddedUserPassword(
4761
+ recoveredUserPad,
4762
+ oValue,
4763
+ uValue,
4764
+ pFlagsSigned,
4765
+ fileId,
4766
+ revision,
4767
+ keyLengthBits
4768
+ );
4464
4769
  }
4465
- function hexCharVal(c) {
4466
- if (c >= 48 && c <= 57) return c - 48;
4467
- if (c >= 65 && c <= 70) return c - 65 + 10;
4468
- if (c >= 97 && c <= 102) return c - 97 + 10;
4469
- return -1;
4770
+ function buildObjectEncryptionKey(encryptionKey, objectNumber, generationNumber) {
4771
+ const n = encryptionKey.byteLength;
4772
+ const buf = new Uint8Array(n + 5);
4773
+ buf.set(encryptionKey, 0);
4774
+ buf[n] = objectNumber & 255;
4775
+ buf[n + 1] = objectNumber >>> 8 & 255;
4776
+ buf[n + 2] = objectNumber >>> 16 & 255;
4777
+ buf[n + 3] = generationNumber & 255;
4778
+ buf[n + 4] = generationNumber >>> 8 & 255;
4779
+ const digest = md5Bytes(buf);
4780
+ return digest.subarray(0, Math.min(n + 5, 16));
4470
4781
  }
4471
- function tokenizeContentStream(bytes) {
4472
- const len = bytes.length;
4473
- let pos = 0;
4474
- const readToken = () => {
4475
- while (pos < len) {
4476
- const c = bytes[pos];
4477
- if (isPdfWhitespace(c)) {
4478
- pos++;
4479
- continue;
4480
- }
4481
- if (c === 37) {
4482
- while (pos < len && bytes[pos] !== 10 && bytes[pos] !== 13) {
4483
- pos++;
4484
- }
4485
- continue;
4486
- }
4487
- break;
4782
+ function decodePdfLiteralBodyBytes(body) {
4783
+ const bytes = [];
4784
+ for (let i = 0; i < body.length; i++) {
4785
+ const ch = body.charCodeAt(i) & 255;
4786
+ if (ch !== 92) {
4787
+ bytes.push(ch);
4788
+ continue;
4488
4789
  }
4489
- if (pos >= len) return null;
4490
- const start = pos;
4491
- const ch = bytes[pos];
4492
- if (ch === 40) {
4493
- pos++;
4494
- let depth = 1;
4495
- const out = [];
4496
- while (pos < len && depth > 0) {
4497
- const b = bytes[pos++];
4498
- if (b === 92) {
4499
- if (pos >= len) break;
4500
- const next = bytes[pos++];
4501
- if (next === 110) out.push(10);
4502
- else if (next === 114) out.push(13);
4503
- else if (next === 116) out.push(9);
4504
- else if (next === 98) out.push(8);
4505
- else if (next === 102) out.push(12);
4506
- else if (next === 40 || next === 41 || next === 92) out.push(next);
4507
- else if (next === 13) {
4508
- if (pos < len && bytes[pos] === 10) pos++;
4509
- } else if (next === 10) {
4510
- } else if (next >= 48 && next <= 55) {
4511
- let oct = next - 48;
4512
- for (let k = 0; k < 2 && pos < len && bytes[pos] >= 48 && bytes[pos] <= 55; k++) {
4513
- oct = (oct << 3) + (bytes[pos++] - 48);
4514
- }
4515
- out.push(oct & 255);
4516
- } else {
4517
- out.push(next);
4518
- }
4519
- } else if (b === 40) {
4520
- depth++;
4521
- out.push(b);
4522
- } else if (b === 41) {
4523
- depth--;
4524
- if (depth > 0) out.push(b);
4790
+ if (i + 1 >= body.length) break;
4791
+ const next = body.charCodeAt(++i) & 255;
4792
+ if (next === 13) {
4793
+ if (i + 1 < body.length && (body.charCodeAt(i + 1) & 255) === 10) i++;
4794
+ } else if (next === 10) {
4795
+ } else if (next === 110) {
4796
+ bytes.push(10);
4797
+ } else if (next === 114) {
4798
+ bytes.push(13);
4799
+ } else if (next === 116) {
4800
+ bytes.push(9);
4801
+ } else if (next === 98) {
4802
+ bytes.push(8);
4803
+ } else if (next === 102) {
4804
+ bytes.push(12);
4805
+ } else if (next >= 48 && next <= 55) {
4806
+ let oct = String.fromCharCode(next);
4807
+ for (let k = 0; k < 2 && i + 1 < body.length; k++) {
4808
+ const peek = body.charCodeAt(i + 1) & 255;
4809
+ if (peek >= 48 && peek <= 55) {
4810
+ oct += String.fromCharCode(peek);
4811
+ i++;
4525
4812
  } else {
4526
- out.push(b);
4813
+ break;
4527
4814
  }
4528
4815
  }
4529
- return { type: "literal", bytes: new Uint8Array(out), start, end: pos };
4816
+ bytes.push(parseInt(oct, 8) & 255);
4817
+ } else {
4818
+ bytes.push(next);
4530
4819
  }
4531
- if (ch === 60) {
4532
- if (pos + 1 < len && bytes[pos + 1] === 60) {
4533
- pos += 2;
4534
- return { type: "dictStart", start, end: pos };
4535
- }
4536
- pos++;
4537
- const nibbles = [];
4538
- while (pos < len && bytes[pos] !== 62) {
4539
- const hv = hexCharVal(bytes[pos++]);
4540
- if (hv >= 0) nibbles.push(hv);
4541
- }
4542
- if (pos < len && bytes[pos] === 62) pos++;
4543
- if (nibbles.length % 2 === 1) nibbles.push(0);
4544
- const hexBytes = new Uint8Array(nibbles.length / 2);
4545
- for (let i = 0; i < hexBytes.length; i++) {
4546
- hexBytes[i] = nibbles[i * 2] << 4 | nibbles[i * 2 + 1];
4820
+ }
4821
+ return new Uint8Array(bytes);
4822
+ }
4823
+ function extractPdfStringRawBytes(strObj) {
4824
+ if (strObj instanceof import_pdf_lib.PDFHexString) {
4825
+ return strObj.asBytes();
4826
+ }
4827
+ const serialized = strObj.asString();
4828
+ const inner = serialized.startsWith("(") && serialized.endsWith(")") ? serialized.slice(1, -1) : serialized;
4829
+ return decodePdfLiteralBodyBytes(inner);
4830
+ }
4831
+ function isSignatureDict(dict) {
4832
+ const typeVal = dict.get(import_pdf_lib.PDFName.of("Type"));
4833
+ if (typeVal instanceof import_pdf_lib.PDFName && typeVal.asString() === "/Sig") return true;
4834
+ const ftVal = dict.get(import_pdf_lib.PDFName.of("FT"));
4835
+ if (ftVal instanceof import_pdf_lib.PDFName && ftVal.asString() === "/Sig") return true;
4836
+ return false;
4837
+ }
4838
+ function transformPdfObjectStringsWithRc4(obj, objKey) {
4839
+ if (obj instanceof import_pdf_lib.PDFHexString || obj instanceof import_pdf_lib.PDFString) {
4840
+ const raw = extractPdfStringRawBytes(obj);
4841
+ const transformed = rc4Bytes(objKey, raw);
4842
+ return import_pdf_lib.PDFHexString.of(bytesToHex(transformed));
4843
+ }
4844
+ if (obj instanceof import_pdf_lib.PDFArray) {
4845
+ for (let i = 0; i < obj.size(); i++) {
4846
+ const item = obj.get(i);
4847
+ const next = transformPdfObjectStringsWithRc4(item, objKey);
4848
+ if (next !== item) {
4849
+ obj.set(i, next);
4547
4850
  }
4548
- return { type: "hex", bytes: hexBytes, start, end: pos };
4549
4851
  }
4550
- if (ch === 62) {
4551
- if (pos + 1 < len && bytes[pos + 1] === 62) {
4552
- pos += 2;
4553
- return { type: "dictEnd", start, end: pos };
4852
+ return obj;
4853
+ }
4854
+ if (obj instanceof import_pdf_lib.PDFDict) {
4855
+ const isSig = isSignatureDict(obj);
4856
+ for (const [key, val] of obj.entries()) {
4857
+ if (isSig && key.asString() === "/Contents") {
4858
+ continue;
4859
+ }
4860
+ const next = transformPdfObjectStringsWithRc4(val, objKey);
4861
+ if (next !== val) {
4862
+ obj.set(key, next);
4554
4863
  }
4555
- pos++;
4556
- return { type: "op", op: ">", start, end: pos };
4557
4864
  }
4558
- if (ch === 91) {
4559
- pos++;
4560
- const items = [];
4561
- while (pos < len) {
4562
- while (pos < len && isPdfWhitespace(bytes[pos])) pos++;
4563
- if (pos < len && bytes[pos] === 93) {
4564
- pos++;
4565
- break;
4865
+ return obj;
4866
+ }
4867
+ return obj;
4868
+ }
4869
+ function extractOrCreateDocumentFileId(pdfDoc) {
4870
+ const existingId = pdfDoc.context.trailerInfo.ID;
4871
+ if (existingId) {
4872
+ const idArr = existingId instanceof import_pdf_lib.PDFArray ? existingId : pdfDoc.context.lookupMaybe(existingId, import_pdf_lib.PDFArray);
4873
+ if (idArr && idArr.size() > 0) {
4874
+ const first = idArr.get(0);
4875
+ if (first instanceof import_pdf_lib.PDFHexString || first instanceof import_pdf_lib.PDFString) {
4876
+ const bytes = extractPdfStringRawBytes(first);
4877
+ if (bytes.byteLength > 0) {
4878
+ const hex = bytesToHex(bytes);
4879
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
4880
+ import_pdf_lib.PDFHexString.of(hex),
4881
+ import_pdf_lib.PDFHexString.of(hex)
4882
+ ]);
4883
+ return bytes;
4566
4884
  }
4567
- const child = readToken();
4568
- if (!child) break;
4569
- items.push(child);
4570
4885
  }
4571
- return { type: "array", items, start, end: pos };
4572
4886
  }
4573
- if (ch === 93) {
4574
- pos++;
4575
- return { type: "op", op: "]", start, end: pos };
4887
+ }
4888
+ const seedBytes = new Uint8Array(32);
4889
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
4890
+ globalThis.crypto.getRandomValues(seedBytes);
4891
+ } else {
4892
+ const fallbackText = `univer-pdf-${Date.now()}-${Math.random()}-${pdfDoc.getPageCount()}`;
4893
+ const enc = new TextEncoder().encode(fallbackText);
4894
+ seedBytes.set(enc.subarray(0, Math.min(32, enc.byteLength)));
4895
+ }
4896
+ const fileId = md5Bytes(seedBytes);
4897
+ const idHex = bytesToHex(fileId);
4898
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
4899
+ import_pdf_lib.PDFHexString.of(idHex),
4900
+ import_pdf_lib.PDFHexString.of(idHex)
4901
+ ]);
4902
+ return fileId;
4903
+ }
4904
+ async function applyPdfSecurityToDocument(pdfDoc, security) {
4905
+ if (security.enabled === false) return;
4906
+ await pdfDoc.flush();
4907
+ const keyLength = security.keyLength === 40 ? 40 : 128;
4908
+ const version = keyLength === 40 ? 1 : 2;
4909
+ const revision = keyLength === 40 ? 2 : 3;
4910
+ const userPassword = security.userPassword ?? "";
4911
+ const ownerPassword = security.ownerPassword && security.ownerPassword.length > 0 ? security.ownerPassword : userPassword.length > 0 ? userPassword : "univer-pdf-owner-guard";
4912
+ const fileId = extractOrCreateDocumentFileId(pdfDoc);
4913
+ const pSigned = encodePdfPermissionFlags(security.permissions, revision);
4914
+ const oBytes = computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLength);
4915
+ const encryptionKey = computeFileEncryptionKeyFromPadded(
4916
+ padPdfPassword(userPassword),
4917
+ oBytes,
4918
+ pSigned,
4919
+ fileId,
4920
+ revision,
4921
+ keyLength
4922
+ );
4923
+ const uBytes = computeUserPasswordValue(encryptionKey, fileId, revision);
4924
+ const idRef = pdfDoc.context.trailerInfo.ID instanceof import_pdf_lib.PDFRef ? pdfDoc.context.trailerInfo.ID : null;
4925
+ for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
4926
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
4927
+ continue;
4576
4928
  }
4577
- if (ch === 47) {
4578
- pos++;
4579
- let name = "";
4580
- while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
4581
- if (bytes[pos] === 35 && pos + 2 < len) {
4582
- const h1 = hexCharVal(bytes[pos + 1]);
4583
- const h2 = hexCharVal(bytes[pos + 2]);
4584
- if (h1 >= 0 && h2 >= 0) {
4585
- name += String.fromCharCode(h1 << 4 | h2);
4586
- pos += 3;
4587
- continue;
4588
- }
4929
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
4930
+ if (obj instanceof import_pdf_lib.PDFRawStream) {
4931
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
4932
+ const encryptedStream = rc4Bytes(objKey, obj.contents);
4933
+ obj.dict.set(import_pdf_lib.PDFName.of("Length"), import_pdf_lib.PDFNumber.of(encryptedStream.byteLength));
4934
+ pdfDoc.context.assign(ref, import_pdf_lib.PDFRawStream.of(obj.dict, encryptedStream));
4935
+ } else if (obj instanceof import_pdf_lib.PDFStream) {
4936
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
4937
+ const encodedContents = obj.getContents();
4938
+ const encryptedStream = rc4Bytes(objKey, encodedContents);
4939
+ obj.dict.set(import_pdf_lib.PDFName.of("Length"), import_pdf_lib.PDFNumber.of(encryptedStream.byteLength));
4940
+ pdfDoc.context.assign(ref, import_pdf_lib.PDFRawStream.of(obj.dict, encryptedStream));
4941
+ } else {
4942
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
4943
+ if (next !== obj) {
4944
+ pdfDoc.context.assign(ref, next);
4945
+ }
4946
+ }
4947
+ }
4948
+ const encryptDict = pdfDoc.context.obj({
4949
+ Filter: import_pdf_lib.PDFName.of("Standard"),
4950
+ V: import_pdf_lib.PDFNumber.of(version),
4951
+ R: import_pdf_lib.PDFNumber.of(revision),
4952
+ Length: import_pdf_lib.PDFNumber.of(keyLength),
4953
+ P: import_pdf_lib.PDFNumber.of(pSigned),
4954
+ O: import_pdf_lib.PDFHexString.of(bytesToHex(oBytes)),
4955
+ U: import_pdf_lib.PDFHexString.of(bytesToHex(uBytes))
4956
+ });
4957
+ const encryptRef = pdfDoc.context.register(encryptDict);
4958
+ pdfDoc.context.trailerInfo.Encrypt = encryptRef;
4959
+ }
4960
+ async function encryptPdfBytes(pdfBytes, security) {
4961
+ if (!security || security.enabled === false) {
4962
+ return pdfBytes.slice();
4963
+ }
4964
+ const cleanBytes = inspectPdfEncryption(pdfBytes).encrypted ? await decryptPdfBytes(pdfBytes, security.ownerPassword || security.userPassword || "") : pdfBytes;
4965
+ const pdfDoc = await import_pdf_lib.PDFDocument.load(cleanBytes, { updateMetadata: false });
4966
+ await applyPdfSecurityToDocument(pdfDoc, security);
4967
+ return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false });
4968
+ }
4969
+ function bytesToLatin1(bytes) {
4970
+ let out = "";
4971
+ const chunk = 32768;
4972
+ for (let i = 0; i < bytes.byteLength; i += chunk) {
4973
+ out += String.fromCharCode(...bytes.subarray(i, i + chunk));
4974
+ }
4975
+ return out;
4976
+ }
4977
+ function extractBalancedPdfDict(text, startIdx) {
4978
+ const openIdx = text.indexOf("<<", startIdx);
4979
+ if (openIdx < 0) return null;
4980
+ let depth = 0;
4981
+ let inLiteral = false;
4982
+ let literalDepth = 0;
4983
+ for (let i = openIdx; i < text.length; i++) {
4984
+ const ch = text.charCodeAt(i);
4985
+ if (inLiteral) {
4986
+ if (ch === 92) {
4987
+ i++;
4988
+ continue;
4989
+ }
4990
+ if (ch === 40) literalDepth++;
4991
+ else if (ch === 41) {
4992
+ literalDepth--;
4993
+ if (literalDepth <= 0) {
4994
+ inLiteral = false;
4589
4995
  }
4590
- name += String.fromCharCode(bytes[pos++]);
4591
4996
  }
4592
- return { type: "name", value: name, start, end: pos };
4997
+ continue;
4593
4998
  }
4594
- let word = "";
4595
- while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
4596
- word += String.fromCharCode(bytes[pos++]);
4999
+ if (ch === 40) {
5000
+ inLiteral = true;
5001
+ literalDepth = 1;
5002
+ continue;
4597
5003
  }
4598
- if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(word)) {
4599
- return { type: "number", num: parseFloat(word), start, end: pos };
5004
+ if (ch === 37) {
5005
+ while (i < text.length && text.charCodeAt(i) !== 10 && text.charCodeAt(i) !== 13) {
5006
+ i++;
5007
+ }
5008
+ continue;
4600
5009
  }
4601
- if (word === "ID") {
4602
- if (pos < len && isPdfWhitespace(bytes[pos])) pos++;
4603
- while (pos + 1 < len) {
4604
- if (bytes[pos] === 69 && bytes[pos + 1] === 73 && (pos === 0 || isPdfWhitespace(bytes[pos - 1])) && (pos + 2 >= len || isPdfWhitespace(bytes[pos + 2]) || isPdfDelimiter(bytes[pos + 2]))) {
4605
- pos += 2;
4606
- return { type: "op", op: "EI", start, end: pos };
4607
- }
4608
- pos++;
5010
+ if (ch === 60 && text.charCodeAt(i + 1) === 60) {
5011
+ depth++;
5012
+ i++;
5013
+ continue;
5014
+ }
5015
+ if (ch === 62 && text.charCodeAt(i + 1) === 62) {
5016
+ depth--;
5017
+ i++;
5018
+ if (depth === 0) {
5019
+ return text.slice(openIdx, i + 1);
4609
5020
  }
4610
5021
  }
4611
- return { type: "op", op: word, start, end: pos };
4612
- };
4613
- const tokens = [];
4614
- let tok;
4615
- while ((tok = readToken()) !== null) {
4616
- tokens.push(tok);
4617
5022
  }
4618
- return tokens;
5023
+ return null;
4619
5024
  }
4620
- function estimateTextAdvanceInTextSpace(text, state) {
4621
- const fs = Math.abs(state.fontSize) || 12;
4622
- const scaleH = state.horizScaling / 100;
4623
- let adv = 0;
4624
- for (const ch of text) {
4625
- const cp = ch.codePointAt(0) ?? 32;
4626
- const glyphW = cp > 127 ? fs : fs * 0.54;
4627
- adv += (glyphW + state.charSpacing + (cp === 32 ? state.wordSpacing : 0)) * scaleH;
5025
+ function parsePdfStringTokenAfterKey(dictText, keyName) {
5026
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*`);
5027
+ const match = re.exec(dictText);
5028
+ if (!match) return null;
5029
+ let pos = match.index + match[0].length;
5030
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5031
+ if (pos >= dictText.length) return null;
5032
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5033
+ const close = dictText.indexOf(">", pos + 1);
5034
+ if (close < 0) return null;
5035
+ return hexToBytes(dictText.slice(pos + 1, close));
4628
5036
  }
4629
- return adv;
5037
+ if (dictText[pos] === "(") {
5038
+ let depth = 1;
5039
+ let i = pos + 1;
5040
+ while (i < dictText.length && depth > 0) {
5041
+ const ch = dictText.charCodeAt(i);
5042
+ if (ch === 92) {
5043
+ i += 2;
5044
+ continue;
5045
+ }
5046
+ if (ch === 40) depth++;
5047
+ else if (ch === 41) depth--;
5048
+ i++;
5049
+ }
5050
+ if (depth === 0) {
5051
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
5052
+ }
5053
+ }
5054
+ return null;
4630
5055
  }
4631
- function parsePdfContentStreamTextOps(doc, streamBytes, resourcesDict, mediaBox, initialCtm = [1, 0, 0, 1, 0, 0], isTopLevelStream = true, depth = 0) {
4632
- if (streamBytes.byteLength === 0 || depth > 5) return [];
4633
- const fonts = extractResourcesFontMap(doc, resourcesDict);
4634
- const tokens = tokenizeContentStream(streamBytes);
4635
- const results = [];
4636
- const stateStack = [];
4637
- let state = {
4638
- ctm: [...initialCtm],
4639
- fontName: "",
4640
- fontSize: 12,
4641
- charSpacing: 0,
4642
- wordSpacing: 0,
4643
- horizScaling: 100,
4644
- leading: 0,
4645
- textRise: 0
4646
- };
4647
- let textMatrix = [1, 0, 0, 1, 0, 0];
4648
- let textLineMatrix = [1, 0, 0, 1, 0, 0];
4649
- const operands = [];
4650
- const emitTextSpan = (rawText, textSpaceAdvance, opStart, opEnd) => {
4651
- const trimmed = rawText.replace(/\0/g, "");
4652
- if (!trimmed.trim()) {
4653
- textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
4654
- return;
5056
+ function parseFirstPdfArrayStringBytes(dictText, keyName) {
5057
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*\\[`);
5058
+ const match = re.exec(dictText);
5059
+ if (!match) return null;
5060
+ let pos = match.index + match[0].length;
5061
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5062
+ if (pos >= dictText.length) return null;
5063
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5064
+ const close = dictText.indexOf(">", pos + 1);
5065
+ if (close >= 0) return hexToBytes(dictText.slice(pos + 1, close));
5066
+ } else if (dictText[pos] === "(") {
5067
+ let depth = 1;
5068
+ let i = pos + 1;
5069
+ while (i < dictText.length && depth > 0) {
5070
+ const ch = dictText.charCodeAt(i);
5071
+ if (ch === 92) {
5072
+ i += 2;
5073
+ continue;
5074
+ }
5075
+ if (ch === 40) depth++;
5076
+ else if (ch === 41) depth--;
5077
+ i++;
4655
5078
  }
4656
- const combined = multiplyPdfMatrix(textMatrix, state.ctm);
4657
- const bx = combined[4];
4658
- const by = combined[5] + state.textRise;
4659
- const scaleX = Math.hypot(combined[0], combined[1]) || 1;
4660
- const scaleY = Math.hypot(combined[2], combined[3]) || 1;
4661
- const effectiveFontSize = Math.round(Math.max(1, (Math.abs(state.fontSize) || 12) * scaleY) * 100) / 100;
4662
- const widthPt = Math.max(4, Math.abs(textSpaceAdvance * scaleX));
4663
- const heightPt = Math.max(8, effectiveFontSize * 1.2);
4664
- const left = Math.round((bx - mediaBox.x) * 100) / 100;
4665
- const top = Math.round(Math.max(0, mediaBox.height - (by - mediaBox.y) - effectiveFontSize * 0.85) * 100) / 100;
4666
- results.push({
4667
- text: trimmed,
4668
- left,
4669
- top,
4670
- width: Math.round(widthPt * 100) / 100,
4671
- height: Math.round(heightPt * 100) / 100,
4672
- fontSize: effectiveFontSize,
4673
- ...isTopLevelStream ? { streamStartOffset: opStart, streamEndOffset: opEnd } : {}
4674
- });
4675
- textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
4676
- };
4677
- for (const tok of tokens) {
4678
- if (tok.type !== "op") {
4679
- operands.push(tok);
4680
- continue;
5079
+ if (depth === 0) {
5080
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
4681
5081
  }
4682
- const op = tok.op;
4683
- const opStart = operands.length > 0 ? operands[0].start : tok.start;
4684
- const opEnd = tok.end;
4685
- switch (op) {
4686
- case "q": {
4687
- stateStack.push({ ...state, ctm: [...state.ctm] });
4688
- break;
4689
- }
4690
- case "Q": {
4691
- const popped = stateStack.pop();
4692
- if (popped) state = popped;
4693
- break;
4694
- }
4695
- case "cm": {
4696
- if (operands.length >= 6) {
4697
- const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
4698
- const m = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
4699
- state.ctm = multiplyPdfMatrix(m, state.ctm);
4700
- }
4701
- break;
4702
- }
4703
- case "BT": {
4704
- textMatrix = [1, 0, 0, 1, 0, 0];
4705
- textLineMatrix = [1, 0, 0, 1, 0, 0];
4706
- break;
4707
- }
4708
- case "ET": {
4709
- break;
4710
- }
4711
- case "Tf": {
4712
- if (operands.length >= 2) {
4713
- const nameTok = operands[operands.length - 2];
4714
- const sizeTok = operands[operands.length - 1];
4715
- if (nameTok.type === "name") state.fontName = nameTok.value;
4716
- if (sizeTok.type === "number") state.fontSize = sizeTok.num;
4717
- }
4718
- break;
4719
- }
4720
- case "Tc": {
4721
- const last = operands[operands.length - 1];
4722
- if (last?.type === "number") state.charSpacing = last.num;
4723
- break;
4724
- }
4725
- case "Tw": {
4726
- const last = operands[operands.length - 1];
4727
- if (last?.type === "number") state.wordSpacing = last.num;
4728
- break;
4729
- }
4730
- case "Tz": {
4731
- const last = operands[operands.length - 1];
4732
- if (last?.type === "number") state.horizScaling = last.num;
4733
- break;
4734
- }
4735
- case "TL": {
4736
- const last = operands[operands.length - 1];
4737
- if (last?.type === "number") state.leading = last.num;
4738
- break;
4739
- }
4740
- case "Ts": {
4741
- const last = operands[operands.length - 1];
4742
- if (last?.type === "number") state.textRise = last.num;
4743
- break;
4744
- }
4745
- case "Td":
4746
- case "TD": {
4747
- if (operands.length >= 2) {
4748
- const txTok = operands[operands.length - 2];
4749
- const tyTok = operands[operands.length - 1];
4750
- const tx = txTok.type === "number" ? txTok.num : 0;
4751
- const ty = tyTok.type === "number" ? tyTok.num : 0;
4752
- if (op === "TD") state.leading = -ty;
4753
- textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, tx, ty], textLineMatrix);
4754
- textMatrix = [...textLineMatrix];
4755
- }
4756
- break;
4757
- }
4758
- case "Tm": {
4759
- if (operands.length >= 6) {
4760
- const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
4761
- textMatrix = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
4762
- textLineMatrix = [...textMatrix];
4763
- }
4764
- break;
4765
- }
4766
- case "T*": {
4767
- textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
4768
- textMatrix = [...textLineMatrix];
4769
- break;
4770
- }
4771
- case "Tj":
4772
- case "'":
4773
- case '"': {
4774
- if (op === "'" || op === '"') {
4775
- if (op === '"' && operands.length >= 3) {
4776
- const twTok = operands[operands.length - 3];
4777
- const tcTok = operands[operands.length - 2];
4778
- if (twTok.type === "number") state.wordSpacing = twTok.num;
4779
- if (tcTok.type === "number") state.charSpacing = tcTok.num;
4780
- }
4781
- textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
4782
- textMatrix = [...textLineMatrix];
4783
- }
4784
- const strTok = operands[operands.length - 1];
4785
- if (strTok && (strTok.type === "literal" || strTok.type === "hex")) {
4786
- const fontInfo = fonts.get(state.fontName);
4787
- const { text } = decodePdfStringBytes(strTok.bytes, fontInfo);
4788
- const adv = estimateTextAdvanceInTextSpace(text, state);
4789
- emitTextSpan(text, adv, opStart, opEnd);
4790
- }
4791
- break;
4792
- }
4793
- case "TJ": {
4794
- const arrTok = operands[operands.length - 1];
4795
- if (arrTok?.type === "array") {
4796
- const fontInfo = fonts.get(state.fontName);
4797
- const fs = Math.abs(state.fontSize) || 12;
4798
- const scaleH = state.horizScaling / 100;
4799
- let joined = "";
4800
- let totalAdv = 0;
4801
- for (const item of arrTok.items) {
4802
- if (item.type === "literal" || item.type === "hex") {
4803
- const { text } = decodePdfStringBytes(item.bytes, fontInfo);
4804
- joined += text;
4805
- totalAdv += estimateTextAdvanceInTextSpace(text, state);
4806
- } else if (item.type === "number") {
4807
- const shift = -item.num / 1e3 * fs * scaleH;
4808
- totalAdv += shift;
4809
- if (item.num < -180 && joined.length > 0 && !joined.endsWith(" ")) {
4810
- joined += " ";
4811
- }
4812
- }
4813
- }
4814
- emitTextSpan(joined, totalAdv, opStart, opEnd);
4815
- }
5082
+ }
5083
+ return null;
5084
+ }
5085
+ function parseRawEncryptFromPdfBytes(pdfBytes) {
5086
+ if (!pdfBytes || pdfBytes.byteLength < 16) return null;
5087
+ const rawText = bytesToLatin1(pdfBytes);
5088
+ let containerDict = null;
5089
+ let searchEnd = rawText.length;
5090
+ while (searchEnd > 0) {
5091
+ const trailerIdx = rawText.lastIndexOf("trailer", searchEnd - 1);
5092
+ if (trailerIdx < 0) break;
5093
+ const prevCh = trailerIdx > 0 ? rawText[trailerIdx - 1] : "\n";
5094
+ const afterCh = rawText[trailerIdx + 7] ?? " ";
5095
+ if (/[\s\r\n>]/.test(prevCh) && /[\s\r\n<]/.test(afterCh)) {
5096
+ const candidate = extractBalancedPdfDict(rawText, trailerIdx + 7);
5097
+ if (candidate && /\/Encrypt\b/.test(candidate)) {
5098
+ containerDict = candidate;
4816
5099
  break;
4817
5100
  }
4818
- case "Do": {
4819
- const nameTok = operands[operands.length - 1];
4820
- if (nameTok?.type === "name" && resourcesDict) {
4821
- const xObjEntry = resourcesDict.get(import_pdf_lib.PDFName.of("XObject"));
4822
- const xObjDict = doc.context.lookupMaybe(xObjEntry, import_pdf_lib.PDFDict);
4823
- const targetObj = xObjDict?.get(import_pdf_lib.PDFName.of(nameTok.value));
4824
- const resolvedXObj = targetObj instanceof import_pdf_lib.PDFRef ? doc.context.lookup(targetObj) : targetObj;
4825
- if (resolvedXObj instanceof import_pdf_lib.PDFRawStream) {
4826
- const subType = resolvedXObj.dict.get(import_pdf_lib.PDFName.of("Subtype"));
4827
- if (subType instanceof import_pdf_lib.PDFName && subType.decodeText() === "Form") {
4828
- const formBytes = decodeSingleStreamObject(doc, resolvedXObj);
4829
- const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(import_pdf_lib.PDFName.of("Resources")), import_pdf_lib.PDFDict) ?? resourcesDict;
4830
- let formMat = [...state.ctm];
4831
- const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(import_pdf_lib.PDFName.of("Matrix")), import_pdf_lib.PDFArray);
4832
- if (matArr && matArr.size() >= 6) {
4833
- const nums = [];
4834
- for (let k = 0; k < 6; k++) {
4835
- const nObj = matArr.get(k);
4836
- nums.push(nObj instanceof import_pdf_lib.PDFNumber ? nObj.asNumber() : 0);
4837
- }
4838
- formMat = multiplyPdfMatrix(
4839
- [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]],
4840
- state.ctm
4841
- );
4842
- }
4843
- const subSpans = parsePdfContentStreamTextOps(
4844
- doc,
4845
- formBytes,
4846
- formRes,
4847
- mediaBox,
4848
- formMat,
4849
- false,
4850
- depth + 1
4851
- );
4852
- results.push(...subSpans);
4853
- }
4854
- }
4855
- }
4856
- break;
5101
+ if (candidate && !containerDict) {
5102
+ containerDict = candidate;
4857
5103
  }
4858
- default:
4859
- break;
4860
5104
  }
4861
- operands.length = 0;
5105
+ searchEnd = trailerIdx;
4862
5106
  }
4863
- return results;
4864
- }
4865
- function rectsIntersect(a, b) {
4866
- const ax2 = a.left + a.width;
4867
- const ay2 = a.top + a.height;
4868
- const bx2 = b.left + b.width;
4869
- const by2 = b.top + b.height;
4870
- return !(ax2 <= b.left || a.left >= bx2 || ay2 <= b.top || a.top >= by2);
4871
- }
4872
- function stripPdfPageNativeTextInRects(doc, page, stripRects) {
4873
- if (!stripRects.length) return 0;
4874
- const contentsBytes = decodeContentsEntry(doc, page.node.Contents());
4875
- if (contentsBytes.byteLength === 0) return 0;
4876
- const mediaBox = page.getMediaBox();
4877
- const ops = parsePdfContentStreamTextOps(doc, contentsBytes, page.node.Resources(), mediaBox, [1, 0, 0, 1, 0, 0], true);
4878
- const matchingOps = ops.filter(
4879
- (op) => op.streamStartOffset !== void 0 && op.streamEndOffset !== void 0 && stripRects.some((r) => rectsIntersect(op, r))
4880
- );
4881
- if (matchingOps.length === 0) return 0;
4882
- const sanitized = contentsBytes.slice();
4883
- for (const op of matchingOps) {
4884
- for (let i = op.streamStartOffset; i < op.streamEndOffset; i++) {
4885
- if (sanitized[i] !== 10 && sanitized[i] !== 13) {
4886
- sanitized[i] = 32;
4887
- }
5107
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5108
+ const xrefMatch = /<<[\s\S]{0,2048}?\/Type\s*\/XRef[\s\S]{0,2048}?>>/.exec(rawText);
5109
+ if (xrefMatch && /\/Encrypt\b/.test(xrefMatch[0])) {
5110
+ containerDict = xrefMatch[0];
4888
5111
  }
4889
5112
  }
4890
- const newStream = doc.context.flateStream(sanitized);
4891
- const newRef = doc.context.register(newStream);
4892
- page.node.set(import_pdf_lib.PDFName.of("Contents"), newRef);
4893
- return matchingOps.length;
4894
- }
4895
-
4896
- // src/exporter/pdf-security.ts
4897
- var import_pdf_lib2 = require("pdf-lib");
4898
- var PdfSecurityError = class extends Error {
4899
- constructor(code, message) {
4900
- super(message);
4901
- this.name = "PdfSecurityError";
4902
- this.code = code;
4903
- }
4904
- };
4905
- var PDF_PASSWORD_PADDING = new Uint8Array([
4906
- 40,
4907
- 191,
4908
- 78,
4909
- 94,
4910
- 78,
4911
- 117,
4912
- 138,
4913
- 65,
4914
- 100,
4915
- 0,
4916
- 78,
4917
- 86,
4918
- 255,
4919
- 250,
4920
- 1,
4921
- 8,
4922
- 46,
4923
- 46,
4924
- 0,
4925
- 182,
4926
- 208,
4927
- 104,
4928
- 62,
4929
- 128,
4930
- 47,
4931
- 12,
4932
- 169,
4933
- 254,
4934
- 100,
4935
- 83,
4936
- 105,
4937
- 122
4938
- ]);
4939
- var DEFAULT_ALL_PERMISSIONS = Object.freeze({
4940
- print: true,
4941
- highResPrint: true,
4942
- modify: true,
4943
- copy: true,
4944
- annotate: true,
4945
- fillForms: true,
4946
- assemble: true
4947
- });
4948
- var MD5_SHIFTS = [
4949
- 7,
4950
- 12,
4951
- 17,
4952
- 22,
4953
- 7,
4954
- 12,
4955
- 17,
4956
- 22,
4957
- 7,
4958
- 12,
4959
- 17,
4960
- 22,
4961
- 7,
4962
- 12,
4963
- 17,
4964
- 22,
4965
- 5,
4966
- 9,
4967
- 14,
4968
- 20,
4969
- 5,
4970
- 9,
4971
- 14,
4972
- 20,
4973
- 5,
4974
- 9,
4975
- 14,
4976
- 20,
4977
- 5,
4978
- 9,
4979
- 14,
4980
- 20,
4981
- 4,
4982
- 11,
4983
- 16,
4984
- 23,
4985
- 4,
4986
- 11,
4987
- 16,
4988
- 23,
4989
- 4,
4990
- 11,
4991
- 16,
4992
- 23,
4993
- 4,
4994
- 11,
4995
- 16,
4996
- 23,
4997
- 6,
4998
- 10,
4999
- 15,
5000
- 21,
5001
- 6,
5002
- 10,
5003
- 15,
5004
- 21,
5005
- 6,
5006
- 10,
5007
- 15,
5008
- 21,
5009
- 6,
5010
- 10,
5011
- 15,
5012
- 21
5013
- ];
5014
- var MD5_K = (() => {
5015
- const table = new Uint32Array(64);
5016
- for (let i = 0; i < 64; i++) {
5017
- table[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
5113
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5114
+ return null;
5018
5115
  }
5019
- return table;
5020
- })();
5021
- function rotl32(x, n) {
5022
- return (x << n | x >>> 32 - n) >>> 0;
5023
- }
5024
- function md5Bytes(data) {
5025
- const msgLen = data.byteLength;
5026
- const rem = (msgLen + 9) % 64;
5027
- const padZeroes = rem === 0 ? 0 : 64 - rem;
5028
- const totalLen = msgLen + 9 + padZeroes;
5029
- const buf = new Uint8Array(totalLen);
5030
- buf.set(data, 0);
5031
- buf[msgLen] = 128;
5032
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
5033
- const bitLenLow = msgLen * 8 >>> 0;
5034
- const bitLenHigh = Math.floor(msgLen * 8 / 4294967296) >>> 0;
5035
- view.setUint32(totalLen - 8, bitLenLow, true);
5036
- view.setUint32(totalLen - 4, bitLenHigh, true);
5037
- let a0 = 1732584193;
5038
- let b0 = 4023233417;
5039
- let c0 = 2562383102;
5040
- let d0 = 271733878;
5041
- const M = new Uint32Array(16);
5042
- for (let offset = 0; offset < totalLen; offset += 64) {
5043
- for (let j = 0; j < 16; j++) {
5044
- M[j] = view.getUint32(offset + j * 4, true);
5116
+ let encryptDictText = null;
5117
+ const refMatch = /\/Encrypt\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
5118
+ if (refMatch) {
5119
+ const objNum = refMatch[1];
5120
+ const genNum = refMatch[2];
5121
+ const objRe = new RegExp(`(?:^|[\\r\\n\\s])${objNum}\\s+${genNum}\\s+obj\\b`, "g");
5122
+ let lastObjMatch = null;
5123
+ let m;
5124
+ while ((m = objRe.exec(rawText)) !== null) {
5125
+ lastObjMatch = m;
5045
5126
  }
5046
- let A = a0;
5047
- let B = b0;
5048
- let C = c0;
5049
- let D = d0;
5050
- for (let i = 0; i < 64; i++) {
5051
- let F;
5052
- let g;
5053
- if (i < 16) {
5054
- F = B & C | ~B & D;
5055
- g = i;
5056
- } else if (i < 32) {
5057
- F = D & B | ~D & C;
5058
- g = (5 * i + 1) % 16;
5059
- } else if (i < 48) {
5060
- F = B ^ C ^ D;
5061
- g = (3 * i + 5) % 16;
5062
- } else {
5063
- F = C ^ (B | ~D);
5064
- g = 7 * i % 16;
5127
+ if (lastObjMatch) {
5128
+ encryptDictText = extractBalancedPdfDict(rawText, lastObjMatch.index + lastObjMatch[0].length);
5129
+ }
5130
+ } else if (/\/Encrypt\s*<</.test(containerDict)) {
5131
+ const inlineIdx = containerDict.search(/\/Encrypt\s*<</);
5132
+ encryptDictText = extractBalancedPdfDict(containerDict, inlineIdx);
5133
+ }
5134
+ if (!encryptDictText) return null;
5135
+ const filterMatch = /\/Filter\s*\/([A-Za-z0-9_.+-]+)/.exec(encryptDictText);
5136
+ const vMatch = /\/V\s+(-?\d+)/.exec(encryptDictText);
5137
+ const rMatch = /\/R\s+(-?\d+)/.exec(encryptDictText);
5138
+ const lenMatch = /\/Length\s+(\d+)/.exec(encryptDictText);
5139
+ const pMatch = /\/P\s+(-?\d+)/.exec(encryptDictText);
5140
+ const filter = filterMatch ? filterMatch[1] : "Standard";
5141
+ const version = vMatch ? parseInt(vMatch[1], 10) : 1;
5142
+ const revision = rMatch ? parseInt(rMatch[1], 10) : version >= 2 ? 3 : 2;
5143
+ const keyLength = lenMatch ? parseInt(lenMatch[1], 10) : version >= 2 ? 128 : 40;
5144
+ const pSigned = pMatch ? parseInt(pMatch[1], 10) | 0 : -4;
5145
+ const oBytes = parsePdfStringTokenAfterKey(encryptDictText, "O") ?? new Uint8Array(0);
5146
+ const uBytes = parsePdfStringTokenAfterKey(encryptDictText, "U") ?? new Uint8Array(0);
5147
+ let fileId = parseFirstPdfArrayStringBytes(containerDict, "ID");
5148
+ if (!fileId) {
5149
+ const idRefMatch = /\/ID\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
5150
+ if (idRefMatch) {
5151
+ const idObjRe = new RegExp(`(?:^|[\\r\\n\\s])${idRefMatch[1]}\\s+${idRefMatch[2]}\\s+obj\\b([\\s\\S]{0,512}?)endobj`);
5152
+ const idObjM = idObjRe.exec(rawText);
5153
+ if (idObjM) {
5154
+ fileId = parseFirstPdfArrayStringBytes(`/ID ${idObjM[1]}`, "ID");
5065
5155
  }
5066
- const sum = A + F + MD5_K[i] + M[g] >>> 0;
5067
- A = D;
5068
- D = C;
5069
- C = B;
5070
- B = B + rotl32(sum, MD5_SHIFTS[i]) >>> 0;
5071
5156
  }
5072
- a0 = a0 + A >>> 0;
5073
- b0 = b0 + B >>> 0;
5074
- c0 = c0 + C >>> 0;
5075
- d0 = d0 + D >>> 0;
5076
5157
  }
5077
- const out = new Uint8Array(16);
5078
- const outView = new DataView(out.buffer);
5079
- outView.setUint32(0, a0, true);
5080
- outView.setUint32(4, b0, true);
5081
- outView.setUint32(8, c0, true);
5082
- outView.setUint32(12, d0, true);
5083
- return out;
5158
+ return {
5159
+ filter,
5160
+ version,
5161
+ revision,
5162
+ keyLength,
5163
+ pSigned,
5164
+ oBytes,
5165
+ uBytes,
5166
+ fileId: fileId ?? new Uint8Array(0)
5167
+ };
5084
5168
  }
5085
- function rc4Bytes(key, data) {
5086
- const keyLen = key.byteLength;
5087
- if (keyLen === 0) return data.slice();
5088
- const S = new Uint8Array(256);
5089
- for (let i2 = 0; i2 < 256; i2++) {
5090
- S[i2] = i2;
5169
+ function extractEncryptMetadataFromDoc(doc) {
5170
+ const encEntry = doc.context.trailerInfo.Encrypt;
5171
+ if (!encEntry) return null;
5172
+ const encDict = encEntry instanceof import_pdf_lib.PDFDict ? encEntry : doc.context.lookupMaybe(encEntry, import_pdf_lib.PDFDict);
5173
+ if (!encDict) return null;
5174
+ const filterObj = encDict.get(import_pdf_lib.PDFName.of("Filter"));
5175
+ const filter = filterObj instanceof import_pdf_lib.PDFName ? filterObj.decodeText() : "Standard";
5176
+ const vObj = encDict.get(import_pdf_lib.PDFName.of("V"));
5177
+ const version = vObj instanceof import_pdf_lib.PDFNumber ? vObj.asNumber() : 1;
5178
+ const rObj = encDict.get(import_pdf_lib.PDFName.of("R"));
5179
+ const revision = rObj instanceof import_pdf_lib.PDFNumber ? rObj.asNumber() : version >= 2 ? 3 : 2;
5180
+ const lenObj = encDict.get(import_pdf_lib.PDFName.of("Length"));
5181
+ const keyLength = lenObj instanceof import_pdf_lib.PDFNumber ? lenObj.asNumber() : version >= 2 ? 128 : 40;
5182
+ const pObj = encDict.get(import_pdf_lib.PDFName.of("P"));
5183
+ const pSigned = pObj instanceof import_pdf_lib.PDFNumber ? pObj.asNumber() | 0 : -4;
5184
+ const oObj = encDict.get(import_pdf_lib.PDFName.of("O"));
5185
+ const oBytes = oObj instanceof import_pdf_lib.PDFHexString || oObj instanceof import_pdf_lib.PDFString ? extractPdfStringRawBytes(oObj) : new Uint8Array(0);
5186
+ const uObj = encDict.get(import_pdf_lib.PDFName.of("U"));
5187
+ const uBytes = uObj instanceof import_pdf_lib.PDFHexString || uObj instanceof import_pdf_lib.PDFString ? extractPdfStringRawBytes(uObj) : new Uint8Array(0);
5188
+ let fileId = new Uint8Array(0);
5189
+ const idEntry = doc.context.trailerInfo.ID;
5190
+ const idArr = idEntry instanceof import_pdf_lib.PDFArray ? idEntry : doc.context.lookupMaybe(idEntry, import_pdf_lib.PDFArray);
5191
+ if (idArr && idArr.size() > 0) {
5192
+ const first = idArr.get(0);
5193
+ if (first instanceof import_pdf_lib.PDFHexString || first instanceof import_pdf_lib.PDFString) {
5194
+ fileId = extractPdfStringRawBytes(first);
5195
+ }
5091
5196
  }
5092
- let j = 0;
5093
- for (let i2 = 0; i2 < 256; i2++) {
5094
- j = j + S[i2] + key[i2 % keyLen] & 255;
5095
- const tmp = S[i2];
5096
- S[i2] = S[j];
5097
- S[j] = tmp;
5197
+ return {
5198
+ filter,
5199
+ version,
5200
+ revision,
5201
+ keyLength,
5202
+ pSigned,
5203
+ oBytes,
5204
+ uBytes,
5205
+ fileId
5206
+ };
5207
+ }
5208
+ function inspectPdfEncryption(pdfBytes) {
5209
+ const meta = parseRawEncryptFromPdfBytes(pdfBytes);
5210
+ if (!meta) {
5211
+ return {
5212
+ encrypted: false,
5213
+ requiresOpenPassword: false,
5214
+ permissions: { ...DEFAULT_ALL_PERMISSIONS }
5215
+ };
5098
5216
  }
5099
- const out = new Uint8Array(data.byteLength);
5100
- let i = 0;
5101
- j = 0;
5102
- for (let k = 0; k < data.byteLength; k++) {
5103
- i = i + 1 & 255;
5104
- j = j + S[i] & 255;
5105
- const tmp = S[i];
5106
- S[i] = S[j];
5107
- S[j] = tmp;
5108
- out[k] = data[k] ^ S[S[i] + S[j] & 255];
5217
+ let requiresOpenPassword = true;
5218
+ if (meta.filter === "Standard" && (meta.version === 1 || meta.version === 2) && (meta.revision === 2 || meta.revision === 3) && meta.oBytes.byteLength >= 32 && meta.uBytes.byteLength >= 16) {
5219
+ const emptyKey = authenticatePaddedUserPassword(
5220
+ padPdfPassword(""),
5221
+ meta.oBytes,
5222
+ meta.uBytes,
5223
+ meta.pSigned,
5224
+ meta.fileId,
5225
+ meta.revision,
5226
+ meta.keyLength
5227
+ );
5228
+ requiresOpenPassword = emptyKey === null;
5109
5229
  }
5110
- return out;
5230
+ return {
5231
+ encrypted: true,
5232
+ requiresOpenPassword,
5233
+ filter: meta.filter,
5234
+ version: meta.version,
5235
+ revision: meta.revision,
5236
+ keyLength: meta.keyLength,
5237
+ permissionFlagsRaw: meta.pSigned,
5238
+ permissions: decodePdfPermissionFlags(meta.pSigned, meta.revision)
5239
+ };
5111
5240
  }
5112
- function bytesToHex(bytes) {
5113
- let hex = "";
5114
- for (let i = 0; i < bytes.byteLength; i++) {
5115
- hex += bytes[i].toString(16).padStart(2, "0").toUpperCase();
5241
+ async function decryptPdfBytes(pdfBytes, password) {
5242
+ let meta = parseRawEncryptFromPdfBytes(pdfBytes);
5243
+ const doc = await import_pdf_lib.PDFDocument.load(pdfBytes, {
5244
+ ignoreEncryption: true,
5245
+ updateMetadata: false
5246
+ });
5247
+ if (!meta && doc.isEncrypted) {
5248
+ meta = extractEncryptMetadataFromDoc(doc);
5116
5249
  }
5117
- return hex;
5118
- }
5119
- function hexToBytes(hexRaw) {
5120
- const cleaned = hexRaw.replace(/\s+/g, "");
5121
- const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
5122
- const out = new Uint8Array(padded.length / 2);
5123
- for (let i = 0; i < out.byteLength; i++) {
5124
- out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16) || 0;
5250
+ if (!meta) {
5251
+ return pdfBytes.slice();
5125
5252
  }
5126
- return out;
5253
+ if (meta.filter !== "Standard" || meta.version !== 1 && meta.version !== 2 || meta.revision !== 2 && meta.revision !== 3) {
5254
+ throw new PdfSecurityError(
5255
+ "PDF_UNSUPPORTED_ENCRYPTION",
5256
+ `Unsupported PDF encryption handler (Filter=/${meta.filter}, V=${meta.version}, R=${meta.revision}).`
5257
+ );
5258
+ }
5259
+ const rev = meta.revision;
5260
+ const emptyOpenKey = authenticatePaddedUserPassword(
5261
+ padPdfPassword(""),
5262
+ meta.oBytes,
5263
+ meta.uBytes,
5264
+ meta.pSigned,
5265
+ meta.fileId,
5266
+ rev,
5267
+ meta.keyLength
5268
+ );
5269
+ const requiresOpenPassword = emptyOpenKey === null;
5270
+ const candidatePw = password ?? "";
5271
+ if (requiresOpenPassword && candidatePw.length === 0) {
5272
+ throw new PdfSecurityError(
5273
+ "PDF_PASSWORD_REQUIRED",
5274
+ "Encrypted PDF document requires an open password."
5275
+ );
5276
+ }
5277
+ let encryptionKey = null;
5278
+ if (candidatePw.length === 0 && emptyOpenKey) {
5279
+ encryptionKey = emptyOpenKey;
5280
+ } else {
5281
+ encryptionKey = authenticatePaddedUserPassword(
5282
+ padPdfPassword(candidatePw),
5283
+ meta.oBytes,
5284
+ meta.uBytes,
5285
+ meta.pSigned,
5286
+ meta.fileId,
5287
+ rev,
5288
+ meta.keyLength
5289
+ );
5290
+ if (!encryptionKey) {
5291
+ encryptionKey = authenticateOwnerPassword(
5292
+ candidatePw,
5293
+ meta.oBytes,
5294
+ meta.uBytes,
5295
+ meta.pSigned,
5296
+ meta.fileId,
5297
+ rev,
5298
+ meta.keyLength
5299
+ );
5300
+ }
5301
+ }
5302
+ if (!encryptionKey) {
5303
+ throw new PdfSecurityError(
5304
+ "PDF_INVALID_PASSWORD",
5305
+ "Incorrect password for encrypted PDF document."
5306
+ );
5307
+ }
5308
+ const encryptRef = doc.context.trailerInfo.Encrypt instanceof import_pdf_lib.PDFRef ? doc.context.trailerInfo.Encrypt : null;
5309
+ const idRef = doc.context.trailerInfo.ID instanceof import_pdf_lib.PDFRef ? doc.context.trailerInfo.ID : null;
5310
+ for (const [ref, obj] of doc.context.enumerateIndirectObjects()) {
5311
+ if (encryptRef && ref.objectNumber === encryptRef.objectNumber && ref.generationNumber === encryptRef.generationNumber) {
5312
+ continue;
5313
+ }
5314
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
5315
+ continue;
5316
+ }
5317
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
5318
+ if (obj instanceof import_pdf_lib.PDFRawStream) {
5319
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
5320
+ const decryptedStream = rc4Bytes(objKey, obj.contents);
5321
+ obj.dict.set(import_pdf_lib.PDFName.of("Length"), import_pdf_lib.PDFNumber.of(decryptedStream.byteLength));
5322
+ doc.context.assign(ref, import_pdf_lib.PDFRawStream.of(obj.dict, decryptedStream));
5323
+ } else if (obj instanceof import_pdf_lib.PDFStream) {
5324
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
5325
+ const decryptedStream = rc4Bytes(objKey, obj.getContents());
5326
+ obj.dict.set(import_pdf_lib.PDFName.of("Length"), import_pdf_lib.PDFNumber.of(decryptedStream.byteLength));
5327
+ doc.context.assign(ref, import_pdf_lib.PDFRawStream.of(obj.dict, decryptedStream));
5328
+ } else {
5329
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
5330
+ if (next !== obj) {
5331
+ doc.context.assign(ref, next);
5332
+ }
5333
+ }
5334
+ }
5335
+ delete doc.context.trailerInfo.Encrypt;
5336
+ if (encryptRef) {
5337
+ doc.context.delete(encryptRef);
5338
+ }
5339
+ return await doc.save({ useObjectStreams: false, updateFieldAppearances: false });
5127
5340
  }
5128
- function encodePasswordToBytes(password) {
5129
- if (!password) return new Uint8Array(0);
5130
- let hasHighCodePoint = false;
5131
- for (let i = 0; i < password.length; i++) {
5132
- if (password.charCodeAt(i) > 255) {
5133
- hasHighCodePoint = true;
5134
- break;
5341
+
5342
+ // src/exporter/pdf-native-text.ts
5343
+ var WIN_ANSI_EXTENDED = {
5344
+ 128: 8364,
5345
+ 130: 8218,
5346
+ 131: 402,
5347
+ 132: 8222,
5348
+ 133: 8230,
5349
+ 134: 8224,
5350
+ 135: 8225,
5351
+ 136: 710,
5352
+ 137: 8240,
5353
+ 138: 352,
5354
+ 139: 8249,
5355
+ 140: 338,
5356
+ 142: 381,
5357
+ 145: 8216,
5358
+ 146: 8217,
5359
+ 147: 8220,
5360
+ 148: 8221,
5361
+ 149: 8226,
5362
+ 150: 8211,
5363
+ 151: 8212,
5364
+ 152: 732,
5365
+ 153: 8482,
5366
+ 154: 353,
5367
+ 155: 8250,
5368
+ 156: 339,
5369
+ 158: 382,
5370
+ 159: 376
5371
+ };
5372
+ function multiplyPdfMatrix(m1, m2) {
5373
+ return [
5374
+ m1[0] * m2[0] + m1[1] * m2[2],
5375
+ m1[0] * m2[1] + m1[1] * m2[3],
5376
+ m1[2] * m2[0] + m1[3] * m2[2],
5377
+ m1[2] * m2[1] + m1[3] * m2[3],
5378
+ m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
5379
+ m1[4] * m2[1] + m1[5] * m2[3] + m2[5]
5380
+ ];
5381
+ }
5382
+ function decodeSingleStreamObject(doc, objOrRef) {
5383
+ const resolved = objOrRef instanceof import_pdf_lib2.PDFRef ? doc.context.lookup(objOrRef) : objOrRef;
5384
+ if (!resolved) return new Uint8Array(0);
5385
+ if (resolved instanceof import_pdf_lib2.PDFRawStream) {
5386
+ try {
5387
+ const decoded = (0, import_pdf_lib2.decodePDFRawStream)(resolved).decode();
5388
+ return decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded);
5389
+ } catch {
5390
+ return resolved.contents;
5135
5391
  }
5136
5392
  }
5137
- if (hasHighCodePoint) {
5138
- return new TextEncoder().encode(password);
5393
+ if (resolved instanceof import_pdf_lib2.PDFStream) {
5394
+ const anyStream = resolved;
5395
+ if (typeof anyStream.getUnencodedContents === "function") {
5396
+ return anyStream.getUnencodedContents();
5397
+ }
5398
+ if (typeof anyStream.getContents === "function") {
5399
+ return anyStream.getContents();
5400
+ }
5139
5401
  }
5140
- const out = new Uint8Array(password.length);
5141
- for (let i = 0; i < password.length; i++) {
5142
- out[i] = password.charCodeAt(i) & 255;
5402
+ return new Uint8Array(0);
5403
+ }
5404
+ function decodeContentsEntry(doc, contentsEntry) {
5405
+ const resolved = contentsEntry instanceof import_pdf_lib2.PDFRef ? doc.context.lookup(contentsEntry) : contentsEntry;
5406
+ if (!resolved) return new Uint8Array(0);
5407
+ if (resolved instanceof import_pdf_lib2.PDFArray) {
5408
+ const parts = [];
5409
+ let total = 0;
5410
+ for (let i = 0; i < resolved.size(); i++) {
5411
+ const part = decodeSingleStreamObject(doc, resolved.get(i));
5412
+ if (part.byteLength > 0) {
5413
+ parts.push(part);
5414
+ total += part.byteLength + 1;
5415
+ }
5416
+ }
5417
+ const merged = new Uint8Array(total);
5418
+ let offset = 0;
5419
+ for (const part of parts) {
5420
+ merged.set(part, offset);
5421
+ offset += part.byteLength;
5422
+ merged[offset++] = 10;
5423
+ }
5424
+ return merged;
5143
5425
  }
5144
- return out;
5426
+ return decodeSingleStreamObject(doc, resolved);
5145
5427
  }
5146
- function padPdfPassword(password) {
5147
- const raw = password instanceof Uint8Array ? password : encodePasswordToBytes(password);
5148
- const out = new Uint8Array(32);
5149
- const copyLen = Math.min(32, raw.byteLength);
5150
- out.set(raw.subarray(0, copyLen), 0);
5151
- if (copyLen < 32) {
5152
- out.set(PDF_PASSWORD_PADDING.subarray(0, 32 - copyLen), copyLen);
5428
+ function bytesToLatin1String(bytes) {
5429
+ let out = "";
5430
+ const chunk = 16384;
5431
+ for (let i = 0; i < bytes.length; i += chunk) {
5432
+ out += String.fromCharCode(...bytes.subarray(i, i + chunk));
5153
5433
  }
5154
5434
  return out;
5155
5435
  }
5156
- function encodePdfPermissionFlags(permissions, revision = 3) {
5157
- const allowPrint = permissions?.print !== false;
5158
- const allowModify = permissions?.modify !== false;
5159
- const allowCopy = permissions?.copy !== false;
5160
- const allowAnnotate = permissions?.annotate !== false;
5161
- const allowFillForms = permissions?.fillForms !== false;
5162
- const allowAssemble = permissions?.assemble !== false;
5163
- const allowHighResPrint = permissions?.highResPrint !== void 0 ? Boolean(permissions.highResPrint) : allowPrint;
5164
- let mask = 4294963392 | 1 << 9;
5165
- if (allowPrint) mask |= 1 << 2;
5166
- if (allowModify) mask |= 1 << 3;
5167
- if (allowCopy) mask |= 1 << 4;
5168
- if (allowAnnotate) mask |= 1 << 5;
5169
- if (revision >= 3) {
5170
- if (allowFillForms) mask |= 1 << 8;
5171
- if (allowAssemble) mask |= 1 << 10;
5172
- if (allowHighResPrint && allowPrint) mask |= 1 << 11;
5173
- } else {
5174
- mask |= 1 << 8 | 1 << 10 | 1 << 11;
5436
+ function decodeUtf16BeHex(hex) {
5437
+ const cleaned = hex.replace(/\s+/g, "");
5438
+ if (!cleaned) return "";
5439
+ if (cleaned.length <= 2) {
5440
+ return String.fromCodePoint(parseInt(cleaned, 16) || 32);
5175
5441
  }
5176
- return mask | 0;
5177
- }
5178
- function decodePdfPermissionFlags(pMask, revision = 3) {
5179
- const print = (pMask & 1 << 2) !== 0;
5180
- const modify = (pMask & 1 << 3) !== 0;
5181
- const copy = (pMask & 1 << 4) !== 0;
5182
- const annotate = (pMask & 1 << 5) !== 0;
5183
- const fillForms = revision >= 3 ? (pMask & 1 << 8) !== 0 : annotate;
5184
- const assemble = revision >= 3 ? (pMask & 1 << 10) !== 0 : modify;
5185
- const highResPrint = revision >= 3 ? print && (pMask & 1 << 11) !== 0 : print;
5186
- return {
5187
- print,
5188
- highResPrint,
5189
- modify,
5190
- copy,
5191
- annotate,
5192
- fillForms,
5193
- assemble
5194
- };
5195
- }
5196
- function isPdfSecurityActive(security) {
5197
- if (!security || security.enabled === false) return false;
5198
- if (security.enabled === true) return true;
5199
- if (security.userPassword && security.userPassword.length > 0) return true;
5200
- if (security.ownerPassword && security.ownerPassword.length > 0) return true;
5201
- if (security.permissions && Object.keys(security.permissions).length > 0) return true;
5202
- return false;
5442
+ const codeUnits = [];
5443
+ for (let i = 0; i + 3 < cleaned.length; i += 4) {
5444
+ codeUnits.push(parseInt(cleaned.slice(i, i + 4), 16));
5445
+ }
5446
+ return String.fromCharCode(...codeUnits);
5203
5447
  }
5204
- function computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLengthBits) {
5205
- const effectiveOwner = ownerPassword || userPassword || "";
5206
- const ownerPad = padPdfPassword(effectiveOwner);
5207
- let hash = md5Bytes(ownerPad);
5208
- if (revision >= 3) {
5209
- for (let i = 0; i < 50; i++) {
5210
- hash = md5Bytes(hash);
5448
+ function parseToUnicodeCMap(cmapText) {
5449
+ const map = /* @__PURE__ */ new Map();
5450
+ let bytesPerCode = 1;
5451
+ const bfCharRe = /beginbfchar([\s\S]*?)endbfchar/g;
5452
+ let blockMatch;
5453
+ while ((blockMatch = bfCharRe.exec(cmapText)) !== null) {
5454
+ const body = blockMatch[1];
5455
+ const pairRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
5456
+ let m;
5457
+ while ((m = pairRe.exec(body)) !== null) {
5458
+ if (m[1].length >= 4) bytesPerCode = 2;
5459
+ const srcCode = parseInt(m[1], 16);
5460
+ const dstStr = decodeUtf16BeHex(m[2]);
5461
+ if (!Number.isNaN(srcCode) && dstStr) {
5462
+ map.set(srcCode, dstStr);
5463
+ }
5211
5464
  }
5212
5465
  }
5213
- const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5214
- const userPad = padPdfPassword(userPassword);
5215
- let encrypted = rc4Bytes(hash.subarray(0, keyByteLen), userPad);
5216
- if (revision >= 3) {
5217
- const derivedKey = new Uint8Array(keyByteLen);
5218
- for (let iter = 1; iter <= 19; iter++) {
5219
- for (let k = 0; k < keyByteLen; k++) {
5220
- derivedKey[k] = hash[k] ^ iter;
5466
+ const bfRangeRe = /beginbfrange([\s\S]*?)endbfrange/g;
5467
+ while ((blockMatch = bfRangeRe.exec(cmapText)) !== null) {
5468
+ const body = blockMatch[1];
5469
+ const arrayRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([^\]]*)\]/g;
5470
+ let am;
5471
+ while ((am = arrayRangeRe.exec(body)) !== null) {
5472
+ if (am[1].length >= 4) bytesPerCode = 2;
5473
+ const start = parseInt(am[1], 16);
5474
+ const end = parseInt(am[2], 16);
5475
+ const targets = Array.from(am[3].matchAll(/<([0-9A-Fa-f]+)>/g)).map((x) => decodeUtf16BeHex(x[1]));
5476
+ for (let code = start; code <= end && code - start < targets.length; code++) {
5477
+ if (targets[code - start]) {
5478
+ map.set(code, targets[code - start]);
5479
+ }
5221
5480
  }
5222
- encrypted = rc4Bytes(derivedKey, encrypted);
5223
5481
  }
5224
- }
5225
- return encrypted;
5226
- }
5227
- function computeFileEncryptionKeyFromPadded(paddedUserPassword, oValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5228
- const buf = new Uint8Array(32 + oValue.byteLength + 4 + fileId.byteLength);
5229
- let offset = 0;
5230
- buf.set(paddedUserPassword.subarray(0, 32), offset);
5231
- offset += 32;
5232
- buf.set(oValue, offset);
5233
- offset += oValue.byteLength;
5234
- buf[offset++] = pFlagsSigned & 255;
5235
- buf[offset++] = pFlagsSigned >>> 8 & 255;
5236
- buf[offset++] = pFlagsSigned >>> 16 & 255;
5237
- buf[offset++] = pFlagsSigned >>> 24 & 255;
5238
- buf.set(fileId, offset);
5239
- let hash = md5Bytes(buf);
5240
- const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5241
- if (revision >= 3) {
5242
- for (let i = 0; i < 50; i++) {
5243
- hash = md5Bytes(hash.subarray(0, keyByteLen));
5482
+ const directRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
5483
+ let dm;
5484
+ while ((dm = directRangeRe.exec(body)) !== null) {
5485
+ if (dm[1].length >= 4) bytesPerCode = 2;
5486
+ const start = parseInt(dm[1], 16);
5487
+ const end = parseInt(dm[2], 16);
5488
+ const baseStr = decodeUtf16BeHex(dm[3]);
5489
+ const baseCp = baseStr.codePointAt(0) ?? 32;
5490
+ if (end >= start && end - start <= 16384) {
5491
+ for (let code = start; code <= end; code++) {
5492
+ map.set(code, String.fromCodePoint(baseCp + (code - start)));
5493
+ }
5494
+ }
5244
5495
  }
5245
5496
  }
5246
- return hash.subarray(0, keyByteLen);
5497
+ return { map, bytesPerCode };
5247
5498
  }
5248
- function computeUserPasswordValue(encryptionKey, fileId, revision) {
5249
- if (revision === 2) {
5250
- return rc4Bytes(encryptionKey, PDF_PASSWORD_PADDING);
5251
- }
5252
- const hashInput = new Uint8Array(32 + fileId.byteLength);
5253
- hashInput.set(PDF_PASSWORD_PADDING, 0);
5254
- hashInput.set(fileId, 32);
5255
- let check = rc4Bytes(encryptionKey, md5Bytes(hashInput));
5256
- const keyLen = encryptionKey.byteLength;
5257
- const derivedKey = new Uint8Array(keyLen);
5258
- for (let iter = 1; iter <= 19; iter++) {
5259
- for (let k = 0; k < keyLen; k++) {
5260
- derivedKey[k] = encryptionKey[k] ^ iter;
5499
+ function extractResourcesFontMap(doc, resourcesDict) {
5500
+ const fonts = /* @__PURE__ */ new Map();
5501
+ if (!resourcesDict) return fonts;
5502
+ const fontObj = resourcesDict.get(import_pdf_lib2.PDFName.of("Font"));
5503
+ const fontDict = doc.context.lookupMaybe(fontObj, import_pdf_lib2.PDFDict);
5504
+ if (!fontDict) return fonts;
5505
+ for (const [keyObj, valObj] of fontDict.entries()) {
5506
+ const cleanKey = keyObj.decodeText ? keyObj.decodeText() : keyObj.asString().replace(/^\//, "");
5507
+ const fDict = doc.context.lookupMaybe(valObj, import_pdf_lib2.PDFDict);
5508
+ if (!fDict) continue;
5509
+ const subtypeObj = fDict.get(import_pdf_lib2.PDFName.of("Subtype"));
5510
+ const subtype = subtypeObj instanceof import_pdf_lib2.PDFName ? subtypeObj.decodeText() : "";
5511
+ const encObj = fDict.get(import_pdf_lib2.PDFName.of("Encoding"));
5512
+ const encoding = encObj instanceof import_pdf_lib2.PDFName ? encObj.decodeText() : "";
5513
+ const isUtf16Cid = /UTF16|UCS2/i.test(encoding);
5514
+ let toUnicode = /* @__PURE__ */ new Map();
5515
+ let bytesPerCode = subtype === "Type0" ? 2 : 1;
5516
+ const toUniEntry = fDict.get(import_pdf_lib2.PDFName.of("ToUnicode"));
5517
+ if (toUniEntry) {
5518
+ const cmapBytes = decodeSingleStreamObject(doc, toUniEntry);
5519
+ if (cmapBytes.byteLength > 0) {
5520
+ const parsed = parseToUnicodeCMap(bytesToLatin1String(cmapBytes));
5521
+ toUnicode = parsed.map;
5522
+ if (parsed.bytesPerCode === 2 || subtype === "Type0") {
5523
+ bytesPerCode = 2;
5524
+ }
5525
+ }
5261
5526
  }
5262
- check = rc4Bytes(derivedKey, check);
5527
+ fonts.set(cleanKey, {
5528
+ subtype,
5529
+ encoding,
5530
+ isUtf16Cid,
5531
+ bytesPerCode,
5532
+ toUnicode
5533
+ });
5263
5534
  }
5264
- const out = new Uint8Array(32);
5265
- out.set(check.subarray(0, 16), 0);
5266
- out.set(PDF_PASSWORD_PADDING.subarray(0, 16), 16);
5267
- return out;
5535
+ return fonts;
5268
5536
  }
5269
- function authenticatePaddedUserPassword(paddedPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5270
- const candidateKey = computeFileEncryptionKeyFromPadded(
5271
- paddedPassword,
5272
- oValue,
5273
- pFlagsSigned,
5274
- fileId,
5275
- revision,
5276
- keyLengthBits
5277
- );
5278
- const expectedU = computeUserPasswordValue(candidateKey, fileId, revision);
5279
- const compareLen = revision >= 3 ? 16 : 32;
5280
- if (uValue.byteLength < compareLen) return null;
5281
- let diff = 0;
5282
- for (let i = 0; i < compareLen; i++) {
5283
- diff |= expectedU[i] ^ uValue[i];
5537
+ function decodeWinAnsiBytes(bytes) {
5538
+ let out = "";
5539
+ for (let i = 0; i < bytes.length; i++) {
5540
+ const b = bytes[i];
5541
+ if (b in WIN_ANSI_EXTENDED) {
5542
+ out += String.fromCharCode(WIN_ANSI_EXTENDED[b]);
5543
+ } else if (b >= 32 || b === 9 || b === 10 || b === 13) {
5544
+ out += String.fromCharCode(b);
5545
+ }
5284
5546
  }
5285
- return diff === 0 ? candidateKey : null;
5547
+ return out;
5286
5548
  }
5287
- function authenticateOwnerPassword(ownerPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5288
- const ownerPad = padPdfPassword(ownerPassword);
5289
- let hash = md5Bytes(ownerPad);
5290
- if (revision >= 3) {
5291
- for (let i = 0; i < 50; i++) {
5292
- hash = md5Bytes(hash);
5549
+ function decodeUtf16BeBytes(bytes, startOffset = 0) {
5550
+ const units = [];
5551
+ for (let i = startOffset; i + 1 < bytes.length; i += 2) {
5552
+ const u = bytes[i] << 8 | bytes[i + 1];
5553
+ if (u !== 65279 && u > 0) {
5554
+ units.push(u);
5293
5555
  }
5294
5556
  }
5295
- const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5296
- let recoveredUserPad;
5297
- if (revision >= 3) {
5298
- recoveredUserPad = oValue.slice(0, 32);
5299
- const derivedKey = new Uint8Array(keyByteLen);
5300
- for (let iter = 19; iter >= 0; iter--) {
5301
- for (let k = 0; k < keyByteLen; k++) {
5302
- derivedKey[k] = hash[k] ^ iter;
5557
+ return String.fromCharCode(...units);
5558
+ }
5559
+ function decodePdfStringBytes(bytes, fontInfo) {
5560
+ if (bytes.length === 0) return { text: "", glyphCount: 0 };
5561
+ if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) {
5562
+ const text2 = decodeUtf16BeBytes(bytes, 2);
5563
+ return { text: text2, glyphCount: text2.length };
5564
+ }
5565
+ if (fontInfo && fontInfo.toUnicode.size > 0) {
5566
+ if (fontInfo.bytesPerCode === 2 && bytes.length >= 2) {
5567
+ let out2 = "";
5568
+ let count = 0;
5569
+ for (let i = 0; i + 1 < bytes.length; i += 2) {
5570
+ const code = bytes[i] << 8 | bytes[i + 1];
5571
+ count++;
5572
+ const mapped = fontInfo.toUnicode.get(code);
5573
+ if (mapped !== void 0) {
5574
+ out2 += mapped;
5575
+ } else if (code >= 32 && code !== 65279) {
5576
+ out2 += String.fromCharCode(code);
5577
+ }
5303
5578
  }
5304
- recoveredUserPad = rc4Bytes(derivedKey, recoveredUserPad);
5579
+ return { text: out2, glyphCount: count };
5305
5580
  }
5306
- } else {
5307
- recoveredUserPad = rc4Bytes(hash.subarray(0, 5), oValue.subarray(0, 32));
5581
+ let out = "";
5582
+ for (let i = 0; i < bytes.length; i++) {
5583
+ const code = bytes[i];
5584
+ const mapped = fontInfo.toUnicode.get(code);
5585
+ if (mapped !== void 0) {
5586
+ out += mapped;
5587
+ } else if (code in WIN_ANSI_EXTENDED) {
5588
+ out += String.fromCharCode(WIN_ANSI_EXTENDED[code]);
5589
+ } else if (code >= 32) {
5590
+ out += String.fromCharCode(code);
5591
+ }
5592
+ }
5593
+ return { text: out, glyphCount: bytes.length };
5308
5594
  }
5309
- return authenticatePaddedUserPassword(
5310
- recoveredUserPad,
5311
- oValue,
5312
- uValue,
5313
- pFlagsSigned,
5314
- fileId,
5315
- revision,
5316
- keyLengthBits
5317
- );
5595
+ if (fontInfo?.isUtf16Cid || fontInfo?.subtype === "Type0" && bytes.length % 2 === 0) {
5596
+ const text2 = decodeUtf16BeBytes(bytes, 0);
5597
+ return { text: text2, glyphCount: Math.floor(bytes.length / 2) };
5598
+ }
5599
+ const text = decodeWinAnsiBytes(bytes);
5600
+ return { text, glyphCount: bytes.length };
5318
5601
  }
5319
- function buildObjectEncryptionKey(encryptionKey, objectNumber, generationNumber) {
5320
- const n = encryptionKey.byteLength;
5321
- const buf = new Uint8Array(n + 5);
5322
- buf.set(encryptionKey, 0);
5323
- buf[n] = objectNumber & 255;
5324
- buf[n + 1] = objectNumber >>> 8 & 255;
5325
- buf[n + 2] = objectNumber >>> 16 & 255;
5326
- buf[n + 3] = generationNumber & 255;
5327
- buf[n + 4] = generationNumber >>> 8 & 255;
5328
- const digest = md5Bytes(buf);
5329
- return digest.subarray(0, Math.min(n + 5, 16));
5602
+ function isPdfWhitespace(ch) {
5603
+ return ch === 0 || ch === 9 || ch === 10 || ch === 12 || ch === 13 || ch === 32;
5330
5604
  }
5331
- function decodePdfLiteralBodyBytes(body) {
5332
- const bytes = [];
5333
- for (let i = 0; i < body.length; i++) {
5334
- const ch = body.charCodeAt(i) & 255;
5335
- if (ch !== 92) {
5336
- bytes.push(ch);
5337
- continue;
5605
+ function isPdfDelimiter(ch) {
5606
+ return ch === 40 || // (
5607
+ ch === 41 || // )
5608
+ ch === 60 || // <
5609
+ ch === 62 || // >
5610
+ ch === 91 || // [
5611
+ ch === 93 || // ]
5612
+ ch === 123 || // {
5613
+ ch === 125 || // }
5614
+ ch === 47 || // /
5615
+ ch === 37;
5616
+ }
5617
+ function hexCharVal(c) {
5618
+ if (c >= 48 && c <= 57) return c - 48;
5619
+ if (c >= 65 && c <= 70) return c - 65 + 10;
5620
+ if (c >= 97 && c <= 102) return c - 97 + 10;
5621
+ return -1;
5622
+ }
5623
+ function tokenizeContentStream(bytes) {
5624
+ const len = bytes.length;
5625
+ let pos = 0;
5626
+ const readToken = () => {
5627
+ while (pos < len) {
5628
+ const c = bytes[pos];
5629
+ if (isPdfWhitespace(c)) {
5630
+ pos++;
5631
+ continue;
5632
+ }
5633
+ if (c === 37) {
5634
+ while (pos < len && bytes[pos] !== 10 && bytes[pos] !== 13) {
5635
+ pos++;
5636
+ }
5637
+ continue;
5638
+ }
5639
+ break;
5338
5640
  }
5339
- if (i + 1 >= body.length) break;
5340
- const next = body.charCodeAt(++i) & 255;
5341
- if (next === 13) {
5342
- if (i + 1 < body.length && (body.charCodeAt(i + 1) & 255) === 10) i++;
5343
- } else if (next === 10) {
5344
- } else if (next === 110) {
5345
- bytes.push(10);
5346
- } else if (next === 114) {
5347
- bytes.push(13);
5348
- } else if (next === 116) {
5349
- bytes.push(9);
5350
- } else if (next === 98) {
5351
- bytes.push(8);
5352
- } else if (next === 102) {
5353
- bytes.push(12);
5354
- } else if (next >= 48 && next <= 55) {
5355
- let oct = String.fromCharCode(next);
5356
- for (let k = 0; k < 2 && i + 1 < body.length; k++) {
5357
- const peek = body.charCodeAt(i + 1) & 255;
5358
- if (peek >= 48 && peek <= 55) {
5359
- oct += String.fromCharCode(peek);
5360
- i++;
5641
+ if (pos >= len) return null;
5642
+ const start = pos;
5643
+ const ch = bytes[pos];
5644
+ if (ch === 40) {
5645
+ pos++;
5646
+ let depth = 1;
5647
+ const out = [];
5648
+ while (pos < len && depth > 0) {
5649
+ const b = bytes[pos++];
5650
+ if (b === 92) {
5651
+ if (pos >= len) break;
5652
+ const next = bytes[pos++];
5653
+ if (next === 110) out.push(10);
5654
+ else if (next === 114) out.push(13);
5655
+ else if (next === 116) out.push(9);
5656
+ else if (next === 98) out.push(8);
5657
+ else if (next === 102) out.push(12);
5658
+ else if (next === 40 || next === 41 || next === 92) out.push(next);
5659
+ else if (next === 13) {
5660
+ if (pos < len && bytes[pos] === 10) pos++;
5661
+ } else if (next === 10) {
5662
+ } else if (next >= 48 && next <= 55) {
5663
+ let oct = next - 48;
5664
+ for (let k = 0; k < 2 && pos < len && bytes[pos] >= 48 && bytes[pos] <= 55; k++) {
5665
+ oct = (oct << 3) + (bytes[pos++] - 48);
5666
+ }
5667
+ out.push(oct & 255);
5668
+ } else {
5669
+ out.push(next);
5670
+ }
5671
+ } else if (b === 40) {
5672
+ depth++;
5673
+ out.push(b);
5674
+ } else if (b === 41) {
5675
+ depth--;
5676
+ if (depth > 0) out.push(b);
5361
5677
  } else {
5362
- break;
5678
+ out.push(b);
5363
5679
  }
5364
5680
  }
5365
- bytes.push(parseInt(oct, 8) & 255);
5366
- } else {
5367
- bytes.push(next);
5681
+ return { type: "literal", bytes: new Uint8Array(out), start, end: pos };
5368
5682
  }
5369
- }
5370
- return new Uint8Array(bytes);
5371
- }
5372
- function extractPdfStringRawBytes(strObj) {
5373
- if (strObj instanceof import_pdf_lib2.PDFHexString) {
5374
- return strObj.asBytes();
5375
- }
5376
- const serialized = strObj.asString();
5377
- const inner = serialized.startsWith("(") && serialized.endsWith(")") ? serialized.slice(1, -1) : serialized;
5378
- return decodePdfLiteralBodyBytes(inner);
5379
- }
5380
- function isSignatureDict(dict) {
5381
- const typeVal = dict.get(import_pdf_lib2.PDFName.of("Type"));
5382
- if (typeVal instanceof import_pdf_lib2.PDFName && typeVal.asString() === "/Sig") return true;
5383
- const ftVal = dict.get(import_pdf_lib2.PDFName.of("FT"));
5384
- if (ftVal instanceof import_pdf_lib2.PDFName && ftVal.asString() === "/Sig") return true;
5385
- return false;
5386
- }
5387
- function transformPdfObjectStringsWithRc4(obj, objKey) {
5388
- if (obj instanceof import_pdf_lib2.PDFHexString || obj instanceof import_pdf_lib2.PDFString) {
5389
- const raw = extractPdfStringRawBytes(obj);
5390
- const transformed = rc4Bytes(objKey, raw);
5391
- return import_pdf_lib2.PDFHexString.of(bytesToHex(transformed));
5392
- }
5393
- if (obj instanceof import_pdf_lib2.PDFArray) {
5394
- for (let i = 0; i < obj.size(); i++) {
5395
- const item = obj.get(i);
5396
- const next = transformPdfObjectStringsWithRc4(item, objKey);
5397
- if (next !== item) {
5398
- obj.set(i, next);
5683
+ if (ch === 60) {
5684
+ if (pos + 1 < len && bytes[pos + 1] === 60) {
5685
+ pos += 2;
5686
+ return { type: "dictStart", start, end: pos };
5687
+ }
5688
+ pos++;
5689
+ const nibbles = [];
5690
+ while (pos < len && bytes[pos] !== 62) {
5691
+ const hv = hexCharVal(bytes[pos++]);
5692
+ if (hv >= 0) nibbles.push(hv);
5693
+ }
5694
+ if (pos < len && bytes[pos] === 62) pos++;
5695
+ if (nibbles.length % 2 === 1) nibbles.push(0);
5696
+ const hexBytes = new Uint8Array(nibbles.length / 2);
5697
+ for (let i = 0; i < hexBytes.length; i++) {
5698
+ hexBytes[i] = nibbles[i * 2] << 4 | nibbles[i * 2 + 1];
5699
+ }
5700
+ return { type: "hex", bytes: hexBytes, start, end: pos };
5701
+ }
5702
+ if (ch === 62) {
5703
+ if (pos + 1 < len && bytes[pos + 1] === 62) {
5704
+ pos += 2;
5705
+ return { type: "dictEnd", start, end: pos };
5706
+ }
5707
+ pos++;
5708
+ return { type: "op", op: ">", start, end: pos };
5709
+ }
5710
+ if (ch === 91) {
5711
+ pos++;
5712
+ const items = [];
5713
+ while (pos < len) {
5714
+ while (pos < len && isPdfWhitespace(bytes[pos])) pos++;
5715
+ if (pos < len && bytes[pos] === 93) {
5716
+ pos++;
5717
+ break;
5718
+ }
5719
+ const child = readToken();
5720
+ if (!child) break;
5721
+ items.push(child);
5399
5722
  }
5723
+ return { type: "array", items, start, end: pos };
5400
5724
  }
5401
- return obj;
5402
- }
5403
- if (obj instanceof import_pdf_lib2.PDFDict) {
5404
- const isSig = isSignatureDict(obj);
5405
- for (const [key, val] of obj.entries()) {
5406
- if (isSig && key.asString() === "/Contents") {
5407
- continue;
5408
- }
5409
- const next = transformPdfObjectStringsWithRc4(val, objKey);
5410
- if (next !== val) {
5411
- obj.set(key, next);
5412
- }
5725
+ if (ch === 93) {
5726
+ pos++;
5727
+ return { type: "op", op: "]", start, end: pos };
5413
5728
  }
5414
- return obj;
5415
- }
5416
- return obj;
5417
- }
5418
- function extractOrCreateDocumentFileId(pdfDoc) {
5419
- const existingId = pdfDoc.context.trailerInfo.ID;
5420
- if (existingId) {
5421
- const idArr = existingId instanceof import_pdf_lib2.PDFArray ? existingId : pdfDoc.context.lookupMaybe(existingId, import_pdf_lib2.PDFArray);
5422
- if (idArr && idArr.size() > 0) {
5423
- const first = idArr.get(0);
5424
- if (first instanceof import_pdf_lib2.PDFHexString || first instanceof import_pdf_lib2.PDFString) {
5425
- const bytes = extractPdfStringRawBytes(first);
5426
- if (bytes.byteLength > 0) {
5427
- const hex = bytesToHex(bytes);
5428
- pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
5429
- import_pdf_lib2.PDFHexString.of(hex),
5430
- import_pdf_lib2.PDFHexString.of(hex)
5431
- ]);
5432
- return bytes;
5729
+ if (ch === 47) {
5730
+ pos++;
5731
+ let name = "";
5732
+ while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
5733
+ if (bytes[pos] === 35 && pos + 2 < len) {
5734
+ const h1 = hexCharVal(bytes[pos + 1]);
5735
+ const h2 = hexCharVal(bytes[pos + 2]);
5736
+ if (h1 >= 0 && h2 >= 0) {
5737
+ name += String.fromCharCode(h1 << 4 | h2);
5738
+ pos += 3;
5739
+ continue;
5740
+ }
5433
5741
  }
5742
+ name += String.fromCharCode(bytes[pos++]);
5434
5743
  }
5744
+ return { type: "name", value: name, start, end: pos };
5435
5745
  }
5436
- }
5437
- const seedBytes = new Uint8Array(32);
5438
- if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
5439
- globalThis.crypto.getRandomValues(seedBytes);
5440
- } else {
5441
- const fallbackText = `univer-pdf-${Date.now()}-${Math.random()}-${pdfDoc.getPageCount()}`;
5442
- const enc = new TextEncoder().encode(fallbackText);
5443
- seedBytes.set(enc.subarray(0, Math.min(32, enc.byteLength)));
5444
- }
5445
- const fileId = md5Bytes(seedBytes);
5446
- const idHex = bytesToHex(fileId);
5447
- pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
5448
- import_pdf_lib2.PDFHexString.of(idHex),
5449
- import_pdf_lib2.PDFHexString.of(idHex)
5450
- ]);
5451
- return fileId;
5452
- }
5453
- async function applyPdfSecurityToDocument(pdfDoc, security) {
5454
- if (security.enabled === false) return;
5455
- await pdfDoc.flush();
5456
- const keyLength = security.keyLength === 40 ? 40 : 128;
5457
- const version = keyLength === 40 ? 1 : 2;
5458
- const revision = keyLength === 40 ? 2 : 3;
5459
- const userPassword = security.userPassword ?? "";
5460
- const ownerPassword = security.ownerPassword && security.ownerPassword.length > 0 ? security.ownerPassword : userPassword.length > 0 ? userPassword : "univer-pdf-owner-guard";
5461
- const fileId = extractOrCreateDocumentFileId(pdfDoc);
5462
- const pSigned = encodePdfPermissionFlags(security.permissions, revision);
5463
- const oBytes = computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLength);
5464
- const encryptionKey = computeFileEncryptionKeyFromPadded(
5465
- padPdfPassword(userPassword),
5466
- oBytes,
5467
- pSigned,
5468
- fileId,
5469
- revision,
5470
- keyLength
5471
- );
5472
- const uBytes = computeUserPasswordValue(encryptionKey, fileId, revision);
5473
- const idRef = pdfDoc.context.trailerInfo.ID instanceof import_pdf_lib2.PDFRef ? pdfDoc.context.trailerInfo.ID : null;
5474
- for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
5475
- if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
5476
- continue;
5746
+ let word = "";
5747
+ while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
5748
+ word += String.fromCharCode(bytes[pos++]);
5477
5749
  }
5478
- const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
5479
- if (obj instanceof import_pdf_lib2.PDFRawStream) {
5480
- transformPdfObjectStringsWithRc4(obj.dict, objKey);
5481
- const encryptedStream = rc4Bytes(objKey, obj.contents);
5482
- obj.dict.set(import_pdf_lib2.PDFName.of("Length"), import_pdf_lib2.PDFNumber.of(encryptedStream.byteLength));
5483
- pdfDoc.context.assign(ref, import_pdf_lib2.PDFRawStream.of(obj.dict, encryptedStream));
5484
- } else if (obj instanceof import_pdf_lib2.PDFStream) {
5485
- transformPdfObjectStringsWithRc4(obj.dict, objKey);
5486
- const encodedContents = obj.getContents();
5487
- const encryptedStream = rc4Bytes(objKey, encodedContents);
5488
- obj.dict.set(import_pdf_lib2.PDFName.of("Length"), import_pdf_lib2.PDFNumber.of(encryptedStream.byteLength));
5489
- pdfDoc.context.assign(ref, import_pdf_lib2.PDFRawStream.of(obj.dict, encryptedStream));
5490
- } else {
5491
- const next = transformPdfObjectStringsWithRc4(obj, objKey);
5492
- if (next !== obj) {
5493
- pdfDoc.context.assign(ref, next);
5750
+ if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(word)) {
5751
+ return { type: "number", num: parseFloat(word), start, end: pos };
5752
+ }
5753
+ if (word === "ID") {
5754
+ if (pos < len && isPdfWhitespace(bytes[pos])) pos++;
5755
+ while (pos + 1 < len) {
5756
+ if (bytes[pos] === 69 && bytes[pos + 1] === 73 && (pos === 0 || isPdfWhitespace(bytes[pos - 1])) && (pos + 2 >= len || isPdfWhitespace(bytes[pos + 2]) || isPdfDelimiter(bytes[pos + 2]))) {
5757
+ pos += 2;
5758
+ return { type: "op", op: "EI", start, end: pos };
5759
+ }
5760
+ pos++;
5494
5761
  }
5495
5762
  }
5763
+ return { type: "op", op: word, start, end: pos };
5764
+ };
5765
+ const tokens = [];
5766
+ let tok;
5767
+ while ((tok = readToken()) !== null) {
5768
+ tokens.push(tok);
5496
5769
  }
5497
- const encryptDict = pdfDoc.context.obj({
5498
- Filter: import_pdf_lib2.PDFName.of("Standard"),
5499
- V: import_pdf_lib2.PDFNumber.of(version),
5500
- R: import_pdf_lib2.PDFNumber.of(revision),
5501
- Length: import_pdf_lib2.PDFNumber.of(keyLength),
5502
- P: import_pdf_lib2.PDFNumber.of(pSigned),
5503
- O: import_pdf_lib2.PDFHexString.of(bytesToHex(oBytes)),
5504
- U: import_pdf_lib2.PDFHexString.of(bytesToHex(uBytes))
5505
- });
5506
- const encryptRef = pdfDoc.context.register(encryptDict);
5507
- pdfDoc.context.trailerInfo.Encrypt = encryptRef;
5508
- }
5509
- async function encryptPdfBytes(pdfBytes, security) {
5510
- if (!security || security.enabled === false) {
5511
- return pdfBytes.slice();
5512
- }
5513
- const cleanBytes = inspectPdfEncryption(pdfBytes).encrypted ? await decryptPdfBytes(pdfBytes, security.ownerPassword || security.userPassword || "") : pdfBytes;
5514
- const pdfDoc = await import_pdf_lib2.PDFDocument.load(cleanBytes, { updateMetadata: false });
5515
- await applyPdfSecurityToDocument(pdfDoc, security);
5516
- return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false });
5770
+ return tokens;
5517
5771
  }
5518
- function bytesToLatin1(bytes) {
5519
- let out = "";
5520
- const chunk = 32768;
5521
- for (let i = 0; i < bytes.byteLength; i += chunk) {
5522
- out += String.fromCharCode(...bytes.subarray(i, i + chunk));
5772
+ function estimateTextAdvanceInTextSpace(text, state) {
5773
+ const fs = Math.abs(state.fontSize) || 12;
5774
+ const scaleH = state.horizScaling / 100;
5775
+ let adv = 0;
5776
+ for (const ch of text) {
5777
+ const cp = ch.codePointAt(0) ?? 32;
5778
+ const glyphW = cp > 127 ? fs : fs * 0.54;
5779
+ adv += (glyphW + state.charSpacing + (cp === 32 ? state.wordSpacing : 0)) * scaleH;
5523
5780
  }
5524
- return out;
5781
+ return adv;
5525
5782
  }
5526
- function extractBalancedPdfDict(text, startIdx) {
5527
- const openIdx = text.indexOf("<<", startIdx);
5528
- if (openIdx < 0) return null;
5529
- let depth = 0;
5530
- let inLiteral = false;
5531
- let literalDepth = 0;
5532
- for (let i = openIdx; i < text.length; i++) {
5533
- const ch = text.charCodeAt(i);
5534
- if (inLiteral) {
5535
- if (ch === 92) {
5536
- i++;
5537
- continue;
5783
+ function parsePdfContentStreamTextOps(doc, streamBytes, resourcesDict, mediaBox, initialCtm = [1, 0, 0, 1, 0, 0], isTopLevelStream = true, depth = 0) {
5784
+ if (streamBytes.byteLength === 0 || depth > 5) return [];
5785
+ const fonts = extractResourcesFontMap(doc, resourcesDict);
5786
+ const tokens = tokenizeContentStream(streamBytes);
5787
+ const results = [];
5788
+ const stateStack = [];
5789
+ let state = {
5790
+ ctm: [...initialCtm],
5791
+ fontName: "",
5792
+ fontSize: 12,
5793
+ charSpacing: 0,
5794
+ wordSpacing: 0,
5795
+ horizScaling: 100,
5796
+ leading: 0,
5797
+ textRise: 0
5798
+ };
5799
+ let textMatrix = [1, 0, 0, 1, 0, 0];
5800
+ let textLineMatrix = [1, 0, 0, 1, 0, 0];
5801
+ const operands = [];
5802
+ const emitTextSpan = (rawText, textSpaceAdvance, opStart, opEnd) => {
5803
+ const trimmed = rawText.replace(/\0/g, "");
5804
+ if (!trimmed.trim()) {
5805
+ textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
5806
+ return;
5807
+ }
5808
+ const combined = multiplyPdfMatrix(textMatrix, state.ctm);
5809
+ const bx = combined[4];
5810
+ const by = combined[5] + state.textRise;
5811
+ const scaleX = Math.hypot(combined[0], combined[1]) || 1;
5812
+ const scaleY = Math.hypot(combined[2], combined[3]) || 1;
5813
+ const effectiveFontSize = Math.round(Math.max(1, (Math.abs(state.fontSize) || 12) * scaleY) * 100) / 100;
5814
+ const widthPt = Math.max(4, Math.abs(textSpaceAdvance * scaleX));
5815
+ const heightPt = Math.max(8, effectiveFontSize * 1.2);
5816
+ const left = Math.round((bx - mediaBox.x) * 100) / 100;
5817
+ const top = Math.round(Math.max(0, mediaBox.height - (by - mediaBox.y) - effectiveFontSize * 0.85) * 100) / 100;
5818
+ results.push({
5819
+ text: trimmed,
5820
+ left,
5821
+ top,
5822
+ width: Math.round(widthPt * 100) / 100,
5823
+ height: Math.round(heightPt * 100) / 100,
5824
+ fontSize: effectiveFontSize,
5825
+ ...isTopLevelStream ? { streamStartOffset: opStart, streamEndOffset: opEnd } : {}
5826
+ });
5827
+ textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
5828
+ };
5829
+ for (const tok of tokens) {
5830
+ if (tok.type !== "op") {
5831
+ operands.push(tok);
5832
+ continue;
5833
+ }
5834
+ const op = tok.op;
5835
+ const opStart = operands.length > 0 ? operands[0].start : tok.start;
5836
+ const opEnd = tok.end;
5837
+ switch (op) {
5838
+ case "q": {
5839
+ stateStack.push({ ...state, ctm: [...state.ctm] });
5840
+ break;
5538
5841
  }
5539
- if (ch === 40) literalDepth++;
5540
- else if (ch === 41) {
5541
- literalDepth--;
5542
- if (literalDepth <= 0) {
5543
- inLiteral = false;
5842
+ case "Q": {
5843
+ const popped = stateStack.pop();
5844
+ if (popped) state = popped;
5845
+ break;
5846
+ }
5847
+ case "cm": {
5848
+ if (operands.length >= 6) {
5849
+ const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
5850
+ const m = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
5851
+ state.ctm = multiplyPdfMatrix(m, state.ctm);
5852
+ }
5853
+ break;
5854
+ }
5855
+ case "BT": {
5856
+ textMatrix = [1, 0, 0, 1, 0, 0];
5857
+ textLineMatrix = [1, 0, 0, 1, 0, 0];
5858
+ break;
5859
+ }
5860
+ case "ET": {
5861
+ break;
5862
+ }
5863
+ case "Tf": {
5864
+ if (operands.length >= 2) {
5865
+ const nameTok = operands[operands.length - 2];
5866
+ const sizeTok = operands[operands.length - 1];
5867
+ if (nameTok.type === "name") state.fontName = nameTok.value;
5868
+ if (sizeTok.type === "number") state.fontSize = sizeTok.num;
5544
5869
  }
5870
+ break;
5871
+ }
5872
+ case "Tc": {
5873
+ const last = operands[operands.length - 1];
5874
+ if (last?.type === "number") state.charSpacing = last.num;
5875
+ break;
5876
+ }
5877
+ case "Tw": {
5878
+ const last = operands[operands.length - 1];
5879
+ if (last?.type === "number") state.wordSpacing = last.num;
5880
+ break;
5881
+ }
5882
+ case "Tz": {
5883
+ const last = operands[operands.length - 1];
5884
+ if (last?.type === "number") state.horizScaling = last.num;
5885
+ break;
5545
5886
  }
5546
- continue;
5547
- }
5548
- if (ch === 40) {
5549
- inLiteral = true;
5550
- literalDepth = 1;
5551
- continue;
5552
- }
5553
- if (ch === 37) {
5554
- while (i < text.length && text.charCodeAt(i) !== 10 && text.charCodeAt(i) !== 13) {
5555
- i++;
5887
+ case "TL": {
5888
+ const last = operands[operands.length - 1];
5889
+ if (last?.type === "number") state.leading = last.num;
5890
+ break;
5556
5891
  }
5557
- continue;
5558
- }
5559
- if (ch === 60 && text.charCodeAt(i + 1) === 60) {
5560
- depth++;
5561
- i++;
5562
- continue;
5563
- }
5564
- if (ch === 62 && text.charCodeAt(i + 1) === 62) {
5565
- depth--;
5566
- i++;
5567
- if (depth === 0) {
5568
- return text.slice(openIdx, i + 1);
5892
+ case "Ts": {
5893
+ const last = operands[operands.length - 1];
5894
+ if (last?.type === "number") state.textRise = last.num;
5895
+ break;
5569
5896
  }
5570
- }
5571
- }
5572
- return null;
5573
- }
5574
- function parsePdfStringTokenAfterKey(dictText, keyName) {
5575
- const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*`);
5576
- const match = re.exec(dictText);
5577
- if (!match) return null;
5578
- let pos = match.index + match[0].length;
5579
- while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5580
- if (pos >= dictText.length) return null;
5581
- if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5582
- const close = dictText.indexOf(">", pos + 1);
5583
- if (close < 0) return null;
5584
- return hexToBytes(dictText.slice(pos + 1, close));
5585
- }
5586
- if (dictText[pos] === "(") {
5587
- let depth = 1;
5588
- let i = pos + 1;
5589
- while (i < dictText.length && depth > 0) {
5590
- const ch = dictText.charCodeAt(i);
5591
- if (ch === 92) {
5592
- i += 2;
5593
- continue;
5897
+ case "Td":
5898
+ case "TD": {
5899
+ if (operands.length >= 2) {
5900
+ const txTok = operands[operands.length - 2];
5901
+ const tyTok = operands[operands.length - 1];
5902
+ const tx = txTok.type === "number" ? txTok.num : 0;
5903
+ const ty = tyTok.type === "number" ? tyTok.num : 0;
5904
+ if (op === "TD") state.leading = -ty;
5905
+ textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, tx, ty], textLineMatrix);
5906
+ textMatrix = [...textLineMatrix];
5907
+ }
5908
+ break;
5594
5909
  }
5595
- if (ch === 40) depth++;
5596
- else if (ch === 41) depth--;
5597
- i++;
5598
- }
5599
- if (depth === 0) {
5600
- return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
5601
- }
5602
- }
5603
- return null;
5604
- }
5605
- function parseFirstPdfArrayStringBytes(dictText, keyName) {
5606
- const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*\\[`);
5607
- const match = re.exec(dictText);
5608
- if (!match) return null;
5609
- let pos = match.index + match[0].length;
5610
- while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5611
- if (pos >= dictText.length) return null;
5612
- if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5613
- const close = dictText.indexOf(">", pos + 1);
5614
- if (close >= 0) return hexToBytes(dictText.slice(pos + 1, close));
5615
- } else if (dictText[pos] === "(") {
5616
- let depth = 1;
5617
- let i = pos + 1;
5618
- while (i < dictText.length && depth > 0) {
5619
- const ch = dictText.charCodeAt(i);
5620
- if (ch === 92) {
5621
- i += 2;
5622
- continue;
5910
+ case "Tm": {
5911
+ if (operands.length >= 6) {
5912
+ const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
5913
+ textMatrix = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
5914
+ textLineMatrix = [...textMatrix];
5915
+ }
5916
+ break;
5623
5917
  }
5624
- if (ch === 40) depth++;
5625
- else if (ch === 41) depth--;
5626
- i++;
5627
- }
5628
- if (depth === 0) {
5629
- return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
5630
- }
5631
- }
5632
- return null;
5633
- }
5634
- function parseRawEncryptFromPdfBytes(pdfBytes) {
5635
- if (!pdfBytes || pdfBytes.byteLength < 16) return null;
5636
- const rawText = bytesToLatin1(pdfBytes);
5637
- let containerDict = null;
5638
- let searchEnd = rawText.length;
5639
- while (searchEnd > 0) {
5640
- const trailerIdx = rawText.lastIndexOf("trailer", searchEnd - 1);
5641
- if (trailerIdx < 0) break;
5642
- const prevCh = trailerIdx > 0 ? rawText[trailerIdx - 1] : "\n";
5643
- const afterCh = rawText[trailerIdx + 7] ?? " ";
5644
- if (/[\s\r\n>]/.test(prevCh) && /[\s\r\n<]/.test(afterCh)) {
5645
- const candidate = extractBalancedPdfDict(rawText, trailerIdx + 7);
5646
- if (candidate && /\/Encrypt\b/.test(candidate)) {
5647
- containerDict = candidate;
5918
+ case "T*": {
5919
+ textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
5920
+ textMatrix = [...textLineMatrix];
5648
5921
  break;
5649
5922
  }
5650
- if (candidate && !containerDict) {
5651
- containerDict = candidate;
5923
+ case "Tj":
5924
+ case "'":
5925
+ case '"': {
5926
+ if (op === "'" || op === '"') {
5927
+ if (op === '"' && operands.length >= 3) {
5928
+ const twTok = operands[operands.length - 3];
5929
+ const tcTok = operands[operands.length - 2];
5930
+ if (twTok.type === "number") state.wordSpacing = twTok.num;
5931
+ if (tcTok.type === "number") state.charSpacing = tcTok.num;
5932
+ }
5933
+ textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
5934
+ textMatrix = [...textLineMatrix];
5935
+ }
5936
+ const strTok = operands[operands.length - 1];
5937
+ if (strTok && (strTok.type === "literal" || strTok.type === "hex")) {
5938
+ const fontInfo = fonts.get(state.fontName);
5939
+ const { text } = decodePdfStringBytes(strTok.bytes, fontInfo);
5940
+ const adv = estimateTextAdvanceInTextSpace(text, state);
5941
+ emitTextSpan(text, adv, opStart, opEnd);
5942
+ }
5943
+ break;
5652
5944
  }
5653
- }
5654
- searchEnd = trailerIdx;
5655
- }
5656
- if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5657
- const xrefMatch = /<<[\s\S]{0,2048}?\/Type\s*\/XRef[\s\S]{0,2048}?>>/.exec(rawText);
5658
- if (xrefMatch && /\/Encrypt\b/.test(xrefMatch[0])) {
5659
- containerDict = xrefMatch[0];
5660
- }
5661
- }
5662
- if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5663
- return null;
5664
- }
5665
- let encryptDictText = null;
5666
- const refMatch = /\/Encrypt\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
5667
- if (refMatch) {
5668
- const objNum = refMatch[1];
5669
- const genNum = refMatch[2];
5670
- const objRe = new RegExp(`(?:^|[\\r\\n\\s])${objNum}\\s+${genNum}\\s+obj\\b`, "g");
5671
- let lastObjMatch = null;
5672
- let m;
5673
- while ((m = objRe.exec(rawText)) !== null) {
5674
- lastObjMatch = m;
5675
- }
5676
- if (lastObjMatch) {
5677
- encryptDictText = extractBalancedPdfDict(rawText, lastObjMatch.index + lastObjMatch[0].length);
5678
- }
5679
- } else if (/\/Encrypt\s*<</.test(containerDict)) {
5680
- const inlineIdx = containerDict.search(/\/Encrypt\s*<</);
5681
- encryptDictText = extractBalancedPdfDict(containerDict, inlineIdx);
5682
- }
5683
- if (!encryptDictText) return null;
5684
- const filterMatch = /\/Filter\s*\/([A-Za-z0-9_.+-]+)/.exec(encryptDictText);
5685
- const vMatch = /\/V\s+(-?\d+)/.exec(encryptDictText);
5686
- const rMatch = /\/R\s+(-?\d+)/.exec(encryptDictText);
5687
- const lenMatch = /\/Length\s+(\d+)/.exec(encryptDictText);
5688
- const pMatch = /\/P\s+(-?\d+)/.exec(encryptDictText);
5689
- const filter = filterMatch ? filterMatch[1] : "Standard";
5690
- const version = vMatch ? parseInt(vMatch[1], 10) : 1;
5691
- const revision = rMatch ? parseInt(rMatch[1], 10) : version >= 2 ? 3 : 2;
5692
- const keyLength = lenMatch ? parseInt(lenMatch[1], 10) : version >= 2 ? 128 : 40;
5693
- const pSigned = pMatch ? parseInt(pMatch[1], 10) | 0 : -4;
5694
- const oBytes = parsePdfStringTokenAfterKey(encryptDictText, "O") ?? new Uint8Array(0);
5695
- const uBytes = parsePdfStringTokenAfterKey(encryptDictText, "U") ?? new Uint8Array(0);
5696
- let fileId = parseFirstPdfArrayStringBytes(containerDict, "ID");
5697
- if (!fileId) {
5698
- const idRefMatch = /\/ID\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
5699
- if (idRefMatch) {
5700
- const idObjRe = new RegExp(`(?:^|[\\r\\n\\s])${idRefMatch[1]}\\s+${idRefMatch[2]}\\s+obj\\b([\\s\\S]{0,512}?)endobj`);
5701
- const idObjM = idObjRe.exec(rawText);
5702
- if (idObjM) {
5703
- fileId = parseFirstPdfArrayStringBytes(`/ID ${idObjM[1]}`, "ID");
5945
+ case "TJ": {
5946
+ const arrTok = operands[operands.length - 1];
5947
+ if (arrTok?.type === "array") {
5948
+ const fontInfo = fonts.get(state.fontName);
5949
+ const fs = Math.abs(state.fontSize) || 12;
5950
+ const scaleH = state.horizScaling / 100;
5951
+ let joined = "";
5952
+ let totalAdv = 0;
5953
+ for (const item of arrTok.items) {
5954
+ if (item.type === "literal" || item.type === "hex") {
5955
+ const { text } = decodePdfStringBytes(item.bytes, fontInfo);
5956
+ joined += text;
5957
+ totalAdv += estimateTextAdvanceInTextSpace(text, state);
5958
+ } else if (item.type === "number") {
5959
+ const shift = -item.num / 1e3 * fs * scaleH;
5960
+ totalAdv += shift;
5961
+ if (item.num < -180 && joined.length > 0 && !joined.endsWith(" ")) {
5962
+ joined += " ";
5963
+ }
5964
+ }
5965
+ }
5966
+ emitTextSpan(joined, totalAdv, opStart, opEnd);
5967
+ }
5968
+ break;
5969
+ }
5970
+ case "Do": {
5971
+ const nameTok = operands[operands.length - 1];
5972
+ if (nameTok?.type === "name" && resourcesDict) {
5973
+ const xObjEntry = resourcesDict.get(import_pdf_lib2.PDFName.of("XObject"));
5974
+ const xObjDict = doc.context.lookupMaybe(xObjEntry, import_pdf_lib2.PDFDict);
5975
+ const targetObj = xObjDict?.get(import_pdf_lib2.PDFName.of(nameTok.value));
5976
+ const resolvedXObj = targetObj instanceof import_pdf_lib2.PDFRef ? doc.context.lookup(targetObj) : targetObj;
5977
+ if (resolvedXObj instanceof import_pdf_lib2.PDFRawStream) {
5978
+ const subType = resolvedXObj.dict.get(import_pdf_lib2.PDFName.of("Subtype"));
5979
+ if (subType instanceof import_pdf_lib2.PDFName && subType.decodeText() === "Form") {
5980
+ const formBytes = decodeSingleStreamObject(doc, resolvedXObj);
5981
+ const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(import_pdf_lib2.PDFName.of("Resources")), import_pdf_lib2.PDFDict) ?? resourcesDict;
5982
+ let formMat = [...state.ctm];
5983
+ const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(import_pdf_lib2.PDFName.of("Matrix")), import_pdf_lib2.PDFArray);
5984
+ if (matArr && matArr.size() >= 6) {
5985
+ const nums = [];
5986
+ for (let k = 0; k < 6; k++) {
5987
+ const nObj = matArr.get(k);
5988
+ nums.push(nObj instanceof import_pdf_lib2.PDFNumber ? nObj.asNumber() : 0);
5989
+ }
5990
+ formMat = multiplyPdfMatrix(
5991
+ [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]],
5992
+ state.ctm
5993
+ );
5994
+ }
5995
+ const subSpans = parsePdfContentStreamTextOps(
5996
+ doc,
5997
+ formBytes,
5998
+ formRes,
5999
+ mediaBox,
6000
+ formMat,
6001
+ false,
6002
+ depth + 1
6003
+ );
6004
+ results.push(...subSpans);
6005
+ }
6006
+ }
6007
+ }
6008
+ break;
5704
6009
  }
6010
+ default:
6011
+ break;
5705
6012
  }
6013
+ operands.length = 0;
5706
6014
  }
5707
- return {
5708
- filter,
5709
- version,
5710
- revision,
5711
- keyLength,
5712
- pSigned,
5713
- oBytes,
5714
- uBytes,
5715
- fileId: fileId ?? new Uint8Array(0)
5716
- };
5717
- }
5718
- function extractEncryptMetadataFromDoc(doc) {
5719
- const encEntry = doc.context.trailerInfo.Encrypt;
5720
- if (!encEntry) return null;
5721
- const encDict = encEntry instanceof import_pdf_lib2.PDFDict ? encEntry : doc.context.lookupMaybe(encEntry, import_pdf_lib2.PDFDict);
5722
- if (!encDict) return null;
5723
- const filterObj = encDict.get(import_pdf_lib2.PDFName.of("Filter"));
5724
- const filter = filterObj instanceof import_pdf_lib2.PDFName ? filterObj.decodeText() : "Standard";
5725
- const vObj = encDict.get(import_pdf_lib2.PDFName.of("V"));
5726
- const version = vObj instanceof import_pdf_lib2.PDFNumber ? vObj.asNumber() : 1;
5727
- const rObj = encDict.get(import_pdf_lib2.PDFName.of("R"));
5728
- const revision = rObj instanceof import_pdf_lib2.PDFNumber ? rObj.asNumber() : version >= 2 ? 3 : 2;
5729
- const lenObj = encDict.get(import_pdf_lib2.PDFName.of("Length"));
5730
- const keyLength = lenObj instanceof import_pdf_lib2.PDFNumber ? lenObj.asNumber() : version >= 2 ? 128 : 40;
5731
- const pObj = encDict.get(import_pdf_lib2.PDFName.of("P"));
5732
- const pSigned = pObj instanceof import_pdf_lib2.PDFNumber ? pObj.asNumber() | 0 : -4;
5733
- const oObj = encDict.get(import_pdf_lib2.PDFName.of("O"));
5734
- const oBytes = oObj instanceof import_pdf_lib2.PDFHexString || oObj instanceof import_pdf_lib2.PDFString ? extractPdfStringRawBytes(oObj) : new Uint8Array(0);
5735
- const uObj = encDict.get(import_pdf_lib2.PDFName.of("U"));
5736
- const uBytes = uObj instanceof import_pdf_lib2.PDFHexString || uObj instanceof import_pdf_lib2.PDFString ? extractPdfStringRawBytes(uObj) : new Uint8Array(0);
5737
- let fileId = new Uint8Array(0);
5738
- const idEntry = doc.context.trailerInfo.ID;
5739
- const idArr = idEntry instanceof import_pdf_lib2.PDFArray ? idEntry : doc.context.lookupMaybe(idEntry, import_pdf_lib2.PDFArray);
5740
- if (idArr && idArr.size() > 0) {
5741
- const first = idArr.get(0);
5742
- if (first instanceof import_pdf_lib2.PDFHexString || first instanceof import_pdf_lib2.PDFString) {
5743
- fileId = extractPdfStringRawBytes(first);
5744
- }
5745
- }
5746
- return {
5747
- filter,
5748
- version,
5749
- revision,
5750
- keyLength,
5751
- pSigned,
5752
- oBytes,
5753
- uBytes,
5754
- fileId
5755
- };
6015
+ return results;
5756
6016
  }
5757
- function inspectPdfEncryption(pdfBytes) {
5758
- const meta = parseRawEncryptFromPdfBytes(pdfBytes);
5759
- if (!meta) {
5760
- return {
5761
- encrypted: false,
5762
- requiresOpenPassword: false,
5763
- permissions: { ...DEFAULT_ALL_PERMISSIONS }
5764
- };
5765
- }
5766
- let requiresOpenPassword = true;
5767
- if (meta.filter === "Standard" && (meta.version === 1 || meta.version === 2) && (meta.revision === 2 || meta.revision === 3) && meta.oBytes.byteLength >= 32 && meta.uBytes.byteLength >= 16) {
5768
- const emptyKey = authenticatePaddedUserPassword(
5769
- padPdfPassword(""),
5770
- meta.oBytes,
5771
- meta.uBytes,
5772
- meta.pSigned,
5773
- meta.fileId,
5774
- meta.revision,
5775
- meta.keyLength
5776
- );
5777
- requiresOpenPassword = emptyKey === null;
5778
- }
5779
- return {
5780
- encrypted: true,
5781
- requiresOpenPassword,
5782
- filter: meta.filter,
5783
- version: meta.version,
5784
- revision: meta.revision,
5785
- keyLength: meta.keyLength,
5786
- permissionFlagsRaw: meta.pSigned,
5787
- permissions: decodePdfPermissionFlags(meta.pSigned, meta.revision)
5788
- };
6017
+ function rectsIntersect(a, b) {
6018
+ const ax2 = a.left + a.width;
6019
+ const ay2 = a.top + a.height;
6020
+ const bx2 = b.left + b.width;
6021
+ const by2 = b.top + b.height;
6022
+ return !(ax2 <= b.left || a.left >= bx2 || ay2 <= b.top || a.top >= by2);
5789
6023
  }
5790
- async function decryptPdfBytes(pdfBytes, password) {
5791
- let meta = parseRawEncryptFromPdfBytes(pdfBytes);
5792
- const doc = await import_pdf_lib2.PDFDocument.load(pdfBytes, {
5793
- ignoreEncryption: true,
5794
- updateMetadata: false
5795
- });
5796
- if (!meta && doc.isEncrypted) {
5797
- meta = extractEncryptMetadataFromDoc(doc);
5798
- }
5799
- if (!meta) {
5800
- return pdfBytes.slice();
5801
- }
5802
- if (meta.filter !== "Standard" || meta.version !== 1 && meta.version !== 2 || meta.revision !== 2 && meta.revision !== 3) {
5803
- throw new PdfSecurityError(
5804
- "PDF_UNSUPPORTED_ENCRYPTION",
5805
- `Unsupported PDF encryption handler (Filter=/${meta.filter}, V=${meta.version}, R=${meta.revision}).`
5806
- );
5807
- }
5808
- const rev = meta.revision;
5809
- const emptyOpenKey = authenticatePaddedUserPassword(
5810
- padPdfPassword(""),
5811
- meta.oBytes,
5812
- meta.uBytes,
5813
- meta.pSigned,
5814
- meta.fileId,
5815
- rev,
5816
- meta.keyLength
6024
+ function stripPdfPageNativeTextInRects(doc, page, stripRects) {
6025
+ if (!stripRects.length) return 0;
6026
+ const contentsBytes = decodeContentsEntry(doc, page.node.Contents());
6027
+ if (contentsBytes.byteLength === 0) return 0;
6028
+ const mediaBox = page.getMediaBox();
6029
+ const ops = parsePdfContentStreamTextOps(doc, contentsBytes, page.node.Resources(), mediaBox, [1, 0, 0, 1, 0, 0], true);
6030
+ const matchingOps = ops.filter(
6031
+ (op) => op.streamStartOffset !== void 0 && op.streamEndOffset !== void 0 && stripRects.some((r) => rectsIntersect(op, r))
5817
6032
  );
5818
- const requiresOpenPassword = emptyOpenKey === null;
5819
- const candidatePw = password ?? "";
5820
- if (requiresOpenPassword && candidatePw.length === 0) {
5821
- throw new PdfSecurityError(
5822
- "PDF_PASSWORD_REQUIRED",
5823
- "Encrypted PDF document requires an open password."
5824
- );
5825
- }
5826
- let encryptionKey = null;
5827
- if (candidatePw.length === 0 && emptyOpenKey) {
5828
- encryptionKey = emptyOpenKey;
5829
- } else {
5830
- encryptionKey = authenticatePaddedUserPassword(
5831
- padPdfPassword(candidatePw),
5832
- meta.oBytes,
5833
- meta.uBytes,
5834
- meta.pSigned,
5835
- meta.fileId,
5836
- rev,
5837
- meta.keyLength
5838
- );
5839
- if (!encryptionKey) {
5840
- encryptionKey = authenticateOwnerPassword(
5841
- candidatePw,
5842
- meta.oBytes,
5843
- meta.uBytes,
5844
- meta.pSigned,
5845
- meta.fileId,
5846
- rev,
5847
- meta.keyLength
5848
- );
5849
- }
5850
- }
5851
- if (!encryptionKey) {
5852
- throw new PdfSecurityError(
5853
- "PDF_INVALID_PASSWORD",
5854
- "Incorrect password for encrypted PDF document."
5855
- );
5856
- }
5857
- const encryptRef = doc.context.trailerInfo.Encrypt instanceof import_pdf_lib2.PDFRef ? doc.context.trailerInfo.Encrypt : null;
5858
- const idRef = doc.context.trailerInfo.ID instanceof import_pdf_lib2.PDFRef ? doc.context.trailerInfo.ID : null;
5859
- for (const [ref, obj] of doc.context.enumerateIndirectObjects()) {
5860
- if (encryptRef && ref.objectNumber === encryptRef.objectNumber && ref.generationNumber === encryptRef.generationNumber) {
5861
- continue;
5862
- }
5863
- if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
5864
- continue;
5865
- }
5866
- const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
5867
- if (obj instanceof import_pdf_lib2.PDFRawStream) {
5868
- transformPdfObjectStringsWithRc4(obj.dict, objKey);
5869
- const decryptedStream = rc4Bytes(objKey, obj.contents);
5870
- obj.dict.set(import_pdf_lib2.PDFName.of("Length"), import_pdf_lib2.PDFNumber.of(decryptedStream.byteLength));
5871
- doc.context.assign(ref, import_pdf_lib2.PDFRawStream.of(obj.dict, decryptedStream));
5872
- } else if (obj instanceof import_pdf_lib2.PDFStream) {
5873
- transformPdfObjectStringsWithRc4(obj.dict, objKey);
5874
- const decryptedStream = rc4Bytes(objKey, obj.getContents());
5875
- obj.dict.set(import_pdf_lib2.PDFName.of("Length"), import_pdf_lib2.PDFNumber.of(decryptedStream.byteLength));
5876
- doc.context.assign(ref, import_pdf_lib2.PDFRawStream.of(obj.dict, decryptedStream));
5877
- } else {
5878
- const next = transformPdfObjectStringsWithRc4(obj, objKey);
5879
- if (next !== obj) {
5880
- doc.context.assign(ref, next);
6033
+ if (matchingOps.length === 0) return 0;
6034
+ const sanitized = contentsBytes.slice();
6035
+ for (const op of matchingOps) {
6036
+ for (let i = op.streamStartOffset; i < op.streamEndOffset; i++) {
6037
+ if (sanitized[i] !== 10 && sanitized[i] !== 13) {
6038
+ sanitized[i] = 32;
5881
6039
  }
5882
6040
  }
5883
6041
  }
5884
- delete doc.context.trailerInfo.Encrypt;
5885
- if (encryptRef) {
5886
- doc.context.delete(encryptRef);
5887
- }
5888
- return await doc.save({ useObjectStreams: false, updateFieldAppearances: false });
6042
+ const newStream = doc.context.flateStream(sanitized);
6043
+ const newRef = doc.context.register(newStream);
6044
+ page.node.set(import_pdf_lib2.PDFName.of("Contents"), newRef);
6045
+ return matchingOps.length;
5889
6046
  }
5890
6047
 
5891
6048
  // src/exporter/pdf-svg-vector.ts
@@ -9966,9 +10123,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9966
10123
  pdfPage.setRotation((0, import_pdf_lib4.degrees)(pageMeta.rotation));
9967
10124
  }
9968
10125
  if (pageMeta.cropBox) {
9969
- const cb = pageMeta.cropBox;
9970
- const cropY = Math.max(0, pageHeight - cb.top - cb.height);
9971
- pdfPage.setCropBox(cb.left, cropY, cb.width, cb.height);
10126
+ const cb = resolvePdfCropBoxPt(pageMeta.cropBox);
10127
+ if (cb) {
10128
+ const cropY = Math.max(0, pageHeight - cb.top - cb.height);
10129
+ pdfPage.setCropBox(cb.left, cropY, cb.width, cb.height);
10130
+ }
9972
10131
  }
9973
10132
  if (isCopiedBasePage && suppressedNativeRects.length > 0) {
9974
10133
  for (const sRect of suppressedNativeRects) {
@@ -10268,60 +10427,123 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10268
10427
  { colorType: elColorType }
10269
10428
  );
10270
10429
  } else if (el.type === "stamp" /* STAMP */) {
10271
- const sealColor = parseHexColor(el.color) ?? { r: 0.86, g: 0.15, b: 0.15, a: 1 };
10272
- const sealPdfCol = toPdfLibColor(sealColor, elColorType);
10273
- if (el.stampShape === "rect") {
10274
- pdfPage.drawRectangle({
10275
- x: left,
10276
- y: pdfY,
10430
+ if (el.svgContent) {
10431
+ drawVectorSvgOnPdfPage(
10432
+ pdfPage,
10433
+ pageHeight,
10434
+ left,
10435
+ top,
10277
10436
  width,
10278
10437
  height,
10279
- borderColor: sealPdfCol,
10280
- borderWidth: 2,
10281
- opacity: (el.opacity ?? 0.85) * sealColor.a
10282
- });
10438
+ el.svgContent,
10439
+ el.opacity ?? 0.9,
10440
+ elColorType
10441
+ );
10442
+ const stampTexts = extractSvgTextDescriptors(el.svgContent, width, height);
10443
+ for (const td of stampTexts) {
10444
+ try {
10445
+ await drawTextBox(
10446
+ pdfDoc,
10447
+ pdfPage,
10448
+ pageHeight,
10449
+ td.text,
10450
+ left + td.leftPt,
10451
+ top + td.topPt,
10452
+ td.widthPt,
10453
+ td.heightPt,
10454
+ {
10455
+ fontSize: td.fontSizePt,
10456
+ fontWeight: td.bold ? "bold" : "normal",
10457
+ color: td.color,
10458
+ textAlign: td.align,
10459
+ verticalAlign: "middle",
10460
+ padding: 0
10461
+ },
10462
+ cjkState,
10463
+ { noWrapSingleLine: true, colorType: elColorType }
10464
+ );
10465
+ } catch {
10466
+ await drawTextBox(
10467
+ pdfDoc,
10468
+ pdfPage,
10469
+ pageHeight,
10470
+ td.text,
10471
+ left + td.leftPt,
10472
+ top + td.topPt,
10473
+ td.widthPt,
10474
+ td.heightPt,
10475
+ {
10476
+ fontSize: td.fontSizePt,
10477
+ fontWeight: td.bold ? "bold" : "normal",
10478
+ color: td.color,
10479
+ textAlign: td.align,
10480
+ verticalAlign: "middle",
10481
+ padding: 0
10482
+ },
10483
+ null,
10484
+ { noWrapSingleLine: true, colorType: elColorType }
10485
+ );
10486
+ }
10487
+ }
10283
10488
  } else {
10284
- pdfPage.drawEllipse({
10285
- x: left + width / 2,
10286
- y: pdfY + height / 2,
10287
- xScale: width / 2,
10288
- yScale: height / 2,
10289
- borderColor: sealPdfCol,
10290
- borderWidth: 2,
10291
- opacity: (el.opacity ?? 0.85) * sealColor.a
10292
- });
10293
- pdfPage.drawEllipse({
10294
- x: left + width / 2,
10295
- y: pdfY + height / 2,
10296
- xScale: Math.max(4, width / 2 - 3.5),
10297
- yScale: Math.max(4, height / 2 - 3.5),
10298
- borderColor: sealPdfCol,
10299
- borderWidth: 0.75,
10300
- opacity: (el.opacity ?? 0.85) * sealColor.a
10301
- });
10302
- }
10303
- const stampText = el.secondaryText ? `${el.primaryText}
10489
+ const sealColor = parseHexColor(el.color) ?? { r: 0.86, g: 0.15, b: 0.15, a: 1 };
10490
+ const sealPdfCol = toPdfLibColor(sealColor, elColorType);
10491
+ if (el.stampShape === "rect" || el.stampShape === "pill") {
10492
+ pdfPage.drawRectangle({
10493
+ x: left,
10494
+ y: pdfY,
10495
+ width,
10496
+ height,
10497
+ borderColor: sealPdfCol,
10498
+ borderWidth: 2,
10499
+ opacity: (el.opacity ?? 0.85) * sealColor.a
10500
+ });
10501
+ } else {
10502
+ pdfPage.drawEllipse({
10503
+ x: left + width / 2,
10504
+ y: pdfY + height / 2,
10505
+ xScale: width / 2,
10506
+ yScale: height / 2,
10507
+ borderColor: sealPdfCol,
10508
+ borderWidth: 2,
10509
+ opacity: (el.opacity ?? 0.85) * sealColor.a
10510
+ });
10511
+ pdfPage.drawEllipse({
10512
+ x: left + width / 2,
10513
+ y: pdfY + height / 2,
10514
+ xScale: Math.max(4, width / 2 - 3.5),
10515
+ yScale: Math.max(4, height / 2 - 3.5),
10516
+ borderColor: sealPdfCol,
10517
+ borderWidth: 0.75,
10518
+ opacity: (el.opacity ?? 0.85) * sealColor.a
10519
+ });
10520
+ }
10521
+ const signerFooter = [el.signer, el.dateText].filter(Boolean).join(" \xB7 ");
10522
+ const baseStampText = el.secondaryText ? `${el.primaryText}
10304
10523
  \u2605 ${el.secondaryText}` : el.primaryText;
10305
- await drawTextBox(
10306
- pdfDoc,
10307
- pdfPage,
10308
- pageHeight,
10309
- stampText,
10310
- left + 6,
10311
- top + 6,
10312
- width - 12,
10313
- height - 12,
10314
- {
10315
- fontSize: 10,
10316
- fontWeight: "bold",
10317
- color: el.color ?? "#dc2626",
10318
- textAlign: "center",
10319
- verticalAlign: "middle",
10320
- lineHeight: 1.35
10321
- },
10322
- cjkState,
10323
- { colorType: elColorType }
10324
- );
10524
+ const stampText = signerFooter ? `${baseStampText}
10525
+ ${signerFooter}` : baseStampText;
10526
+ await drawTextBox(
10527
+ pdfDoc,
10528
+ pdfPage,
10529
+ pageHeight,
10530
+ stampText,
10531
+ left + 6,
10532
+ top + 6,
10533
+ width - 12,
10534
+ height - 12,
10535
+ {
10536
+ fontSize: 10,
10537
+ fontWeight: "bold",
10538
+ color: el.color ?? "#dc2626",
10539
+ textAlign: "center",
10540
+ verticalAlign: "middle",
10541
+ lineHeight: 1.35
10542
+ },
10543
+ cjkState,
10544
+ { colorType: elColorType }
10545
+ );
10546
+ }
10325
10547
  } else if (el.type === "ink" /* INK */) {
10326
10548
  const stroke2 = parseHexColor(el.strokeColor) ?? { r: 0.94, g: 0.27, b: 0.27, a: 1 };
10327
10549
  const strokeCol = toPdfLibColor(stroke2, elColorType);
@@ -10563,6 +10785,32 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10563
10785
  svgEl.opacity ?? 1,
10564
10786
  elColorType
10565
10787
  );
10788
+ const svgTextNodes = extractSvgTextDescriptors(resolvedSvg, width, height);
10789
+ for (const td of svgTextNodes) {
10790
+ try {
10791
+ await drawTextBox(
10792
+ pdfDoc,
10793
+ pdfPage,
10794
+ pageHeight,
10795
+ td.text,
10796
+ left + td.leftPt,
10797
+ top + td.topPt,
10798
+ td.widthPt,
10799
+ td.heightPt,
10800
+ {
10801
+ fontSize: td.fontSizePt,
10802
+ fontWeight: td.bold ? "bold" : "normal",
10803
+ color: td.color,
10804
+ textAlign: td.align,
10805
+ verticalAlign: "middle",
10806
+ padding: 0
10807
+ },
10808
+ !hasNonAscii(td.text) ? cjkState : null,
10809
+ { noWrapSingleLine: true, colorType: elColorType }
10810
+ );
10811
+ } catch {
10812
+ }
10813
+ }
10566
10814
  } else if (el.type === "circleMark" /* CIRCLE_MARK */) {
10567
10815
  const cmEl = el;
10568
10816
  const cmKey = cmEl.formFieldName || cmEl.fieldKey || cmEl.bindingField;
@@ -11361,11 +11609,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11361
11609
  });
11362
11610
  }
11363
11611
  const pdfSubtype = annotType === "highlight" ? "Highlight" : annotType === "underline" ? "Underline" : annotType === "strikeout" ? "StrikeOut" : annotType === "squiggly" ? "Squiggly" : "Text";
11612
+ const effectiveStatus = annotEl.reviewStatus ?? annotEl.status;
11364
11613
  const replyLines = (annotEl.replies ?? []).map((r) => `[${r.author}] ${r.content}`);
11365
11614
  const threadSummary = [
11366
- annotEl.status ? `[${annotEl.status.toUpperCase()}] ${annotEl.comment ?? ""}`.trim() : annotEl.comment ?? "",
11615
+ effectiveStatus ? `[${effectiveStatus.toUpperCase()}] ${annotEl.comment ?? ""}`.trim() : annotEl.comment ?? "",
11367
11616
  ...replyLines
11368
11617
  ].filter(Boolean).join("\n");
11618
+ const pdfReviewStateMap = {
11619
+ accepted: "Accepted",
11620
+ rejected: "Rejected",
11621
+ completed: "Completed",
11622
+ cancelled: "Cancelled",
11623
+ resolved: "Completed",
11624
+ open: "None"
11625
+ };
11626
+ const pdfReviewState = effectiveStatus ? pdfReviewStateMap[effectiveStatus] : void 0;
11369
11627
  const annotDictEntries = {
11370
11628
  Type: "Annot",
11371
11629
  Subtype: pdfSubtype,
@@ -11373,7 +11631,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11373
11631
  C: [col.r, col.g, col.b],
11374
11632
  CA: op,
11375
11633
  T: import_pdf_lib4.PDFHexString.fromText(annotEl.author || "Reviewer"),
11376
- Contents: import_pdf_lib4.PDFHexString.fromText(threadSummary)
11634
+ Contents: import_pdf_lib4.PDFHexString.fromText(threadSummary),
11635
+ ...pdfReviewState ? {
11636
+ StateModel: import_pdf_lib4.PDFString.of("Review"),
11637
+ State: import_pdf_lib4.PDFString.of(pdfReviewState)
11638
+ } : {}
11377
11639
  };
11378
11640
  if (pdfSubtype !== "Text") {
11379
11641
  annotDictEntries.QuadPoints = [