@yudaocode/univer-pdfs 1.6.217 → 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.
@@ -183,6 +183,22 @@ var PDF_PAGE_PRESETS = {
183
183
  INVOICE_240_93: { width: mmToPt(240), height: mmToPt(93), preset: "INVOICE_240_93" },
184
184
  CUSTOM: { width: 595.28, height: 841.89, preset: "CUSTOM" }
185
185
  };
186
+ function resolvePdfCropBoxPt(cropBox) {
187
+ if (!cropBox) return null;
188
+ const rawLeft = cropBox.left ?? cropBox.leftPt;
189
+ const rawTop = cropBox.top ?? cropBox.topPt;
190
+ const rawWidth = cropBox.width ?? cropBox.widthPt;
191
+ const rawHeight = cropBox.height ?? cropBox.heightPt;
192
+ if (rawLeft === void 0 && rawTop === void 0 && rawWidth === void 0 && rawHeight === void 0) {
193
+ return null;
194
+ }
195
+ return {
196
+ left: Math.max(0, Number(rawLeft) || 0),
197
+ top: Math.max(0, Number(rawTop) || 0),
198
+ width: Math.max(8, Number(rawWidth) || 8),
199
+ height: Math.max(8, Number(rawHeight) || 8)
200
+ };
201
+ }
186
202
  var PdfElementType = /* @__PURE__ */ ((PdfElementType2) => {
187
203
  PdfElementType2["TEXT"] = "text";
188
204
  PdfElementType2["LIST"] = "list";
@@ -313,7 +329,9 @@ function createDefaultPdfUnitData(partial) {
313
329
  nativeTextSpansByPage: partial?.editState?.nativeTextSpansByPage ? Tools.deepClone(partial.editState.nativeTextSpansByPage) : partial?.metadata?.nativeTextSpansByPage ? Tools.deepClone(partial.metadata.nativeTextSpansByPage) : void 0
314
330
  },
315
331
  ...partial?.layers !== void 0 ? { layers: Tools.deepClone(partial.layers) } : {},
332
+ ...partial?.bookmarks !== void 0 ? { bookmarks: Tools.deepClone(partial.bookmarks) } : partial?.metadata?.bookmarks !== void 0 ? { bookmarks: Tools.deepClone(partial.metadata.bookmarks) } : {},
316
333
  ...partial?.attachments !== void 0 ? { attachments: Tools.deepClone(partial.attachments) } : {},
334
+ ...partial?.security !== void 0 ? { security: Tools.deepClone(partial.security) } : partial?.metadata?.security !== void 0 ? { security: Tools.deepClone(partial.metadata.security) } : {},
317
335
  ...partial?.securityPermissions !== void 0 ? { securityPermissions: Tools.deepClone(partial.securityPermissions) } : {},
318
336
  ...partial?.signatureEnvelope !== void 0 ? { signatureEnvelope: Tools.deepClone(partial.signatureEnvelope) } : {},
319
337
  ...partial?.pdfACompliant !== void 0 ? { pdfACompliant: partial.pdfACompliant } : {},
@@ -546,9 +564,33 @@ var PdfUnitModel = class extends UnitModel {
546
564
  if (patch.layers !== void 0) {
547
565
  this._snapshot.layers = patch.layers ? Tools.deepClone(patch.layers) : void 0;
548
566
  }
567
+ if (patch.bookmarks !== void 0) {
568
+ this._snapshot.bookmarks = patch.bookmarks ? Tools.deepClone(patch.bookmarks) : void 0;
569
+ if (!this._snapshot.metadata) {
570
+ this._snapshot.metadata = {};
571
+ }
572
+ if (patch.bookmarks && patch.bookmarks.length > 0) {
573
+ this._snapshot.metadata.bookmarks = Tools.deepClone(patch.bookmarks);
574
+ } else if (patch.bookmarks === null || Array.isArray(patch.bookmarks) && patch.bookmarks.length === 0) {
575
+ if (patch.bookmarks === null) {
576
+ delete this._snapshot.metadata.bookmarks;
577
+ } else {
578
+ this._snapshot.metadata.bookmarks = [];
579
+ }
580
+ }
581
+ } else if (patch.metadata !== void 0) {
582
+ if (this._snapshot.metadata?.bookmarks !== void 0) {
583
+ this._snapshot.bookmarks = Tools.deepClone(this._snapshot.metadata.bookmarks);
584
+ } else if (patch.replaceMetadata) {
585
+ delete this._snapshot.bookmarks;
586
+ }
587
+ }
549
588
  if (patch.attachments !== void 0) {
550
589
  this._snapshot.attachments = patch.attachments ? Tools.deepClone(patch.attachments) : void 0;
551
590
  }
591
+ if (patch.security !== void 0) {
592
+ this._snapshot.security = patch.security ? Tools.deepClone(patch.security) : void 0;
593
+ }
552
594
  if (patch.securityPermissions !== void 0) {
553
595
  this._snapshot.securityPermissions = patch.securityPermissions ? Tools.deepClone(patch.securityPermissions) : void 0;
554
596
  }
@@ -3189,7 +3231,7 @@ var exportToPdfmeTemplate = toPdfmeTemplate;
3189
3231
  var importFromPdfmeTemplate = fromPdfmeTemplate;
3190
3232
 
3191
3233
  // src/exporter/pdf-exporter.ts
3192
- import { Tools as Tools2 } from "@univerjs/core";
3234
+ import { Tools as Tools3 } from "@univerjs/core";
3193
3235
  import {
3194
3236
  appendBezierCurve,
3195
3237
  beginText,
@@ -3202,22 +3244,22 @@ import {
3202
3244
  endText,
3203
3245
  moveText,
3204
3246
  moveTo,
3205
- PDFArray as PDFArray2,
3247
+ PDFArray as PDFArray3,
3206
3248
  PDFBool,
3207
3249
  PDFCheckBox,
3208
- PDFDict as PDFDict2,
3209
- PDFDocument as PDFDocument2,
3250
+ PDFDict as PDFDict3,
3251
+ PDFDocument as PDFDocument3,
3210
3252
  PDFDropdown,
3211
- PDFHexString,
3212
- PDFName as PDFName2,
3213
- PDFNumber as PDFNumber2,
3253
+ PDFHexString as PDFHexString2,
3254
+ PDFName as PDFName3,
3255
+ PDFNumber as PDFNumber3,
3214
3256
  PDFOperator,
3215
3257
  PDFOptionList,
3216
3258
  PDFRadioGroup,
3217
- PDFRawStream as PDFRawStream2,
3218
- PDFRef as PDFRef2,
3219
- PDFStream as PDFStream2,
3220
- PDFString,
3259
+ PDFRawStream as PDFRawStream3,
3260
+ PDFRef as PDFRef3,
3261
+ PDFStream as PDFStream3,
3262
+ PDFString as PDFString2,
3221
3263
  PDFTextField,
3222
3264
  popGraphicsState as popGraphicsState2,
3223
3265
  pushGraphicsState as pushGraphicsState2,
@@ -3238,6 +3280,281 @@ import {
3238
3280
  } from "pdf-lib";
3239
3281
  import QRCode2 from "qrcode";
3240
3282
 
3283
+ // src/exporter/pdf-stamps.ts
3284
+ var PDF_STANDARD_STAMP_PRESETS = [
3285
+ {
3286
+ id: "approved",
3287
+ title: "\u5DF2\u6279\u51C6",
3288
+ subtitle: "APPROVED",
3289
+ color: "#16A34A",
3290
+ shape: "rect"
3291
+ },
3292
+ {
3293
+ id: "rejected",
3294
+ title: "\u5DF2\u9A73\u56DE",
3295
+ subtitle: "REJECTED",
3296
+ color: "#DC2626",
3297
+ shape: "rect"
3298
+ },
3299
+ {
3300
+ id: "confidential",
3301
+ title: "\u673A\u5BC6\u6587\u4EF6",
3302
+ subtitle: "CONFIDENTIAL",
3303
+ color: "#B91C1C",
3304
+ shape: "pill"
3305
+ },
3306
+ {
3307
+ id: "draft",
3308
+ title: "\u8349\u7A3F\u4EC5\u4F9B\u53C2\u8003",
3309
+ subtitle: "DRAFT ONLY",
3310
+ color: "#2563EB",
3311
+ shape: "pill"
3312
+ },
3313
+ {
3314
+ id: "reviewed",
3315
+ title: "\u5DF2\u5BA1\u6838",
3316
+ subtitle: "REVIEWED",
3317
+ color: "#0D9488",
3318
+ shape: "rect"
3319
+ },
3320
+ {
3321
+ id: "urgent",
3322
+ title: "\u7279\u6025\u529E\u7406",
3323
+ subtitle: "URGENT",
3324
+ color: "#EA580C",
3325
+ shape: "pill"
3326
+ },
3327
+ {
3328
+ id: "void",
3329
+ title: "\u5DF2\u4F5C\u5E9F",
3330
+ subtitle: "VOID",
3331
+ color: "#64748B",
3332
+ shape: "rect"
3333
+ },
3334
+ {
3335
+ id: "archived",
3336
+ title: "\u5DF2\u5F52\u6863",
3337
+ subtitle: "ARCHIVED",
3338
+ color: "#4F46E5",
3339
+ shape: "circle"
3340
+ }
3341
+ ];
3342
+ var PDF_STANDARD_STAMP_PRESET_MAP = PDF_STANDARD_STAMP_PRESETS.reduce(
3343
+ (acc, item) => {
3344
+ acc[item.id] = item;
3345
+ return acc;
3346
+ },
3347
+ {}
3348
+ );
3349
+ function getPdfStandardStampPreset(presetId) {
3350
+ if (!presetId) return void 0;
3351
+ return PDF_STANDARD_STAMP_PRESETS.find((p) => p.id === presetId);
3352
+ }
3353
+ function escapeXmlAttrOrText(raw) {
3354
+ return raw.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3355
+ }
3356
+ function sanitizeHexColor(color, fallback = "#DC2626") {
3357
+ const trimmed = (color ?? "").trim();
3358
+ if (/^#[0-9a-fA-F]{3,8}$/.test(trimmed)) {
3359
+ return trimmed;
3360
+ }
3361
+ return fallback;
3362
+ }
3363
+ function buildPresetStatusGlyphPath(presetId, cx, cy, r) {
3364
+ switch (presetId) {
3365
+ case "approved":
3366
+ case "reviewed":
3367
+ return `M ${cx - r * 0.55},${cy + r * 0.05} L ${cx - r * 0.15},${cy + r * 0.45} L ${cx + r * 0.6},${cy - r * 0.42}`;
3368
+ case "rejected":
3369
+ case "void":
3370
+ return `M ${cx - r * 0.45},${cy - r * 0.45} L ${cx + r * 0.45},${cy + r * 0.45} M ${cx + r * 0.45},${cy - r * 0.45} L ${cx - r * 0.45},${cy + r * 0.45}`;
3371
+ case "urgent":
3372
+ return `M ${cx + r * 0.1},${cy - r * 0.65} L ${cx - r * 0.42},${cy + r * 0.08} L ${cx + r * 0.04},${cy + r * 0.08} L ${cx - r * 0.12},${cy + r * 0.65} L ${cx + r * 0.45},${cy - r * 0.08} L ${cx - r * 0.02},${cy - r * 0.08} Z`;
3373
+ case "confidential":
3374
+ return `M ${cx},${cy - r * 0.62} L ${cx + r * 0.52},${cy - r * 0.35} L ${cx + r * 0.52},${cy + r * 0.12} C ${cx + r * 0.52},${cy + r * 0.45} ${cx + r * 0.25},${cy + r * 0.65} ${cx},${cy + r * 0.72} C ${cx - r * 0.25},${cy + r * 0.65} ${cx - r * 0.52},${cy + r * 0.45} ${cx - r * 0.52},${cy + r * 0.12} L ${cx - r * 0.52},${cy - r * 0.35} Z`;
3375
+ default:
3376
+ return `M ${cx},${cy - r * 0.6} L ${cx + r * 0.18},${cy - r * 0.18} L ${cx + r * 0.62},${cy - r * 0.14} L ${cx + r * 0.28},${cy + r * 0.16} L ${cx + r * 0.38},${cy + r * 0.6} L ${cx},${cy + r * 0.36} L ${cx - r * 0.38},${cy + r * 0.6} L ${cx - r * 0.28},${cy + r * 0.16} L ${cx - r * 0.62},${cy - r * 0.14} L ${cx - r * 0.18},${cy - r * 0.18} Z`;
3377
+ }
3378
+ }
3379
+ function buildPdfApprovalStampSvg(options) {
3380
+ const preset = getPdfStandardStampPreset(options.preset);
3381
+ const title = (options.title ?? preset?.title ?? "\u5DF2\u6279\u51C6").trim() || "\u5DF2\u6279\u51C6";
3382
+ const subtitle = (options.subtitle ?? preset?.subtitle ?? "").trim();
3383
+ const signer = (options.signer ?? "").trim();
3384
+ const dateText = (options.dateText ?? "").trim();
3385
+ const shape = options.shape ?? preset?.shape ?? "rect";
3386
+ const color = sanitizeHexColor(options.color, preset?.color ?? "#DC2626");
3387
+ const metaLine = [signer, dateText].filter(Boolean).join(" \xB7 ");
3388
+ if (shape === "circle") {
3389
+ const size = 120;
3390
+ const cx = 60;
3391
+ const cy = 60;
3392
+ const starPoints = "60,39 62.6,44.4 68.5,45.2 64.2,49.3 65.3,55.2 60,52.3 54.7,55.2 55.8,49.3 51.5,45.2 57.4,44.4";
3393
+ return [
3394
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">`,
3395
+ `<circle cx="${cx}" cy="${cy}" r="55" fill="${color}" fill-opacity="0.05" stroke="${color}" stroke-width="3.2"/>`,
3396
+ `<circle cx="${cx}" cy="${cy}" r="50" fill="none" stroke="${color}" stroke-width="1.1" stroke-dasharray="3 2"/>`,
3397
+ `<polygon points="${starPoints}" fill="${color}"/>`,
3398
+ `<line x1="20" y1="62" x2="100" y2="62" stroke="${color}" stroke-width="1"/>`,
3399
+ `<text x="${cx}" y="31" text-anchor="middle" font-family="PingFang SC, Microsoft YaHei, Helvetica, sans-serif" font-size="14" font-weight="bold" fill="${color}">${escapeXmlAttrOrText(title)}</text>`,
3400
+ subtitle ? `<text x="${cx}" y="77" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="9.5" font-weight="bold" fill="${color}">${escapeXmlAttrOrText(subtitle)}</text>` : "",
3401
+ metaLine ? `<text x="${cx}" y="92" text-anchor="middle" font-family="PingFang SC, Microsoft YaHei, Helvetica, sans-serif" font-size="8.2" fill="${color}">${escapeXmlAttrOrText(metaLine)}</text>` : "",
3402
+ "</svg>"
3403
+ ].filter(Boolean).join("");
3404
+ }
3405
+ const vbW = 188;
3406
+ const vbH = metaLine ? 74 : 58;
3407
+ const outerRx = shape === "pill" ? Math.round((vbH - 6) / 2) : 7;
3408
+ const innerRx = shape === "pill" ? Math.round((vbH - 13) / 2) : 4.5;
3409
+ const badgeCx = 27;
3410
+ const badgeCy = metaLine ? 25 : Math.round(vbH / 2);
3411
+ const glyphPath = buildPresetStatusGlyphPath(options.preset, badgeCx, badgeCy, 8.5);
3412
+ const isFilledGlyph = options.preset !== "approved" && options.preset !== "reviewed" && options.preset !== "rejected" && options.preset !== "void";
3413
+ const textCenterX = 108;
3414
+ const titleY = subtitle ? metaLine ? 23 : 26 : metaLine ? 29 : 34;
3415
+ const subtitleY = metaLine ? 38 : 43;
3416
+ return [
3417
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${vbW} ${vbH}" width="${vbW}" height="${vbH}">`,
3418
+ `<rect x="3" y="3" width="${vbW - 6}" height="${vbH - 6}" rx="${outerRx}" ry="${outerRx}" fill="${color}" fill-opacity="0.05" stroke="${color}" stroke-width="2.6"/>`,
3419
+ `<rect x="6.5" y="6.5" width="${vbW - 13}" height="${vbH - 13}" rx="${innerRx}" ry="${innerRx}" fill="none" stroke="${color}" stroke-width="0.9"/>`,
3420
+ `<circle cx="${badgeCx}" cy="${badgeCy}" r="11.5" fill="${color}" fill-opacity="0.1" stroke="${color}" stroke-width="1.3"/>`,
3421
+ isFilledGlyph ? `<path d="${glyphPath}" fill="${color}" stroke="none"/>` : `<path d="${glyphPath}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>`,
3422
+ `<text x="${textCenterX}" y="${titleY}" text-anchor="middle" font-family="PingFang SC, Microsoft YaHei, Helvetica, sans-serif" font-size="14.5" font-weight="bold" fill="${color}">${escapeXmlAttrOrText(title)}</text>`,
3423
+ subtitle ? `<text x="${textCenterX}" y="${subtitleY}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="9" font-weight="bold" fill="${color}">${escapeXmlAttrOrText(subtitle)}</text>` : "",
3424
+ metaLine ? `<line x1="16" y1="47" x2="${vbW - 16}" y2="47" stroke="${color}" stroke-width="0.9" stroke-dasharray="3 2"/>` : "",
3425
+ metaLine ? `<text x="${vbW / 2}" y="60" text-anchor="middle" font-family="PingFang SC, Microsoft YaHei, Helvetica, sans-serif" font-size="8.8" fill="${color}">${escapeXmlAttrOrText(metaLine)}</text>` : "",
3426
+ "</svg>"
3427
+ ].filter(Boolean).join("");
3428
+ }
3429
+ function unescapeXmlEntities(raw) {
3430
+ return raw.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
3431
+ }
3432
+ function extractSvgTextDescriptors(svgXml, boxWidthPt, boxHeightPt) {
3433
+ if (!svgXml || boxWidthPt <= 0 || boxHeightPt <= 0) return [];
3434
+ const vbMatch = /viewBox\s*=\s*["']([^"']+)["']/i.exec(svgXml);
3435
+ let vbX = 0;
3436
+ let vbY = 0;
3437
+ let vbW = boxWidthPt;
3438
+ let vbH = boxHeightPt;
3439
+ if (vbMatch) {
3440
+ const nums = vbMatch[1].trim().split(/[\s,]+/).map(Number);
3441
+ if (nums.length >= 4 && nums[2] > 0 && nums[3] > 0) {
3442
+ vbX = nums[0];
3443
+ vbY = nums[1];
3444
+ vbW = nums[2];
3445
+ vbH = nums[3];
3446
+ }
3447
+ }
3448
+ const scale = Math.min(boxWidthPt / vbW, boxHeightPt / vbH);
3449
+ const offsetX = (boxWidthPt - vbW * scale) / 2 - vbX * scale;
3450
+ const offsetY = (boxHeightPt - vbH * scale) / 2 - vbY * scale;
3451
+ const out = [];
3452
+ const textRe = /<text\b([^>]*)>([\s\S]*?)<\/text>/gi;
3453
+ let m;
3454
+ while ((m = textRe.exec(svgXml)) !== null) {
3455
+ const attrStr = m[1] ?? "";
3456
+ const inner = unescapeXmlEntities((m[2] ?? "").replace(/<[^>]+>/g, "").trim());
3457
+ if (!inner) continue;
3458
+ const getAttr = (name) => {
3459
+ const re = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i");
3460
+ const hit = re.exec(attrStr);
3461
+ return hit ? hit[1] ?? hit[2] : void 0;
3462
+ };
3463
+ const rawX = parseFloat(getAttr("x") ?? "0") || 0;
3464
+ const rawY = parseFloat(getAttr("y") ?? "0") || 0;
3465
+ const rawFs = parseFloat(getAttr("font-size") ?? "12") || 12;
3466
+ const anchor = (getAttr("text-anchor") ?? "start").toLowerCase();
3467
+ const weight = (getAttr("font-weight") ?? "normal").toLowerCase();
3468
+ const fill = getAttr("fill") ?? "#1B1C1F";
3469
+ const fontSizePt = Math.max(5, Math.round(rawFs * scale * 100) / 100);
3470
+ const xPt = offsetX + rawX * scale;
3471
+ const baselineYPt = offsetY + rawY * scale;
3472
+ const heightPt = Math.max(fontSizePt * 1.35, 8);
3473
+ const topPt = Math.max(0, baselineYPt - fontSizePt * 0.88);
3474
+ let align = "left";
3475
+ let leftPt = xPt;
3476
+ let widthPt = Math.max(24, boxWidthPt - xPt);
3477
+ if (anchor === "middle") {
3478
+ align = "center";
3479
+ widthPt = boxWidthPt;
3480
+ leftPt = 0;
3481
+ } else if (anchor === "end") {
3482
+ align = "right";
3483
+ widthPt = Math.max(24, xPt);
3484
+ leftPt = 0;
3485
+ }
3486
+ out.push({
3487
+ text: inner,
3488
+ leftPt,
3489
+ topPt,
3490
+ widthPt,
3491
+ heightPt,
3492
+ fontSizePt,
3493
+ bold: weight === "bold" || Number(weight) >= 600,
3494
+ color: fill,
3495
+ align
3496
+ });
3497
+ }
3498
+ return out;
3499
+ }
3500
+ function createPdfApprovalStampSvgElement(options) {
3501
+ const preset = getPdfStandardStampPreset(options.preset);
3502
+ const shape = options.shape ?? preset?.shape ?? "rect";
3503
+ const hasMeta = Boolean((options.signer ?? "").trim() || (options.dateText ?? "").trim());
3504
+ const svgContent = buildPdfApprovalStampSvg(options);
3505
+ const width = shape === "circle" ? 96 : 156;
3506
+ const height = shape === "circle" ? 96 : hasMeta ? 62 : 48;
3507
+ const title = (options.title ?? preset?.title ?? "\u5DF2\u6279\u51C6").trim() || "\u5DF2\u6279\u51C6";
3508
+ return {
3509
+ type: "svg" /* SVG */,
3510
+ name: `\u5BA1\u9605\u7B7E\u7AE0 \xB7 ${title}`,
3511
+ svgContent,
3512
+ opacity: 0.92,
3513
+ metadata: {
3514
+ stampPreset: options.preset ?? "custom",
3515
+ stampShape: shape,
3516
+ stampSigner: options.signer,
3517
+ stampDateText: options.dateText
3518
+ },
3519
+ transform: {
3520
+ left: options.left ?? 360,
3521
+ top: options.top ?? 64,
3522
+ width,
3523
+ height,
3524
+ angle: options.angle ?? -6
3525
+ }
3526
+ };
3527
+ }
3528
+ function createPdfApprovalStampElement(options) {
3529
+ const preset = getPdfStandardStampPreset(options.preset);
3530
+ const shape = options.shape ?? preset?.shape ?? "rect";
3531
+ const title = (options.title ?? preset?.title ?? "\u5DF2\u6279\u51C6").trim() || "\u5DF2\u6279\u51C6";
3532
+ const subtitle = (options.subtitle ?? preset?.subtitle ?? "").trim();
3533
+ const color = sanitizeHexColor(options.color, preset?.color ?? "#DC2626");
3534
+ const hasMeta = Boolean((options.signer ?? "").trim() || (options.dateText ?? "").trim());
3535
+ const svgContent = buildPdfApprovalStampSvg(options);
3536
+ return {
3537
+ type: "stamp" /* STAMP */,
3538
+ name: `\u5BA1\u9605\u7B7E\u7AE0 \xB7 ${title}`,
3539
+ preset: options.preset,
3540
+ stampShape: shape,
3541
+ primaryText: title,
3542
+ secondaryText: subtitle || void 0,
3543
+ signer: options.signer?.trim() || void 0,
3544
+ dateText: options.dateText?.trim() || void 0,
3545
+ svgContent,
3546
+ color,
3547
+ opacity: 0.92,
3548
+ transform: {
3549
+ left: options.left ?? 360,
3550
+ top: options.top ?? 64,
3551
+ width: shape === "circle" ? 96 : 156,
3552
+ height: shape === "circle" ? 96 : hasMeta ? 62 : 48,
3553
+ angle: options.angle ?? -6
3554
+ }
3555
+ };
3556
+ }
3557
+
3241
3558
  // src/exporter/pdf-2d-barcodes.ts
3242
3559
  function encodeBase64Utf8(str) {
3243
3560
  const bytes = new TextEncoder().encode(str);
@@ -4878,18 +5195,1034 @@ function renderBarcodeSvgDataUrlByFormat(format, raw, options) {
4878
5195
  }
4879
5196
 
4880
5197
  // src/exporter/pdf-native-text.ts
5198
+ import { generateRandomId as generateRandomId3, Tools as Tools2 } from "@univerjs/core";
4881
5199
  import {
4882
5200
  decodePDFRawStream,
4883
5201
  degrees,
5202
+ PDFArray as PDFArray2,
5203
+ PDFDict as PDFDict2,
5204
+ PDFDocument as PDFDocument2,
5205
+ PDFName as PDFName2,
5206
+ PDFNumber as PDFNumber2,
5207
+ PDFRawStream as PDFRawStream2,
5208
+ PDFRef as PDFRef2,
5209
+ PDFStream as PDFStream2
5210
+ } from "pdf-lib";
5211
+
5212
+ // src/exporter/pdf-security.ts
5213
+ import {
4884
5214
  PDFArray,
4885
5215
  PDFDict,
4886
5216
  PDFDocument,
5217
+ PDFHexString,
4887
5218
  PDFName,
4888
5219
  PDFNumber,
4889
5220
  PDFRawStream,
4890
5221
  PDFRef,
4891
- PDFStream
5222
+ PDFStream,
5223
+ PDFString
4892
5224
  } from "pdf-lib";
5225
+ var PdfSecurityError = class extends Error {
5226
+ constructor(code, message) {
5227
+ super(message);
5228
+ this.name = "PdfSecurityError";
5229
+ this.code = code;
5230
+ }
5231
+ };
5232
+ var PDF_PASSWORD_PADDING = new Uint8Array([
5233
+ 40,
5234
+ 191,
5235
+ 78,
5236
+ 94,
5237
+ 78,
5238
+ 117,
5239
+ 138,
5240
+ 65,
5241
+ 100,
5242
+ 0,
5243
+ 78,
5244
+ 86,
5245
+ 255,
5246
+ 250,
5247
+ 1,
5248
+ 8,
5249
+ 46,
5250
+ 46,
5251
+ 0,
5252
+ 182,
5253
+ 208,
5254
+ 104,
5255
+ 62,
5256
+ 128,
5257
+ 47,
5258
+ 12,
5259
+ 169,
5260
+ 254,
5261
+ 100,
5262
+ 83,
5263
+ 105,
5264
+ 122
5265
+ ]);
5266
+ var DEFAULT_ALL_PERMISSIONS = Object.freeze({
5267
+ print: true,
5268
+ highResPrint: true,
5269
+ modify: true,
5270
+ copy: true,
5271
+ annotate: true,
5272
+ fillForms: true,
5273
+ assemble: true
5274
+ });
5275
+ var MD5_SHIFTS = [
5276
+ 7,
5277
+ 12,
5278
+ 17,
5279
+ 22,
5280
+ 7,
5281
+ 12,
5282
+ 17,
5283
+ 22,
5284
+ 7,
5285
+ 12,
5286
+ 17,
5287
+ 22,
5288
+ 7,
5289
+ 12,
5290
+ 17,
5291
+ 22,
5292
+ 5,
5293
+ 9,
5294
+ 14,
5295
+ 20,
5296
+ 5,
5297
+ 9,
5298
+ 14,
5299
+ 20,
5300
+ 5,
5301
+ 9,
5302
+ 14,
5303
+ 20,
5304
+ 5,
5305
+ 9,
5306
+ 14,
5307
+ 20,
5308
+ 4,
5309
+ 11,
5310
+ 16,
5311
+ 23,
5312
+ 4,
5313
+ 11,
5314
+ 16,
5315
+ 23,
5316
+ 4,
5317
+ 11,
5318
+ 16,
5319
+ 23,
5320
+ 4,
5321
+ 11,
5322
+ 16,
5323
+ 23,
5324
+ 6,
5325
+ 10,
5326
+ 15,
5327
+ 21,
5328
+ 6,
5329
+ 10,
5330
+ 15,
5331
+ 21,
5332
+ 6,
5333
+ 10,
5334
+ 15,
5335
+ 21,
5336
+ 6,
5337
+ 10,
5338
+ 15,
5339
+ 21
5340
+ ];
5341
+ var MD5_K = (() => {
5342
+ const table = new Uint32Array(64);
5343
+ for (let i = 0; i < 64; i++) {
5344
+ table[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
5345
+ }
5346
+ return table;
5347
+ })();
5348
+ function rotl32(x, n) {
5349
+ return (x << n | x >>> 32 - n) >>> 0;
5350
+ }
5351
+ function md5Bytes(data) {
5352
+ const msgLen = data.byteLength;
5353
+ const rem = (msgLen + 9) % 64;
5354
+ const padZeroes = rem === 0 ? 0 : 64 - rem;
5355
+ const totalLen = msgLen + 9 + padZeroes;
5356
+ const buf = new Uint8Array(totalLen);
5357
+ buf.set(data, 0);
5358
+ buf[msgLen] = 128;
5359
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
5360
+ const bitLenLow = msgLen * 8 >>> 0;
5361
+ const bitLenHigh = Math.floor(msgLen * 8 / 4294967296) >>> 0;
5362
+ view.setUint32(totalLen - 8, bitLenLow, true);
5363
+ view.setUint32(totalLen - 4, bitLenHigh, true);
5364
+ let a0 = 1732584193;
5365
+ let b0 = 4023233417;
5366
+ let c0 = 2562383102;
5367
+ let d0 = 271733878;
5368
+ const M = new Uint32Array(16);
5369
+ for (let offset = 0; offset < totalLen; offset += 64) {
5370
+ for (let j = 0; j < 16; j++) {
5371
+ M[j] = view.getUint32(offset + j * 4, true);
5372
+ }
5373
+ let A = a0;
5374
+ let B = b0;
5375
+ let C = c0;
5376
+ let D = d0;
5377
+ for (let i = 0; i < 64; i++) {
5378
+ let F;
5379
+ let g;
5380
+ if (i < 16) {
5381
+ F = B & C | ~B & D;
5382
+ g = i;
5383
+ } else if (i < 32) {
5384
+ F = D & B | ~D & C;
5385
+ g = (5 * i + 1) % 16;
5386
+ } else if (i < 48) {
5387
+ F = B ^ C ^ D;
5388
+ g = (3 * i + 5) % 16;
5389
+ } else {
5390
+ F = C ^ (B | ~D);
5391
+ g = 7 * i % 16;
5392
+ }
5393
+ const sum = A + F + MD5_K[i] + M[g] >>> 0;
5394
+ A = D;
5395
+ D = C;
5396
+ C = B;
5397
+ B = B + rotl32(sum, MD5_SHIFTS[i]) >>> 0;
5398
+ }
5399
+ a0 = a0 + A >>> 0;
5400
+ b0 = b0 + B >>> 0;
5401
+ c0 = c0 + C >>> 0;
5402
+ d0 = d0 + D >>> 0;
5403
+ }
5404
+ const out = new Uint8Array(16);
5405
+ const outView = new DataView(out.buffer);
5406
+ outView.setUint32(0, a0, true);
5407
+ outView.setUint32(4, b0, true);
5408
+ outView.setUint32(8, c0, true);
5409
+ outView.setUint32(12, d0, true);
5410
+ return out;
5411
+ }
5412
+ function rc4Bytes(key, data) {
5413
+ const keyLen = key.byteLength;
5414
+ if (keyLen === 0) return data.slice();
5415
+ const S = new Uint8Array(256);
5416
+ for (let i2 = 0; i2 < 256; i2++) {
5417
+ S[i2] = i2;
5418
+ }
5419
+ let j = 0;
5420
+ for (let i2 = 0; i2 < 256; i2++) {
5421
+ j = j + S[i2] + key[i2 % keyLen] & 255;
5422
+ const tmp = S[i2];
5423
+ S[i2] = S[j];
5424
+ S[j] = tmp;
5425
+ }
5426
+ const out = new Uint8Array(data.byteLength);
5427
+ let i = 0;
5428
+ j = 0;
5429
+ for (let k = 0; k < data.byteLength; k++) {
5430
+ i = i + 1 & 255;
5431
+ j = j + S[i] & 255;
5432
+ const tmp = S[i];
5433
+ S[i] = S[j];
5434
+ S[j] = tmp;
5435
+ out[k] = data[k] ^ S[S[i] + S[j] & 255];
5436
+ }
5437
+ return out;
5438
+ }
5439
+ function bytesToHex(bytes) {
5440
+ let hex = "";
5441
+ for (let i = 0; i < bytes.byteLength; i++) {
5442
+ hex += bytes[i].toString(16).padStart(2, "0").toUpperCase();
5443
+ }
5444
+ return hex;
5445
+ }
5446
+ function hexToBytes(hexRaw) {
5447
+ const cleaned = hexRaw.replace(/\s+/g, "");
5448
+ const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
5449
+ const out = new Uint8Array(padded.length / 2);
5450
+ for (let i = 0; i < out.byteLength; i++) {
5451
+ out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16) || 0;
5452
+ }
5453
+ return out;
5454
+ }
5455
+ function encodePasswordToBytes(password) {
5456
+ if (!password) return new Uint8Array(0);
5457
+ let hasHighCodePoint = false;
5458
+ for (let i = 0; i < password.length; i++) {
5459
+ if (password.charCodeAt(i) > 255) {
5460
+ hasHighCodePoint = true;
5461
+ break;
5462
+ }
5463
+ }
5464
+ if (hasHighCodePoint) {
5465
+ return new TextEncoder().encode(password);
5466
+ }
5467
+ const out = new Uint8Array(password.length);
5468
+ for (let i = 0; i < password.length; i++) {
5469
+ out[i] = password.charCodeAt(i) & 255;
5470
+ }
5471
+ return out;
5472
+ }
5473
+ function padPdfPassword(password) {
5474
+ const raw = password instanceof Uint8Array ? password : encodePasswordToBytes(password);
5475
+ const out = new Uint8Array(32);
5476
+ const copyLen = Math.min(32, raw.byteLength);
5477
+ out.set(raw.subarray(0, copyLen), 0);
5478
+ if (copyLen < 32) {
5479
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 32 - copyLen), copyLen);
5480
+ }
5481
+ return out;
5482
+ }
5483
+ function encodePdfPermissionFlags(permissions, revision = 3) {
5484
+ const allowPrint = permissions?.print !== false;
5485
+ const allowModify = permissions?.modify !== false;
5486
+ const allowCopy = permissions?.copy !== false;
5487
+ const allowAnnotate = permissions?.annotate !== false;
5488
+ const allowFillForms = permissions?.fillForms !== false;
5489
+ const allowAssemble = permissions?.assemble !== false;
5490
+ const allowHighResPrint = permissions?.highResPrint !== void 0 ? Boolean(permissions.highResPrint) : allowPrint;
5491
+ let mask = 4294963392 | 1 << 9;
5492
+ if (allowPrint) mask |= 1 << 2;
5493
+ if (allowModify) mask |= 1 << 3;
5494
+ if (allowCopy) mask |= 1 << 4;
5495
+ if (allowAnnotate) mask |= 1 << 5;
5496
+ if (revision >= 3) {
5497
+ if (allowFillForms) mask |= 1 << 8;
5498
+ if (allowAssemble) mask |= 1 << 10;
5499
+ if (allowHighResPrint && allowPrint) mask |= 1 << 11;
5500
+ } else {
5501
+ mask |= 1 << 8 | 1 << 10 | 1 << 11;
5502
+ }
5503
+ return mask | 0;
5504
+ }
5505
+ function decodePdfPermissionFlags(pMask, revision = 3) {
5506
+ const print = (pMask & 1 << 2) !== 0;
5507
+ const modify = (pMask & 1 << 3) !== 0;
5508
+ const copy = (pMask & 1 << 4) !== 0;
5509
+ const annotate = (pMask & 1 << 5) !== 0;
5510
+ const fillForms = revision >= 3 ? (pMask & 1 << 8) !== 0 : annotate;
5511
+ const assemble = revision >= 3 ? (pMask & 1 << 10) !== 0 : modify;
5512
+ const highResPrint = revision >= 3 ? print && (pMask & 1 << 11) !== 0 : print;
5513
+ return {
5514
+ print,
5515
+ highResPrint,
5516
+ modify,
5517
+ copy,
5518
+ annotate,
5519
+ fillForms,
5520
+ assemble
5521
+ };
5522
+ }
5523
+ function isPdfSecurityActive(security) {
5524
+ if (!security || security.enabled === false) return false;
5525
+ if (security.enabled === true) return true;
5526
+ if (security.userPassword && security.userPassword.length > 0) return true;
5527
+ if (security.ownerPassword && security.ownerPassword.length > 0) return true;
5528
+ if (security.permissions && Object.keys(security.permissions).length > 0) return true;
5529
+ return false;
5530
+ }
5531
+ function computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLengthBits) {
5532
+ const effectiveOwner = ownerPassword || userPassword || "";
5533
+ const ownerPad = padPdfPassword(effectiveOwner);
5534
+ let hash = md5Bytes(ownerPad);
5535
+ if (revision >= 3) {
5536
+ for (let i = 0; i < 50; i++) {
5537
+ hash = md5Bytes(hash);
5538
+ }
5539
+ }
5540
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5541
+ const userPad = padPdfPassword(userPassword);
5542
+ let encrypted = rc4Bytes(hash.subarray(0, keyByteLen), userPad);
5543
+ if (revision >= 3) {
5544
+ const derivedKey = new Uint8Array(keyByteLen);
5545
+ for (let iter = 1; iter <= 19; iter++) {
5546
+ for (let k = 0; k < keyByteLen; k++) {
5547
+ derivedKey[k] = hash[k] ^ iter;
5548
+ }
5549
+ encrypted = rc4Bytes(derivedKey, encrypted);
5550
+ }
5551
+ }
5552
+ return encrypted;
5553
+ }
5554
+ function computeFileEncryptionKeyFromPadded(paddedUserPassword, oValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5555
+ const buf = new Uint8Array(32 + oValue.byteLength + 4 + fileId.byteLength);
5556
+ let offset = 0;
5557
+ buf.set(paddedUserPassword.subarray(0, 32), offset);
5558
+ offset += 32;
5559
+ buf.set(oValue, offset);
5560
+ offset += oValue.byteLength;
5561
+ buf[offset++] = pFlagsSigned & 255;
5562
+ buf[offset++] = pFlagsSigned >>> 8 & 255;
5563
+ buf[offset++] = pFlagsSigned >>> 16 & 255;
5564
+ buf[offset++] = pFlagsSigned >>> 24 & 255;
5565
+ buf.set(fileId, offset);
5566
+ let hash = md5Bytes(buf);
5567
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5568
+ if (revision >= 3) {
5569
+ for (let i = 0; i < 50; i++) {
5570
+ hash = md5Bytes(hash.subarray(0, keyByteLen));
5571
+ }
5572
+ }
5573
+ return hash.subarray(0, keyByteLen);
5574
+ }
5575
+ function computeUserPasswordValue(encryptionKey, fileId, revision) {
5576
+ if (revision === 2) {
5577
+ return rc4Bytes(encryptionKey, PDF_PASSWORD_PADDING);
5578
+ }
5579
+ const hashInput = new Uint8Array(32 + fileId.byteLength);
5580
+ hashInput.set(PDF_PASSWORD_PADDING, 0);
5581
+ hashInput.set(fileId, 32);
5582
+ let check = rc4Bytes(encryptionKey, md5Bytes(hashInput));
5583
+ const keyLen = encryptionKey.byteLength;
5584
+ const derivedKey = new Uint8Array(keyLen);
5585
+ for (let iter = 1; iter <= 19; iter++) {
5586
+ for (let k = 0; k < keyLen; k++) {
5587
+ derivedKey[k] = encryptionKey[k] ^ iter;
5588
+ }
5589
+ check = rc4Bytes(derivedKey, check);
5590
+ }
5591
+ const out = new Uint8Array(32);
5592
+ out.set(check.subarray(0, 16), 0);
5593
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 16), 16);
5594
+ return out;
5595
+ }
5596
+ function authenticatePaddedUserPassword(paddedPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5597
+ const candidateKey = computeFileEncryptionKeyFromPadded(
5598
+ paddedPassword,
5599
+ oValue,
5600
+ pFlagsSigned,
5601
+ fileId,
5602
+ revision,
5603
+ keyLengthBits
5604
+ );
5605
+ const expectedU = computeUserPasswordValue(candidateKey, fileId, revision);
5606
+ const compareLen = revision >= 3 ? 16 : 32;
5607
+ if (uValue.byteLength < compareLen) return null;
5608
+ let diff = 0;
5609
+ for (let i = 0; i < compareLen; i++) {
5610
+ diff |= expectedU[i] ^ uValue[i];
5611
+ }
5612
+ return diff === 0 ? candidateKey : null;
5613
+ }
5614
+ function authenticateOwnerPassword(ownerPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
5615
+ const ownerPad = padPdfPassword(ownerPassword);
5616
+ let hash = md5Bytes(ownerPad);
5617
+ if (revision >= 3) {
5618
+ for (let i = 0; i < 50; i++) {
5619
+ hash = md5Bytes(hash);
5620
+ }
5621
+ }
5622
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
5623
+ let recoveredUserPad;
5624
+ if (revision >= 3) {
5625
+ recoveredUserPad = oValue.slice(0, 32);
5626
+ const derivedKey = new Uint8Array(keyByteLen);
5627
+ for (let iter = 19; iter >= 0; iter--) {
5628
+ for (let k = 0; k < keyByteLen; k++) {
5629
+ derivedKey[k] = hash[k] ^ iter;
5630
+ }
5631
+ recoveredUserPad = rc4Bytes(derivedKey, recoveredUserPad);
5632
+ }
5633
+ } else {
5634
+ recoveredUserPad = rc4Bytes(hash.subarray(0, 5), oValue.subarray(0, 32));
5635
+ }
5636
+ return authenticatePaddedUserPassword(
5637
+ recoveredUserPad,
5638
+ oValue,
5639
+ uValue,
5640
+ pFlagsSigned,
5641
+ fileId,
5642
+ revision,
5643
+ keyLengthBits
5644
+ );
5645
+ }
5646
+ function buildObjectEncryptionKey(encryptionKey, objectNumber, generationNumber) {
5647
+ const n = encryptionKey.byteLength;
5648
+ const buf = new Uint8Array(n + 5);
5649
+ buf.set(encryptionKey, 0);
5650
+ buf[n] = objectNumber & 255;
5651
+ buf[n + 1] = objectNumber >>> 8 & 255;
5652
+ buf[n + 2] = objectNumber >>> 16 & 255;
5653
+ buf[n + 3] = generationNumber & 255;
5654
+ buf[n + 4] = generationNumber >>> 8 & 255;
5655
+ const digest = md5Bytes(buf);
5656
+ return digest.subarray(0, Math.min(n + 5, 16));
5657
+ }
5658
+ function decodePdfLiteralBodyBytes(body) {
5659
+ const bytes = [];
5660
+ for (let i = 0; i < body.length; i++) {
5661
+ const ch = body.charCodeAt(i) & 255;
5662
+ if (ch !== 92) {
5663
+ bytes.push(ch);
5664
+ continue;
5665
+ }
5666
+ if (i + 1 >= body.length) break;
5667
+ const next = body.charCodeAt(++i) & 255;
5668
+ if (next === 13) {
5669
+ if (i + 1 < body.length && (body.charCodeAt(i + 1) & 255) === 10) i++;
5670
+ } else if (next === 10) {
5671
+ } else if (next === 110) {
5672
+ bytes.push(10);
5673
+ } else if (next === 114) {
5674
+ bytes.push(13);
5675
+ } else if (next === 116) {
5676
+ bytes.push(9);
5677
+ } else if (next === 98) {
5678
+ bytes.push(8);
5679
+ } else if (next === 102) {
5680
+ bytes.push(12);
5681
+ } else if (next >= 48 && next <= 55) {
5682
+ let oct = String.fromCharCode(next);
5683
+ for (let k = 0; k < 2 && i + 1 < body.length; k++) {
5684
+ const peek = body.charCodeAt(i + 1) & 255;
5685
+ if (peek >= 48 && peek <= 55) {
5686
+ oct += String.fromCharCode(peek);
5687
+ i++;
5688
+ } else {
5689
+ break;
5690
+ }
5691
+ }
5692
+ bytes.push(parseInt(oct, 8) & 255);
5693
+ } else {
5694
+ bytes.push(next);
5695
+ }
5696
+ }
5697
+ return new Uint8Array(bytes);
5698
+ }
5699
+ function extractPdfStringRawBytes(strObj) {
5700
+ if (strObj instanceof PDFHexString) {
5701
+ return strObj.asBytes();
5702
+ }
5703
+ const serialized = strObj.asString();
5704
+ const inner = serialized.startsWith("(") && serialized.endsWith(")") ? serialized.slice(1, -1) : serialized;
5705
+ return decodePdfLiteralBodyBytes(inner);
5706
+ }
5707
+ function isSignatureDict(dict) {
5708
+ const typeVal = dict.get(PDFName.of("Type"));
5709
+ if (typeVal instanceof PDFName && typeVal.asString() === "/Sig") return true;
5710
+ const ftVal = dict.get(PDFName.of("FT"));
5711
+ if (ftVal instanceof PDFName && ftVal.asString() === "/Sig") return true;
5712
+ return false;
5713
+ }
5714
+ function transformPdfObjectStringsWithRc4(obj, objKey) {
5715
+ if (obj instanceof PDFHexString || obj instanceof PDFString) {
5716
+ const raw = extractPdfStringRawBytes(obj);
5717
+ const transformed = rc4Bytes(objKey, raw);
5718
+ return PDFHexString.of(bytesToHex(transformed));
5719
+ }
5720
+ if (obj instanceof PDFArray) {
5721
+ for (let i = 0; i < obj.size(); i++) {
5722
+ const item = obj.get(i);
5723
+ const next = transformPdfObjectStringsWithRc4(item, objKey);
5724
+ if (next !== item) {
5725
+ obj.set(i, next);
5726
+ }
5727
+ }
5728
+ return obj;
5729
+ }
5730
+ if (obj instanceof PDFDict) {
5731
+ const isSig = isSignatureDict(obj);
5732
+ for (const [key, val] of obj.entries()) {
5733
+ if (isSig && key.asString() === "/Contents") {
5734
+ continue;
5735
+ }
5736
+ const next = transformPdfObjectStringsWithRc4(val, objKey);
5737
+ if (next !== val) {
5738
+ obj.set(key, next);
5739
+ }
5740
+ }
5741
+ return obj;
5742
+ }
5743
+ return obj;
5744
+ }
5745
+ function extractOrCreateDocumentFileId(pdfDoc) {
5746
+ const existingId = pdfDoc.context.trailerInfo.ID;
5747
+ if (existingId) {
5748
+ const idArr = existingId instanceof PDFArray ? existingId : pdfDoc.context.lookupMaybe(existingId, PDFArray);
5749
+ if (idArr && idArr.size() > 0) {
5750
+ const first = idArr.get(0);
5751
+ if (first instanceof PDFHexString || first instanceof PDFString) {
5752
+ const bytes = extractPdfStringRawBytes(first);
5753
+ if (bytes.byteLength > 0) {
5754
+ const hex = bytesToHex(bytes);
5755
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
5756
+ PDFHexString.of(hex),
5757
+ PDFHexString.of(hex)
5758
+ ]);
5759
+ return bytes;
5760
+ }
5761
+ }
5762
+ }
5763
+ }
5764
+ const seedBytes = new Uint8Array(32);
5765
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
5766
+ globalThis.crypto.getRandomValues(seedBytes);
5767
+ } else {
5768
+ const fallbackText = `univer-pdf-${Date.now()}-${Math.random()}-${pdfDoc.getPageCount()}`;
5769
+ const enc = new TextEncoder().encode(fallbackText);
5770
+ seedBytes.set(enc.subarray(0, Math.min(32, enc.byteLength)));
5771
+ }
5772
+ const fileId = md5Bytes(seedBytes);
5773
+ const idHex = bytesToHex(fileId);
5774
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
5775
+ PDFHexString.of(idHex),
5776
+ PDFHexString.of(idHex)
5777
+ ]);
5778
+ return fileId;
5779
+ }
5780
+ async function applyPdfSecurityToDocument(pdfDoc, security) {
5781
+ if (security.enabled === false) return;
5782
+ await pdfDoc.flush();
5783
+ const keyLength = security.keyLength === 40 ? 40 : 128;
5784
+ const version = keyLength === 40 ? 1 : 2;
5785
+ const revision = keyLength === 40 ? 2 : 3;
5786
+ const userPassword = security.userPassword ?? "";
5787
+ const ownerPassword = security.ownerPassword && security.ownerPassword.length > 0 ? security.ownerPassword : userPassword.length > 0 ? userPassword : "univer-pdf-owner-guard";
5788
+ const fileId = extractOrCreateDocumentFileId(pdfDoc);
5789
+ const pSigned = encodePdfPermissionFlags(security.permissions, revision);
5790
+ const oBytes = computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLength);
5791
+ const encryptionKey = computeFileEncryptionKeyFromPadded(
5792
+ padPdfPassword(userPassword),
5793
+ oBytes,
5794
+ pSigned,
5795
+ fileId,
5796
+ revision,
5797
+ keyLength
5798
+ );
5799
+ const uBytes = computeUserPasswordValue(encryptionKey, fileId, revision);
5800
+ const idRef = pdfDoc.context.trailerInfo.ID instanceof PDFRef ? pdfDoc.context.trailerInfo.ID : null;
5801
+ for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
5802
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
5803
+ continue;
5804
+ }
5805
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
5806
+ if (obj instanceof PDFRawStream) {
5807
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
5808
+ const encryptedStream = rc4Bytes(objKey, obj.contents);
5809
+ obj.dict.set(PDFName.of("Length"), PDFNumber.of(encryptedStream.byteLength));
5810
+ pdfDoc.context.assign(ref, PDFRawStream.of(obj.dict, encryptedStream));
5811
+ } else if (obj instanceof PDFStream) {
5812
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
5813
+ const encodedContents = obj.getContents();
5814
+ const encryptedStream = rc4Bytes(objKey, encodedContents);
5815
+ obj.dict.set(PDFName.of("Length"), PDFNumber.of(encryptedStream.byteLength));
5816
+ pdfDoc.context.assign(ref, PDFRawStream.of(obj.dict, encryptedStream));
5817
+ } else {
5818
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
5819
+ if (next !== obj) {
5820
+ pdfDoc.context.assign(ref, next);
5821
+ }
5822
+ }
5823
+ }
5824
+ const encryptDict = pdfDoc.context.obj({
5825
+ Filter: PDFName.of("Standard"),
5826
+ V: PDFNumber.of(version),
5827
+ R: PDFNumber.of(revision),
5828
+ Length: PDFNumber.of(keyLength),
5829
+ P: PDFNumber.of(pSigned),
5830
+ O: PDFHexString.of(bytesToHex(oBytes)),
5831
+ U: PDFHexString.of(bytesToHex(uBytes))
5832
+ });
5833
+ const encryptRef = pdfDoc.context.register(encryptDict);
5834
+ pdfDoc.context.trailerInfo.Encrypt = encryptRef;
5835
+ }
5836
+ async function encryptPdfBytes(pdfBytes, security) {
5837
+ if (!security || security.enabled === false) {
5838
+ return pdfBytes.slice();
5839
+ }
5840
+ const cleanBytes = inspectPdfEncryption(pdfBytes).encrypted ? await decryptPdfBytes(pdfBytes, security.ownerPassword || security.userPassword || "") : pdfBytes;
5841
+ const pdfDoc = await PDFDocument.load(cleanBytes, { updateMetadata: false });
5842
+ await applyPdfSecurityToDocument(pdfDoc, security);
5843
+ return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false });
5844
+ }
5845
+ function bytesToLatin1(bytes) {
5846
+ let out = "";
5847
+ const chunk = 32768;
5848
+ for (let i = 0; i < bytes.byteLength; i += chunk) {
5849
+ out += String.fromCharCode(...bytes.subarray(i, i + chunk));
5850
+ }
5851
+ return out;
5852
+ }
5853
+ function extractBalancedPdfDict(text, startIdx) {
5854
+ const openIdx = text.indexOf("<<", startIdx);
5855
+ if (openIdx < 0) return null;
5856
+ let depth = 0;
5857
+ let inLiteral = false;
5858
+ let literalDepth = 0;
5859
+ for (let i = openIdx; i < text.length; i++) {
5860
+ const ch = text.charCodeAt(i);
5861
+ if (inLiteral) {
5862
+ if (ch === 92) {
5863
+ i++;
5864
+ continue;
5865
+ }
5866
+ if (ch === 40) literalDepth++;
5867
+ else if (ch === 41) {
5868
+ literalDepth--;
5869
+ if (literalDepth <= 0) {
5870
+ inLiteral = false;
5871
+ }
5872
+ }
5873
+ continue;
5874
+ }
5875
+ if (ch === 40) {
5876
+ inLiteral = true;
5877
+ literalDepth = 1;
5878
+ continue;
5879
+ }
5880
+ if (ch === 37) {
5881
+ while (i < text.length && text.charCodeAt(i) !== 10 && text.charCodeAt(i) !== 13) {
5882
+ i++;
5883
+ }
5884
+ continue;
5885
+ }
5886
+ if (ch === 60 && text.charCodeAt(i + 1) === 60) {
5887
+ depth++;
5888
+ i++;
5889
+ continue;
5890
+ }
5891
+ if (ch === 62 && text.charCodeAt(i + 1) === 62) {
5892
+ depth--;
5893
+ i++;
5894
+ if (depth === 0) {
5895
+ return text.slice(openIdx, i + 1);
5896
+ }
5897
+ }
5898
+ }
5899
+ return null;
5900
+ }
5901
+ function parsePdfStringTokenAfterKey(dictText, keyName) {
5902
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*`);
5903
+ const match = re.exec(dictText);
5904
+ if (!match) return null;
5905
+ let pos = match.index + match[0].length;
5906
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5907
+ if (pos >= dictText.length) return null;
5908
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5909
+ const close = dictText.indexOf(">", pos + 1);
5910
+ if (close < 0) return null;
5911
+ return hexToBytes(dictText.slice(pos + 1, close));
5912
+ }
5913
+ if (dictText[pos] === "(") {
5914
+ let depth = 1;
5915
+ let i = pos + 1;
5916
+ while (i < dictText.length && depth > 0) {
5917
+ const ch = dictText.charCodeAt(i);
5918
+ if (ch === 92) {
5919
+ i += 2;
5920
+ continue;
5921
+ }
5922
+ if (ch === 40) depth++;
5923
+ else if (ch === 41) depth--;
5924
+ i++;
5925
+ }
5926
+ if (depth === 0) {
5927
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
5928
+ }
5929
+ }
5930
+ return null;
5931
+ }
5932
+ function parseFirstPdfArrayStringBytes(dictText, keyName) {
5933
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*\\[`);
5934
+ const match = re.exec(dictText);
5935
+ if (!match) return null;
5936
+ let pos = match.index + match[0].length;
5937
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
5938
+ if (pos >= dictText.length) return null;
5939
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
5940
+ const close = dictText.indexOf(">", pos + 1);
5941
+ if (close >= 0) return hexToBytes(dictText.slice(pos + 1, close));
5942
+ } else if (dictText[pos] === "(") {
5943
+ let depth = 1;
5944
+ let i = pos + 1;
5945
+ while (i < dictText.length && depth > 0) {
5946
+ const ch = dictText.charCodeAt(i);
5947
+ if (ch === 92) {
5948
+ i += 2;
5949
+ continue;
5950
+ }
5951
+ if (ch === 40) depth++;
5952
+ else if (ch === 41) depth--;
5953
+ i++;
5954
+ }
5955
+ if (depth === 0) {
5956
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
5957
+ }
5958
+ }
5959
+ return null;
5960
+ }
5961
+ function parseRawEncryptFromPdfBytes(pdfBytes) {
5962
+ if (!pdfBytes || pdfBytes.byteLength < 16) return null;
5963
+ const rawText = bytesToLatin1(pdfBytes);
5964
+ let containerDict = null;
5965
+ let searchEnd = rawText.length;
5966
+ while (searchEnd > 0) {
5967
+ const trailerIdx = rawText.lastIndexOf("trailer", searchEnd - 1);
5968
+ if (trailerIdx < 0) break;
5969
+ const prevCh = trailerIdx > 0 ? rawText[trailerIdx - 1] : "\n";
5970
+ const afterCh = rawText[trailerIdx + 7] ?? " ";
5971
+ if (/[\s\r\n>]/.test(prevCh) && /[\s\r\n<]/.test(afterCh)) {
5972
+ const candidate = extractBalancedPdfDict(rawText, trailerIdx + 7);
5973
+ if (candidate && /\/Encrypt\b/.test(candidate)) {
5974
+ containerDict = candidate;
5975
+ break;
5976
+ }
5977
+ if (candidate && !containerDict) {
5978
+ containerDict = candidate;
5979
+ }
5980
+ }
5981
+ searchEnd = trailerIdx;
5982
+ }
5983
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5984
+ const xrefMatch = /<<[\s\S]{0,2048}?\/Type\s*\/XRef[\s\S]{0,2048}?>>/.exec(rawText);
5985
+ if (xrefMatch && /\/Encrypt\b/.test(xrefMatch[0])) {
5986
+ containerDict = xrefMatch[0];
5987
+ }
5988
+ }
5989
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
5990
+ return null;
5991
+ }
5992
+ let encryptDictText = null;
5993
+ const refMatch = /\/Encrypt\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
5994
+ if (refMatch) {
5995
+ const objNum = refMatch[1];
5996
+ const genNum = refMatch[2];
5997
+ const objRe = new RegExp(`(?:^|[\\r\\n\\s])${objNum}\\s+${genNum}\\s+obj\\b`, "g");
5998
+ let lastObjMatch = null;
5999
+ let m;
6000
+ while ((m = objRe.exec(rawText)) !== null) {
6001
+ lastObjMatch = m;
6002
+ }
6003
+ if (lastObjMatch) {
6004
+ encryptDictText = extractBalancedPdfDict(rawText, lastObjMatch.index + lastObjMatch[0].length);
6005
+ }
6006
+ } else if (/\/Encrypt\s*<</.test(containerDict)) {
6007
+ const inlineIdx = containerDict.search(/\/Encrypt\s*<</);
6008
+ encryptDictText = extractBalancedPdfDict(containerDict, inlineIdx);
6009
+ }
6010
+ if (!encryptDictText) return null;
6011
+ const filterMatch = /\/Filter\s*\/([A-Za-z0-9_.+-]+)/.exec(encryptDictText);
6012
+ const vMatch = /\/V\s+(-?\d+)/.exec(encryptDictText);
6013
+ const rMatch = /\/R\s+(-?\d+)/.exec(encryptDictText);
6014
+ const lenMatch = /\/Length\s+(\d+)/.exec(encryptDictText);
6015
+ const pMatch = /\/P\s+(-?\d+)/.exec(encryptDictText);
6016
+ const filter = filterMatch ? filterMatch[1] : "Standard";
6017
+ const version = vMatch ? parseInt(vMatch[1], 10) : 1;
6018
+ const revision = rMatch ? parseInt(rMatch[1], 10) : version >= 2 ? 3 : 2;
6019
+ const keyLength = lenMatch ? parseInt(lenMatch[1], 10) : version >= 2 ? 128 : 40;
6020
+ const pSigned = pMatch ? parseInt(pMatch[1], 10) | 0 : -4;
6021
+ const oBytes = parsePdfStringTokenAfterKey(encryptDictText, "O") ?? new Uint8Array(0);
6022
+ const uBytes = parsePdfStringTokenAfterKey(encryptDictText, "U") ?? new Uint8Array(0);
6023
+ let fileId = parseFirstPdfArrayStringBytes(containerDict, "ID");
6024
+ if (!fileId) {
6025
+ const idRefMatch = /\/ID\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
6026
+ if (idRefMatch) {
6027
+ const idObjRe = new RegExp(`(?:^|[\\r\\n\\s])${idRefMatch[1]}\\s+${idRefMatch[2]}\\s+obj\\b([\\s\\S]{0,512}?)endobj`);
6028
+ const idObjM = idObjRe.exec(rawText);
6029
+ if (idObjM) {
6030
+ fileId = parseFirstPdfArrayStringBytes(`/ID ${idObjM[1]}`, "ID");
6031
+ }
6032
+ }
6033
+ }
6034
+ return {
6035
+ filter,
6036
+ version,
6037
+ revision,
6038
+ keyLength,
6039
+ pSigned,
6040
+ oBytes,
6041
+ uBytes,
6042
+ fileId: fileId ?? new Uint8Array(0)
6043
+ };
6044
+ }
6045
+ function extractEncryptMetadataFromDoc(doc) {
6046
+ const encEntry = doc.context.trailerInfo.Encrypt;
6047
+ if (!encEntry) return null;
6048
+ const encDict = encEntry instanceof PDFDict ? encEntry : doc.context.lookupMaybe(encEntry, PDFDict);
6049
+ if (!encDict) return null;
6050
+ const filterObj = encDict.get(PDFName.of("Filter"));
6051
+ const filter = filterObj instanceof PDFName ? filterObj.decodeText() : "Standard";
6052
+ const vObj = encDict.get(PDFName.of("V"));
6053
+ const version = vObj instanceof PDFNumber ? vObj.asNumber() : 1;
6054
+ const rObj = encDict.get(PDFName.of("R"));
6055
+ const revision = rObj instanceof PDFNumber ? rObj.asNumber() : version >= 2 ? 3 : 2;
6056
+ const lenObj = encDict.get(PDFName.of("Length"));
6057
+ const keyLength = lenObj instanceof PDFNumber ? lenObj.asNumber() : version >= 2 ? 128 : 40;
6058
+ const pObj = encDict.get(PDFName.of("P"));
6059
+ const pSigned = pObj instanceof PDFNumber ? pObj.asNumber() | 0 : -4;
6060
+ const oObj = encDict.get(PDFName.of("O"));
6061
+ const oBytes = oObj instanceof PDFHexString || oObj instanceof PDFString ? extractPdfStringRawBytes(oObj) : new Uint8Array(0);
6062
+ const uObj = encDict.get(PDFName.of("U"));
6063
+ const uBytes = uObj instanceof PDFHexString || uObj instanceof PDFString ? extractPdfStringRawBytes(uObj) : new Uint8Array(0);
6064
+ let fileId = new Uint8Array(0);
6065
+ const idEntry = doc.context.trailerInfo.ID;
6066
+ const idArr = idEntry instanceof PDFArray ? idEntry : doc.context.lookupMaybe(idEntry, PDFArray);
6067
+ if (idArr && idArr.size() > 0) {
6068
+ const first = idArr.get(0);
6069
+ if (first instanceof PDFHexString || first instanceof PDFString) {
6070
+ fileId = extractPdfStringRawBytes(first);
6071
+ }
6072
+ }
6073
+ return {
6074
+ filter,
6075
+ version,
6076
+ revision,
6077
+ keyLength,
6078
+ pSigned,
6079
+ oBytes,
6080
+ uBytes,
6081
+ fileId
6082
+ };
6083
+ }
6084
+ function inspectPdfEncryption(pdfBytes) {
6085
+ const meta = parseRawEncryptFromPdfBytes(pdfBytes);
6086
+ if (!meta) {
6087
+ return {
6088
+ encrypted: false,
6089
+ requiresOpenPassword: false,
6090
+ permissions: { ...DEFAULT_ALL_PERMISSIONS }
6091
+ };
6092
+ }
6093
+ let requiresOpenPassword = true;
6094
+ if (meta.filter === "Standard" && (meta.version === 1 || meta.version === 2) && (meta.revision === 2 || meta.revision === 3) && meta.oBytes.byteLength >= 32 && meta.uBytes.byteLength >= 16) {
6095
+ const emptyKey = authenticatePaddedUserPassword(
6096
+ padPdfPassword(""),
6097
+ meta.oBytes,
6098
+ meta.uBytes,
6099
+ meta.pSigned,
6100
+ meta.fileId,
6101
+ meta.revision,
6102
+ meta.keyLength
6103
+ );
6104
+ requiresOpenPassword = emptyKey === null;
6105
+ }
6106
+ return {
6107
+ encrypted: true,
6108
+ requiresOpenPassword,
6109
+ filter: meta.filter,
6110
+ version: meta.version,
6111
+ revision: meta.revision,
6112
+ keyLength: meta.keyLength,
6113
+ permissionFlagsRaw: meta.pSigned,
6114
+ permissions: decodePdfPermissionFlags(meta.pSigned, meta.revision)
6115
+ };
6116
+ }
6117
+ async function decryptPdfBytes(pdfBytes, password) {
6118
+ let meta = parseRawEncryptFromPdfBytes(pdfBytes);
6119
+ const doc = await PDFDocument.load(pdfBytes, {
6120
+ ignoreEncryption: true,
6121
+ updateMetadata: false
6122
+ });
6123
+ if (!meta && doc.isEncrypted) {
6124
+ meta = extractEncryptMetadataFromDoc(doc);
6125
+ }
6126
+ if (!meta) {
6127
+ return pdfBytes.slice();
6128
+ }
6129
+ if (meta.filter !== "Standard" || meta.version !== 1 && meta.version !== 2 || meta.revision !== 2 && meta.revision !== 3) {
6130
+ throw new PdfSecurityError(
6131
+ "PDF_UNSUPPORTED_ENCRYPTION",
6132
+ `Unsupported PDF encryption handler (Filter=/${meta.filter}, V=${meta.version}, R=${meta.revision}).`
6133
+ );
6134
+ }
6135
+ const rev = meta.revision;
6136
+ const emptyOpenKey = authenticatePaddedUserPassword(
6137
+ padPdfPassword(""),
6138
+ meta.oBytes,
6139
+ meta.uBytes,
6140
+ meta.pSigned,
6141
+ meta.fileId,
6142
+ rev,
6143
+ meta.keyLength
6144
+ );
6145
+ const requiresOpenPassword = emptyOpenKey === null;
6146
+ const candidatePw = password ?? "";
6147
+ if (requiresOpenPassword && candidatePw.length === 0) {
6148
+ throw new PdfSecurityError(
6149
+ "PDF_PASSWORD_REQUIRED",
6150
+ "Encrypted PDF document requires an open password."
6151
+ );
6152
+ }
6153
+ let encryptionKey = null;
6154
+ if (candidatePw.length === 0 && emptyOpenKey) {
6155
+ encryptionKey = emptyOpenKey;
6156
+ } else {
6157
+ encryptionKey = authenticatePaddedUserPassword(
6158
+ padPdfPassword(candidatePw),
6159
+ meta.oBytes,
6160
+ meta.uBytes,
6161
+ meta.pSigned,
6162
+ meta.fileId,
6163
+ rev,
6164
+ meta.keyLength
6165
+ );
6166
+ if (!encryptionKey) {
6167
+ encryptionKey = authenticateOwnerPassword(
6168
+ candidatePw,
6169
+ meta.oBytes,
6170
+ meta.uBytes,
6171
+ meta.pSigned,
6172
+ meta.fileId,
6173
+ rev,
6174
+ meta.keyLength
6175
+ );
6176
+ }
6177
+ }
6178
+ if (!encryptionKey) {
6179
+ throw new PdfSecurityError(
6180
+ "PDF_INVALID_PASSWORD",
6181
+ "Incorrect password for encrypted PDF document."
6182
+ );
6183
+ }
6184
+ const encryptRef = doc.context.trailerInfo.Encrypt instanceof PDFRef ? doc.context.trailerInfo.Encrypt : null;
6185
+ const idRef = doc.context.trailerInfo.ID instanceof PDFRef ? doc.context.trailerInfo.ID : null;
6186
+ for (const [ref, obj] of doc.context.enumerateIndirectObjects()) {
6187
+ if (encryptRef && ref.objectNumber === encryptRef.objectNumber && ref.generationNumber === encryptRef.generationNumber) {
6188
+ continue;
6189
+ }
6190
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
6191
+ continue;
6192
+ }
6193
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
6194
+ if (obj instanceof PDFRawStream) {
6195
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6196
+ const decryptedStream = rc4Bytes(objKey, obj.contents);
6197
+ obj.dict.set(PDFName.of("Length"), PDFNumber.of(decryptedStream.byteLength));
6198
+ doc.context.assign(ref, PDFRawStream.of(obj.dict, decryptedStream));
6199
+ } else if (obj instanceof PDFStream) {
6200
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6201
+ const decryptedStream = rc4Bytes(objKey, obj.getContents());
6202
+ obj.dict.set(PDFName.of("Length"), PDFNumber.of(decryptedStream.byteLength));
6203
+ doc.context.assign(ref, PDFRawStream.of(obj.dict, decryptedStream));
6204
+ } else {
6205
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
6206
+ if (next !== obj) {
6207
+ doc.context.assign(ref, next);
6208
+ }
6209
+ }
6210
+ }
6211
+ delete doc.context.trailerInfo.Encrypt;
6212
+ if (encryptRef) {
6213
+ doc.context.delete(encryptRef);
6214
+ }
6215
+ return await doc.save({ useObjectStreams: false, updateFieldAppearances: false });
6216
+ }
6217
+ async function verifyAndDecryptPdfBytes(pdfBytes, password) {
6218
+ const inspection = inspectPdfEncryption(pdfBytes);
6219
+ if (!inspection.encrypted) {
6220
+ return pdfBytes;
6221
+ }
6222
+ return decryptPdfBytes(pdfBytes, password);
6223
+ }
6224
+
6225
+ // src/exporter/pdf-native-text.ts
4893
6226
  var WIN_ANSI_EXTENDED = {
4894
6227
  128: 8364,
4895
6228
  130: 8218,
@@ -4930,9 +6263,9 @@ function multiplyPdfMatrix(m1, m2) {
4930
6263
  ];
4931
6264
  }
4932
6265
  function decodeSingleStreamObject(doc, objOrRef) {
4933
- const resolved = objOrRef instanceof PDFRef ? doc.context.lookup(objOrRef) : objOrRef;
6266
+ const resolved = objOrRef instanceof PDFRef2 ? doc.context.lookup(objOrRef) : objOrRef;
4934
6267
  if (!resolved) return new Uint8Array(0);
4935
- if (resolved instanceof PDFRawStream) {
6268
+ if (resolved instanceof PDFRawStream2) {
4936
6269
  try {
4937
6270
  const decoded = decodePDFRawStream(resolved).decode();
4938
6271
  return decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded);
@@ -4940,7 +6273,7 @@ function decodeSingleStreamObject(doc, objOrRef) {
4940
6273
  return resolved.contents;
4941
6274
  }
4942
6275
  }
4943
- if (resolved instanceof PDFStream) {
6276
+ if (resolved instanceof PDFStream2) {
4944
6277
  const anyStream = resolved;
4945
6278
  if (typeof anyStream.getUnencodedContents === "function") {
4946
6279
  return anyStream.getUnencodedContents();
@@ -4952,9 +6285,9 @@ function decodeSingleStreamObject(doc, objOrRef) {
4952
6285
  return new Uint8Array(0);
4953
6286
  }
4954
6287
  function decodeContentsEntry(doc, contentsEntry) {
4955
- const resolved = contentsEntry instanceof PDFRef ? doc.context.lookup(contentsEntry) : contentsEntry;
6288
+ const resolved = contentsEntry instanceof PDFRef2 ? doc.context.lookup(contentsEntry) : contentsEntry;
4956
6289
  if (!resolved) return new Uint8Array(0);
4957
- if (resolved instanceof PDFArray) {
6290
+ if (resolved instanceof PDFArray2) {
4958
6291
  const parts = [];
4959
6292
  let total = 0;
4960
6293
  for (let i = 0; i < resolved.size(); i++) {
@@ -5049,21 +6382,21 @@ function parseToUnicodeCMap(cmapText) {
5049
6382
  function extractResourcesFontMap(doc, resourcesDict) {
5050
6383
  const fonts = /* @__PURE__ */ new Map();
5051
6384
  if (!resourcesDict) return fonts;
5052
- const fontObj = resourcesDict.get(PDFName.of("Font"));
5053
- const fontDict = doc.context.lookupMaybe(fontObj, PDFDict);
6385
+ const fontObj = resourcesDict.get(PDFName2.of("Font"));
6386
+ const fontDict = doc.context.lookupMaybe(fontObj, PDFDict2);
5054
6387
  if (!fontDict) return fonts;
5055
6388
  for (const [keyObj, valObj] of fontDict.entries()) {
5056
6389
  const cleanKey = keyObj.decodeText ? keyObj.decodeText() : keyObj.asString().replace(/^\//, "");
5057
- const fDict = doc.context.lookupMaybe(valObj, PDFDict);
6390
+ const fDict = doc.context.lookupMaybe(valObj, PDFDict2);
5058
6391
  if (!fDict) continue;
5059
- const subtypeObj = fDict.get(PDFName.of("Subtype"));
5060
- const subtype = subtypeObj instanceof PDFName ? subtypeObj.decodeText() : "";
5061
- const encObj = fDict.get(PDFName.of("Encoding"));
5062
- const encoding = encObj instanceof PDFName ? encObj.decodeText() : "";
6392
+ const subtypeObj = fDict.get(PDFName2.of("Subtype"));
6393
+ const subtype = subtypeObj instanceof PDFName2 ? subtypeObj.decodeText() : "";
6394
+ const encObj = fDict.get(PDFName2.of("Encoding"));
6395
+ const encoding = encObj instanceof PDFName2 ? encObj.decodeText() : "";
5063
6396
  const isUtf16Cid = /UTF16|UCS2/i.test(encoding);
5064
6397
  let toUnicode = /* @__PURE__ */ new Map();
5065
6398
  let bytesPerCode = subtype === "Type0" ? 2 : 1;
5066
- const toUniEntry = fDict.get(PDFName.of("ToUnicode"));
6399
+ const toUniEntry = fDict.get(PDFName2.of("ToUnicode"));
5067
6400
  if (toUniEntry) {
5068
6401
  const cmapBytes = decodeSingleStreamObject(doc, toUniEntry);
5069
6402
  if (cmapBytes.byteLength > 0) {
@@ -5520,22 +6853,22 @@ function parsePdfContentStreamTextOps(doc, streamBytes, resourcesDict, mediaBox,
5520
6853
  case "Do": {
5521
6854
  const nameTok = operands[operands.length - 1];
5522
6855
  if (nameTok?.type === "name" && resourcesDict) {
5523
- const xObjEntry = resourcesDict.get(PDFName.of("XObject"));
5524
- const xObjDict = doc.context.lookupMaybe(xObjEntry, PDFDict);
5525
- const targetObj = xObjDict?.get(PDFName.of(nameTok.value));
5526
- const resolvedXObj = targetObj instanceof PDFRef ? doc.context.lookup(targetObj) : targetObj;
5527
- if (resolvedXObj instanceof PDFRawStream) {
5528
- const subType = resolvedXObj.dict.get(PDFName.of("Subtype"));
5529
- if (subType instanceof PDFName && subType.decodeText() === "Form") {
6856
+ const xObjEntry = resourcesDict.get(PDFName2.of("XObject"));
6857
+ const xObjDict = doc.context.lookupMaybe(xObjEntry, PDFDict2);
6858
+ const targetObj = xObjDict?.get(PDFName2.of(nameTok.value));
6859
+ const resolvedXObj = targetObj instanceof PDFRef2 ? doc.context.lookup(targetObj) : targetObj;
6860
+ if (resolvedXObj instanceof PDFRawStream2) {
6861
+ const subType = resolvedXObj.dict.get(PDFName2.of("Subtype"));
6862
+ if (subType instanceof PDFName2 && subType.decodeText() === "Form") {
5530
6863
  const formBytes = decodeSingleStreamObject(doc, resolvedXObj);
5531
- const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName.of("Resources")), PDFDict) ?? resourcesDict;
6864
+ const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName2.of("Resources")), PDFDict2) ?? resourcesDict;
5532
6865
  let formMat = [...state.ctm];
5533
- const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName.of("Matrix")), PDFArray);
6866
+ const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName2.of("Matrix")), PDFArray2);
5534
6867
  if (matArr && matArr.size() >= 6) {
5535
6868
  const nums = [];
5536
6869
  for (let k = 0; k < 6; k++) {
5537
6870
  const nObj = matArr.get(k);
5538
- nums.push(nObj instanceof PDFNumber ? nObj.asNumber() : 0);
6871
+ nums.push(nObj instanceof PDFNumber2 ? nObj.asNumber() : 0);
5539
6872
  }
5540
6873
  formMat = multiplyPdfMatrix(
5541
6874
  [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]],
@@ -5628,7 +6961,7 @@ async function tryExtractViaPdfjsFallback(pdfBytes, pageIds) {
5628
6961
  }
5629
6962
  }
5630
6963
  async function extractNativeTextSpansFromPdfBytes(pdfBytes, pageIds) {
5631
- const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
6964
+ const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5632
6965
  const pages = doc.getPages();
5633
6966
  const effectivePageIds = pages.map((_, idx) => pageIds?.[idx] || `page-${idx + 1}`);
5634
6967
  const spansByPage = {};
@@ -5696,16 +7029,16 @@ function stripPdfPageNativeTextInRects(doc, page, stripRects) {
5696
7029
  }
5697
7030
  const newStream = doc.context.flateStream(sanitized);
5698
7031
  const newRef = doc.context.register(newStream);
5699
- page.node.set(PDFName.of("Contents"), newRef);
7032
+ page.node.set(PDFName2.of("Contents"), newRef);
5700
7033
  return matchingOps.length;
5701
7034
  }
5702
7035
  async function mergePdfBytes(pdfList) {
5703
7036
  if (!Array.isArray(pdfList) || pdfList.length === 0) {
5704
7037
  throw new Error("[UniverPdfs] mergePdfBytes requires at least one PDF Uint8Array.");
5705
7038
  }
5706
- const mergedDoc = await PDFDocument.create();
7039
+ const mergedDoc = await PDFDocument2.create();
5707
7040
  for (const rawBytes of pdfList) {
5708
- const srcDoc = await PDFDocument.load(rawBytes, { ignoreEncryption: true });
7041
+ const srcDoc = await PDFDocument2.load(rawBytes, { ignoreEncryption: true });
5709
7042
  const indices = srcDoc.getPageIndices();
5710
7043
  if (indices.length > 0) {
5711
7044
  const copiedPages = await mergedDoc.copyPages(srcDoc, indices);
@@ -5720,7 +7053,7 @@ async function splitPdfBytes(pdfBytes, ranges) {
5720
7053
  if (!Array.isArray(ranges) || ranges.length === 0) {
5721
7054
  return [];
5722
7055
  }
5723
- const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
7056
+ const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5724
7057
  const totalPages = srcDoc.getPageCount();
5725
7058
  const outputs = [];
5726
7059
  for (const range of ranges) {
@@ -5736,7 +7069,7 @@ async function splitPdfBytes(pdfBytes, ranges) {
5736
7069
  for (let p = start; p <= clampedEnd; p++) {
5737
7070
  indices.push(p - 1);
5738
7071
  }
5739
- const subDoc = await PDFDocument.create();
7072
+ const subDoc = await PDFDocument2.create();
5740
7073
  const copiedPages = await subDoc.copyPages(srcDoc, indices);
5741
7074
  for (const page of copiedPages) {
5742
7075
  subDoc.addPage(page);
@@ -5803,7 +7136,7 @@ function resolveOneBasedPages(pages, totalPages) {
5803
7136
  return out;
5804
7137
  }
5805
7138
  async function removePdfPagesBytes(pdfBytes, pagesToRemove) {
5806
- const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
7139
+ const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5807
7140
  const totalPages = srcDoc.getPageCount();
5808
7141
  const removeSet = new Set(resolveOneBasedPages(pagesToRemove, totalPages));
5809
7142
  const keepIndices = [];
@@ -5815,7 +7148,7 @@ async function removePdfPagesBytes(pdfBytes, pagesToRemove) {
5815
7148
  if (keepIndices.length === 0) {
5816
7149
  throw new Error("[UniverPdfs] Cannot remove all pages from a PDF document.");
5817
7150
  }
5818
- const outDoc = await PDFDocument.create();
7151
+ const outDoc = await PDFDocument2.create();
5819
7152
  const copied = await outDoc.copyPages(srcDoc, keepIndices);
5820
7153
  for (const page of copied) {
5821
7154
  outDoc.addPage(page);
@@ -5823,13 +7156,13 @@ async function removePdfPagesBytes(pdfBytes, pagesToRemove) {
5823
7156
  return await outDoc.save();
5824
7157
  }
5825
7158
  async function insertPdfPagesBytes(basePdfBytes, insertPdfBytes, atPageIndex, sourcePages) {
5826
- const baseDoc = await PDFDocument.load(basePdfBytes, { ignoreEncryption: true });
5827
- const insertDoc = await PDFDocument.load(insertPdfBytes, { ignoreEncryption: true });
7159
+ const baseDoc = await PDFDocument2.load(basePdfBytes, { ignoreEncryption: true });
7160
+ const insertDoc = await PDFDocument2.load(insertPdfBytes, { ignoreEncryption: true });
5828
7161
  const baseCount = baseDoc.getPageCount();
5829
7162
  const insertTotal = insertDoc.getPageCount();
5830
7163
  const targetIdx = atPageIndex === void 0 ? baseCount : Math.max(0, Math.min(baseCount, Math.floor(atPageIndex)));
5831
7164
  const srcOneBased = sourcePages ? resolveOneBasedPages(sourcePages, insertTotal) : Array.from({ length: insertTotal }, (_, i) => i + 1);
5832
- const outDoc = await PDFDocument.create();
7165
+ const outDoc = await PDFDocument2.create();
5833
7166
  const beforeIndices = Array.from({ length: targetIdx }, (_, i) => i);
5834
7167
  const afterIndices = Array.from({ length: baseCount - targetIdx }, (_, i) => targetIdx + i);
5835
7168
  if (beforeIndices.length > 0) {
@@ -5850,7 +7183,7 @@ async function insertPdfPagesBytes(basePdfBytes, insertPdfBytes, atPageIndex, so
5850
7183
  return await outDoc.save();
5851
7184
  }
5852
7185
  async function rotatePdfPagesBytes(pdfBytes, angleDeg, pages, options) {
5853
- const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
7186
+ const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5854
7187
  const totalPages = doc.getPageCount();
5855
7188
  const targets = pages ? resolveOneBasedPages(pages, totalPages) : Array.from({ length: totalPages }, (_, i) => i + 1);
5856
7189
  const isRelative = options?.relative !== false;
@@ -5863,7 +7196,7 @@ async function rotatePdfPagesBytes(pdfBytes, angleDeg, pages, options) {
5863
7196
  return await doc.save();
5864
7197
  }
5865
7198
  async function movePdfPageBytes(pdfBytes, fromPage, toPage) {
5866
- const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
7199
+ const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5867
7200
  const totalPages = srcDoc.getPageCount();
5868
7201
  const fromIdx = Math.floor(fromPage) - 1;
5869
7202
  const toIdx = Math.floor(toPage) - 1;
@@ -5878,7 +7211,7 @@ async function movePdfPageBytes(pdfBytes, fromPage, toPage) {
5878
7211
  const order = Array.from({ length: totalPages }, (_, i) => i);
5879
7212
  const [moved] = order.splice(fromIdx, 1);
5880
7213
  order.splice(toIdx, 0, moved);
5881
- const outDoc = await PDFDocument.create();
7214
+ const outDoc = await PDFDocument2.create();
5882
7215
  for (const pg of await outDoc.copyPages(srcDoc, order)) {
5883
7216
  outDoc.addPage(pg);
5884
7217
  }
@@ -5895,7 +7228,7 @@ async function organizePdfBytes(pdfBytes, planOrOptions) {
5895
7228
  } else if (act.type === "move") {
5896
7229
  working = await movePdfPageBytes(working, act.fromPage, act.toPage);
5897
7230
  } else if (act.type === "duplicate") {
5898
- const doc = await PDFDocument.load(working, { ignoreEncryption: true });
7231
+ const doc = await PDFDocument2.load(working, { ignoreEncryption: true });
5899
7232
  const total = doc.getPageCount();
5900
7233
  const p = Math.floor(act.pageNumber);
5901
7234
  if (p < 1 || p > total) {
@@ -5919,9 +7252,9 @@ async function organizePdfBytes(pdfBytes, planOrOptions) {
5919
7252
  if (pageSpecs.length === 0) {
5920
7253
  throw new Error("[UniverPdfs] organizePdfBytes requires at least one output page specification.");
5921
7254
  }
5922
- const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
7255
+ const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
5923
7256
  const totalPages = srcDoc.getPageCount();
5924
- const outDoc = await PDFDocument.create();
7257
+ const outDoc = await PDFDocument2.create();
5925
7258
  for (const spec of pageSpecs) {
5926
7259
  const pNum = typeof spec === "number" ? Math.floor(spec) : Math.floor(spec.pageNumber);
5927
7260
  if (pNum < 1 || pNum > totalPages) {
@@ -5942,6 +7275,299 @@ async function organizePdfBytes(pdfBytes, planOrOptions) {
5942
7275
  }
5943
7276
  return await outDoc.save();
5944
7277
  }
7278
+ function formatPdfPageIndicesLabel(pageIndices) {
7279
+ if (pageIndices.length === 0) return "";
7280
+ const runs = [];
7281
+ let runStart = pageIndices[0] + 1;
7282
+ let runPrev = runStart;
7283
+ for (let i = 1; i < pageIndices.length; i++) {
7284
+ const p = pageIndices[i] + 1;
7285
+ if (p === runPrev + 1) {
7286
+ runPrev = p;
7287
+ } else {
7288
+ runs.push(runStart === runPrev ? `${runStart}` : `${runStart}-${runPrev}`);
7289
+ runStart = p;
7290
+ runPrev = p;
7291
+ }
7292
+ }
7293
+ runs.push(runStart === runPrev ? `${runStart}` : `${runStart}-${runPrev}`);
7294
+ return runs.join(",");
7295
+ }
7296
+ function chunkEveryNIndices(indices, everyNPages) {
7297
+ const step = Math.floor(everyNPages);
7298
+ if (!Number.isFinite(step) || step < 1) {
7299
+ throw new Error(`[UniverPdfs] everyNPages must be an integer >= 1, received ${everyNPages}.`);
7300
+ }
7301
+ const chunks = [];
7302
+ for (let i = 0; i < indices.length; i += step) {
7303
+ chunks.push(indices.slice(i, i + step));
7304
+ }
7305
+ return chunks;
7306
+ }
7307
+ function parsePdfPageRangeSpec(spec, totalPages, options) {
7308
+ if (totalPages <= 0) return [];
7309
+ const allZeroBased = Array.from({ length: totalPages }, (_, i) => i);
7310
+ if (options?.everyNPages !== void 0) {
7311
+ const trimmedForChunk = (spec ?? "").trim();
7312
+ if (!trimmedForChunk || /^(all|\*|every.*)$/i.test(trimmedForChunk)) {
7313
+ return chunkEveryNIndices(allZeroBased, options.everyNPages);
7314
+ }
7315
+ const baseFlat = parsePdfPageRangeSpec(trimmedForChunk, totalPages).flat();
7316
+ return chunkEveryNIndices(baseFlat, options.everyNPages);
7317
+ }
7318
+ const trimmed = (spec ?? "").trim();
7319
+ if (!trimmed || trimmed.toLowerCase() === "all" || trimmed === "*") {
7320
+ return [allZeroBased];
7321
+ }
7322
+ const everyMatch = /^every[\s:_-]*(\d+)(?:\s*pages?)?$/i.exec(trimmed) ?? /^(\d+)\s*n$/i.exec(trimmed);
7323
+ if (everyMatch) {
7324
+ const step = parseInt(everyMatch[1], 10);
7325
+ return chunkEveryNIndices(allZeroBased, step);
7326
+ }
7327
+ if (/^(single|each)$/i.test(trimmed)) {
7328
+ return chunkEveryNIndices(allZeroBased, 1);
7329
+ }
7330
+ const parseSingleClause = (clause) => {
7331
+ const lower = clause.toLowerCase();
7332
+ if (lower === "all" || lower === "*") {
7333
+ return [...allZeroBased];
7334
+ }
7335
+ if (lower === "odd") {
7336
+ const odds = [];
7337
+ for (let p = 1; p <= totalPages; p += 2) odds.push(p - 1);
7338
+ return odds;
7339
+ }
7340
+ if (lower === "even") {
7341
+ const evens = [];
7342
+ for (let p = 2; p <= totalPages; p += 2) evens.push(p - 1);
7343
+ return evens;
7344
+ }
7345
+ const group = [];
7346
+ const seen = /* @__PURE__ */ new Set();
7347
+ const pushZeroBased = (oneBased) => {
7348
+ if (oneBased < 1 || oneBased > totalPages) {
7349
+ throw new Error(
7350
+ `[UniverPdfs] Page number ${oneBased} is out of bounds (1..${totalPages}).`
7351
+ );
7352
+ }
7353
+ const zeroIdx = oneBased - 1;
7354
+ if (!seen.has(zeroIdx)) {
7355
+ seen.add(zeroIdx);
7356
+ group.push(zeroIdx);
7357
+ }
7358
+ };
7359
+ const subTokens = clause.split("+").map((s) => s.trim()).filter(Boolean);
7360
+ for (const sub of subTokens) {
7361
+ const rangeMatch = /^(\d+)\s*-\s*(\d*)$/.exec(sub);
7362
+ if (rangeMatch) {
7363
+ const start = parseInt(rangeMatch[1], 10);
7364
+ const end = rangeMatch[2] ? parseInt(rangeMatch[2], 10) : totalPages;
7365
+ if (start < 1 || end < start || end > totalPages) {
7366
+ throw new Error(
7367
+ `[UniverPdfs] Invalid page range "${sub}" for ${totalPages}-page document.`
7368
+ );
7369
+ }
7370
+ for (let p = start; p <= end; p++) {
7371
+ pushZeroBased(p);
7372
+ }
7373
+ continue;
7374
+ }
7375
+ if (/^\d+$/.test(sub)) {
7376
+ pushZeroBased(parseInt(sub, 10));
7377
+ continue;
7378
+ }
7379
+ throw new Error(`[UniverPdfs] Invalid page range token "${sub}".`);
7380
+ }
7381
+ return group;
7382
+ };
7383
+ const clauses = trimmed.split(/[,;]/).map((s) => s.trim()).filter(Boolean);
7384
+ const groups = [];
7385
+ for (const clause of clauses) {
7386
+ const parsed = parseSingleClause(clause);
7387
+ if (parsed.length > 0) {
7388
+ groups.push(parsed);
7389
+ }
7390
+ }
7391
+ return groups;
7392
+ }
7393
+ function resolveMultiSpecGroups(specs, totalPages, everyNPages) {
7394
+ if (totalPages <= 0) return [];
7395
+ if (everyNPages !== void 0 && (!specs || specs.length === 0)) {
7396
+ return parsePdfPageRangeSpec("", totalPages, { everyNPages }).map((pageIndices) => ({
7397
+ label: formatPdfPageIndicesLabel(pageIndices),
7398
+ pageIndices
7399
+ }));
7400
+ }
7401
+ if (!Array.isArray(specs) || specs.length === 0) {
7402
+ return [];
7403
+ }
7404
+ if (specs.length === 1) {
7405
+ const groups = parsePdfPageRangeSpec(
7406
+ specs[0],
7407
+ totalPages,
7408
+ everyNPages !== void 0 ? { everyNPages } : void 0
7409
+ );
7410
+ return groups.map((pageIndices) => ({
7411
+ label: formatPdfPageIndicesLabel(pageIndices),
7412
+ pageIndices
7413
+ }));
7414
+ }
7415
+ const resolved = [];
7416
+ for (const rawSpec of specs) {
7417
+ const trimmed = (rawSpec ?? "").trim();
7418
+ if (!trimmed) continue;
7419
+ const isChunkExpr = /^every[\s:_-]*\d+/i.test(trimmed) || /^\d+\s*n$/i.test(trimmed) || /^(single|each)$/i.test(trimmed);
7420
+ const subGroups = parsePdfPageRangeSpec(trimmed, totalPages);
7421
+ if (isChunkExpr) {
7422
+ for (const grp of subGroups) {
7423
+ resolved.push({ label: formatPdfPageIndicesLabel(grp), pageIndices: grp });
7424
+ }
7425
+ } else if (subGroups.length === 1) {
7426
+ resolved.push({
7427
+ label: formatPdfPageIndicesLabel(subGroups[0]),
7428
+ pageIndices: subGroups[0]
7429
+ });
7430
+ } else if (subGroups.length > 1) {
7431
+ const merged = [];
7432
+ const seen = /* @__PURE__ */ new Set();
7433
+ for (const g of subGroups) {
7434
+ for (const idx of g) {
7435
+ if (!seen.has(idx)) {
7436
+ seen.add(idx);
7437
+ merged.push(idx);
7438
+ }
7439
+ }
7440
+ }
7441
+ if (merged.length > 0) {
7442
+ resolved.push({
7443
+ label: formatPdfPageIndicesLabel(merged),
7444
+ pageIndices: merged
7445
+ });
7446
+ }
7447
+ }
7448
+ }
7449
+ return resolved;
7450
+ }
7451
+ function remapBookmarksForSplit(bookmarks, oldIdxToNewIdx) {
7452
+ if (!bookmarks?.length) return [];
7453
+ const out = [];
7454
+ for (const bm of bookmarks) {
7455
+ const remappedChildren = remapBookmarksForSplit(bm.children, oldIdxToNewIdx);
7456
+ const mappedIdx = oldIdxToNewIdx.get(bm.pageIndex);
7457
+ if (mappedIdx !== void 0) {
7458
+ out.push({
7459
+ ...Tools2.deepClone(bm),
7460
+ pageIndex: mappedIdx,
7461
+ ...remappedChildren.length > 0 ? { children: remappedChildren } : { children: void 0 }
7462
+ });
7463
+ } else if (remappedChildren.length > 0) {
7464
+ out.push(...remappedChildren);
7465
+ }
7466
+ }
7467
+ return out;
7468
+ }
7469
+ function splitPdfUnitByRanges(unitData, specs, options) {
7470
+ const srcPageOrder = unitData.document.pageOrder ?? [];
7471
+ const totalPages = srcPageOrder.length;
7472
+ const groups = resolveMultiSpecGroups(specs, totalPages, options?.everyNPages);
7473
+ const srcNativeSpans = unitData.metadata?.nativeTextSpansByPage ?? unitData.editState.nativeTextSpansByPage ?? {};
7474
+ const srcBookmarks = unitData.bookmarks ?? unitData.metadata?.bookmarks;
7475
+ return groups.map(({ label, pageIndices }, partIdx) => {
7476
+ const pages = {};
7477
+ const pageOrder = [];
7478
+ const elementsByPage = {};
7479
+ const elementOrderByPage = {};
7480
+ const nativeTextSpansByPage = {};
7481
+ const oldIdxToNewIdx = /* @__PURE__ */ new Map();
7482
+ const usedPageIds = /* @__PURE__ */ new Set();
7483
+ pageIndices.forEach((origIdx, newIdx) => {
7484
+ if (!oldIdxToNewIdx.has(origIdx)) {
7485
+ oldIdxToNewIdx.set(origIdx, newIdx);
7486
+ }
7487
+ const origPageId = srcPageOrder[origIdx];
7488
+ const origPage = unitData.document.pages[origPageId];
7489
+ const targetPageId = usedPageIds.has(origPageId) ? `${origPageId}-copy-${generateRandomId3(4)}` : origPageId;
7490
+ usedPageIds.add(targetPageId);
7491
+ pageOrder.push(targetPageId);
7492
+ pages[targetPageId] = {
7493
+ ...origPage ? Tools2.deepClone(origPage) : { id: targetPageId },
7494
+ id: targetPageId,
7495
+ sourcePageNumber: origPage?.sourcePageNumber ?? origIdx + 1
7496
+ };
7497
+ const origEls = unitData.editState.elementsByPage[origPageId] ?? {};
7498
+ const origOrder = unitData.editState.elementOrderByPage[origPageId] ?? Object.keys(origEls);
7499
+ elementsByPage[targetPageId] = Tools2.deepClone(origEls);
7500
+ elementOrderByPage[targetPageId] = [...origOrder];
7501
+ const origSpans = srcNativeSpans[origPageId] ?? [];
7502
+ if (origSpans.length > 0) {
7503
+ nativeTextSpansByPage[targetPageId] = origSpans.map((sp) => ({
7504
+ ...Tools2.deepClone(sp),
7505
+ pageId: targetPageId,
7506
+ pageIndex: newIdx
7507
+ }));
7508
+ }
7509
+ });
7510
+ const firstPage = pageOrder[0] ? pages[pageOrder[0]] : void 0;
7511
+ const remappedBookmarks = remapBookmarksForSplit(srcBookmarks, oldIdxToNewIdx);
7512
+ const nextMetadata = Tools2.deepClone(unitData.metadata ?? {});
7513
+ if (Object.keys(nativeTextSpansByPage).length > 0) {
7514
+ nextMetadata.nativeTextSpansByPage = Tools2.deepClone(nativeTextSpansByPage);
7515
+ } else {
7516
+ delete nextMetadata.nativeTextSpansByPage;
7517
+ }
7518
+ if (remappedBookmarks.length > 0) {
7519
+ nextMetadata.bookmarks = Tools2.deepClone(remappedBookmarks);
7520
+ } else {
7521
+ delete nextMetadata.bookmarks;
7522
+ }
7523
+ const splitUnit = {
7524
+ ...Tools2.deepClone(unitData),
7525
+ id: `${unitData.id || "pdf"}-split-${partIdx + 1}-${generateRandomId3(4)}`,
7526
+ rev: 1,
7527
+ name: `${unitData.name || "Document"} (P${label})`,
7528
+ document: {
7529
+ ...Tools2.deepClone(unitData.document),
7530
+ pageSize: Tools2.deepClone(firstPage?.pageSize ?? unitData.document.pageSize),
7531
+ pages,
7532
+ pageOrder
7533
+ },
7534
+ editState: {
7535
+ elementsByPage,
7536
+ elementOrderByPage,
7537
+ ...unitData.editState.suppressedSourceIds ? { suppressedSourceIds: [...unitData.editState.suppressedSourceIds] } : {},
7538
+ ...Object.keys(nativeTextSpansByPage).length > 0 ? { nativeTextSpansByPage: Tools2.deepClone(nativeTextSpansByPage) } : {}
7539
+ },
7540
+ ...remappedBookmarks.length > 0 ? { bookmarks: remappedBookmarks } : { bookmarks: void 0 },
7541
+ metadata: nextMetadata
7542
+ };
7543
+ return {
7544
+ label,
7545
+ pageIndices: [...pageIndices],
7546
+ unit: splitUnit
7547
+ };
7548
+ });
7549
+ }
7550
+ async function splitPdfBytesByRanges(pdfBytes, specs, options) {
7551
+ const decryptedBytes = await verifyAndDecryptPdfBytes(pdfBytes, options?.password);
7552
+ const srcDoc = await PDFDocument2.load(decryptedBytes, { ignoreEncryption: true });
7553
+ const totalPages = srcDoc.getPageCount();
7554
+ const groups = resolveMultiSpecGroups(specs, totalPages, options?.everyNPages);
7555
+ const outputs = [];
7556
+ for (const { label, pageIndices } of groups) {
7557
+ const subDoc = await PDFDocument2.create();
7558
+ const copiedPages = await subDoc.copyPages(srcDoc, pageIndices);
7559
+ for (const page of copiedPages) {
7560
+ subDoc.addPage(page);
7561
+ }
7562
+ const bytes = await subDoc.save();
7563
+ outputs.push({
7564
+ label,
7565
+ pageCount: pageIndices.length,
7566
+ bytes
7567
+ });
7568
+ }
7569
+ return outputs;
7570
+ }
5945
7571
 
5946
7572
  // src/exporter/pdf-svg-vector.ts
5947
7573
  import {
@@ -7068,8 +8694,8 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
7068
8694
  Subtype: "CIDFontType2",
7069
8695
  BaseFont: fontTag,
7070
8696
  CIDSystemInfo: {
7071
- Registry: PDFString.of("Adobe"),
7072
- Ordering: PDFString.of("Identity"),
8697
+ Registry: PDFString2.of("Adobe"),
8698
+ Ordering: PDFString2.of("Identity"),
7073
8699
  Supplement: 0
7074
8700
  },
7075
8701
  FontDescriptor: fontDescriptorRef,
@@ -7465,8 +9091,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7465
9091
  Subtype: "CIDFontType2",
7466
9092
  BaseFont: "STSong-Light",
7467
9093
  CIDSystemInfo: {
7468
- Registry: PDFString.of("Adobe"),
7469
- Ordering: PDFString.of("GB1"),
9094
+ Registry: PDFString2.of("Adobe"),
9095
+ Ordering: PDFString2.of("GB1"),
7470
9096
  Supplement: 4
7471
9097
  },
7472
9098
  FontDescriptor: fontDescriptorRef,
@@ -7661,7 +9287,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7661
9287
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
7662
9288
  })() : setFillingRgbColor(color.r, color.g, color.b);
7663
9289
  const syntheticBoldOps = wantBold && !usedDedicatedBold ? [
7664
- PDFOperator.of("Tr", [PDFNumber2.of(2)]),
9290
+ PDFOperator.of("Tr", [PDFNumber3.of(2)]),
7665
9291
  setLineWidth(Math.max(0.25, fontSize * 0.032)),
7666
9292
  colorType === "cmyk" ? (() => {
7667
9293
  const cm = rgbToCmyk(color.r, color.g, color.b);
@@ -7705,12 +9331,12 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7705
9331
  const hexStr = encodeVectorCjkLineHex(line, state, activeSubset);
7706
9332
  const totalTc = charSpacing + extraJustifyTc;
7707
9333
  const posOp = style?.italic ? PDFOperator.of("Tm", [
7708
- PDFNumber2.of(1),
7709
- PDFNumber2.of(0),
7710
- PDFNumber2.of(0.2126),
7711
- PDFNumber2.of(1),
7712
- PDFNumber2.of(drawX),
7713
- PDFNumber2.of(drawY)
9334
+ PDFNumber3.of(1),
9335
+ PDFNumber3.of(0),
9336
+ PDFNumber3.of(0.2126),
9337
+ PDFNumber3.of(1),
9338
+ PDFNumber3.of(drawX),
9339
+ PDFNumber3.of(drawY)
7714
9340
  ]) : moveText(drawX, drawY);
7715
9341
  page.pushOperators(
7716
9342
  pushGraphicsState2(),
@@ -7720,7 +9346,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7720
9346
  setFontAndSize(fontKey, fontSize),
7721
9347
  ...totalTc !== 0 ? [setCharacterSpacing(totalTc)] : [],
7722
9348
  posOp,
7723
- showText(PDFHexString.of(hexStr)),
9349
+ showText(PDFHexString2.of(hexStr)),
7724
9350
  endText(),
7725
9351
  popGraphicsState2()
7726
9352
  );
@@ -8301,7 +9927,7 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
8301
9927
  const ops = [pushGraphicsState2()];
8302
9928
  if (totalTc !== 0) ops.push(setCharacterSpacing(totalTc));
8303
9929
  if (extraWordSpacing !== 0) {
8304
- ops.push(PDFOperator.of("Tw", [PDFNumber2.of(extraWordSpacing)]));
9930
+ ops.push(PDFOperator.of("Tw", [PDFNumber3.of(extraWordSpacing)]));
8305
9931
  }
8306
9932
  page.pushOperators(...ops);
8307
9933
  page.drawText(lineText, {
@@ -9143,7 +10769,7 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9143
10769
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
9144
10770
  })() : setFillingRgbColor(col.r, col.g, col.b);
9145
10771
  const boldOps = seg.bold && !usedDedicatedBold ? [
9146
- PDFOperator.of("Tr", [PDFNumber2.of(2)]),
10772
+ PDFOperator.of("Tr", [PDFNumber3.of(2)]),
9147
10773
  setLineWidth(Math.max(0.25, seg.fontSize * 0.032)),
9148
10774
  colorType === "cmyk" ? (() => {
9149
10775
  const cm = rgbToCmyk(col.r, col.g, col.b);
@@ -9151,12 +10777,12 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9151
10777
  })() : setStrokingRgbColor(col.r, col.g, col.b)
9152
10778
  ] : [];
9153
10779
  const posOp = seg.italic ? PDFOperator.of("Tm", [
9154
- PDFNumber2.of(1),
9155
- PDFNumber2.of(0),
9156
- PDFNumber2.of(0.2126),
9157
- PDFNumber2.of(1),
9158
- PDFNumber2.of(segX),
9159
- PDFNumber2.of(baselineY)
10780
+ PDFNumber3.of(1),
10781
+ PDFNumber3.of(0),
10782
+ PDFNumber3.of(0.2126),
10783
+ PDFNumber3.of(1),
10784
+ PDFNumber3.of(segX),
10785
+ PDFNumber3.of(baselineY)
9160
10786
  ]) : moveText(segX, baselineY);
9161
10787
  page.pushOperators(
9162
10788
  pushGraphicsState2(),
@@ -9165,7 +10791,7 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9165
10791
  ...boldOps,
9166
10792
  setFontAndSize(fontKey, seg.fontSize),
9167
10793
  posOp,
9168
- showText(PDFHexString.of(hexStr)),
10794
+ showText(PDFHexString2.of(hexStr)),
9169
10795
  endText(),
9170
10796
  popGraphicsState2()
9171
10797
  );
@@ -9307,10 +10933,11 @@ function attachPdfOutlinesTree(pdfDoc, bookmarks) {
9307
10933
  const selfRef = itemRefs[i];
9308
10934
  const clampedPageIdx = Math.max(0, Math.min(allPages.length - 1, Math.floor(item.pageIndex || 0)));
9309
10935
  const targetPage = allPages[clampedPageIdx];
9310
- const destY = item.topOffsetPt !== void 0 ? Math.round(Math.max(0, targetPage.getHeight() - item.topOffsetPt) * 100) / 100 : null;
9311
- const destArray = pdfDoc.context.obj([targetPage.ref, PDFName2.of("XYZ"), null, destY, null]);
10936
+ const effectiveTopOffset = item.topPt ?? item.topOffsetPt;
10937
+ const destY = effectiveTopOffset !== void 0 ? Math.round(Math.max(0, targetPage.getHeight() - effectiveTopOffset) * 100) / 100 : null;
10938
+ const destArray = pdfDoc.context.obj([targetPage.ref, PDFName3.of("XYZ"), null, destY, null]);
9312
10939
  const dictObj = {
9313
- Title: PDFHexString.fromText(item.title || "Bookmark"),
10940
+ Title: PDFHexString2.fromText(item.title || "Bookmark"),
9314
10941
  Parent: parentRef,
9315
10942
  Dest: destArray
9316
10943
  };
@@ -9343,15 +10970,15 @@ function attachPdfOutlinesTree(pdfDoc, bookmarks) {
9343
10970
  Count: rootChain.totalCount
9344
10971
  })
9345
10972
  );
9346
- pdfDoc.catalog.set(PDFName2.of("Outlines"), outlinesRef);
10973
+ pdfDoc.catalog.set(PDFName3.of("Outlines"), outlinesRef);
9347
10974
  }
9348
10975
  function ensurePagePropertiesDict(pdfDoc, pdfPage) {
9349
10976
  pdfPage.node.normalize();
9350
10977
  const res = pdfPage.node.Resources();
9351
- let props = pdfDoc.context.lookupMaybe(res.get(PDFName2.of("Properties")), PDFDict2);
10978
+ let props = pdfDoc.context.lookupMaybe(res.get(PDFName3.of("Properties")), PDFDict3);
9352
10979
  if (!props) {
9353
10980
  props = pdfDoc.context.obj({});
9354
- res.set(PDFName2.of("Properties"), props);
10981
+ res.set(PDFName3.of("Properties"), props);
9355
10982
  }
9356
10983
  return props;
9357
10984
  }
@@ -9367,11 +10994,11 @@ function attachOptionalContentLayers(pdfDoc, layers) {
9367
10994
  const isPrint = layer.printable !== false;
9368
10995
  const ocgDict = pdfDoc.context.obj({
9369
10996
  Type: "OCG",
9370
- Name: PDFHexString.fromText(layer.name || layer.id),
9371
- Intent: [PDFName2.of("View"), PDFName2.of("Design")],
10997
+ Name: PDFHexString2.fromText(layer.name || layer.id),
10998
+ Intent: [PDFName3.of("View"), PDFName3.of("Design")],
9372
10999
  Usage: {
9373
- View: { ViewState: PDFName2.of(isVis ? "ON" : "OFF") },
9374
- Print: { PrintState: PDFName2.of(isPrint ? "ON" : "OFF") }
11000
+ View: { ViewState: PDFName3.of(isVis ? "ON" : "OFF") },
11001
+ Print: { PrintState: PDFName3.of(isPrint ? "ON" : "OFF") }
9375
11002
  }
9376
11003
  });
9377
11004
  const ocgRef = pdfDoc.context.register(ocgDict);
@@ -9386,11 +11013,11 @@ function attachOptionalContentLayers(pdfDoc, layers) {
9386
11013
  });
9387
11014
  });
9388
11015
  pdfDoc.catalog.set(
9389
- PDFName2.of("OCProperties"),
11016
+ PDFName3.of("OCProperties"),
9390
11017
  pdfDoc.context.obj({
9391
11018
  OCGs: allRefs,
9392
11019
  D: {
9393
- BaseState: PDFName2.of("ON"),
11020
+ BaseState: PDFName3.of("ON"),
9394
11021
  ON: onRefs,
9395
11022
  OFF: offRefs,
9396
11023
  Order: allRefs,
@@ -9409,7 +11036,7 @@ function attachEmbeddedFileAttachments(pdfDoc, attachments) {
9409
11036
  const subtypeSafe = (att.mimeType || "application/octet-stream").replace(/\//g, "#2F");
9410
11037
  const efStream = pdfDoc.context.flateStream(fileBytes, {
9411
11038
  Type: "EmbeddedFile",
9412
- Subtype: PDFName2.of(subtypeSafe),
11039
+ Subtype: PDFName3.of(subtypeSafe),
9413
11040
  Params: {
9414
11041
  Size: fileBytes.byteLength
9415
11042
  }
@@ -9417,30 +11044,30 @@ function attachEmbeddedFileAttachments(pdfDoc, attachments) {
9417
11044
  const efRef = pdfDoc.context.register(efStream);
9418
11045
  const filespecObj = {
9419
11046
  Type: "Filespec",
9420
- F: PDFString.of((att.fileName || "attachment.bin").replace(/[^\x20-\x7E]/g, "_")),
9421
- UF: PDFHexString.fromText(att.fileName || "attachment.bin"),
11047
+ F: PDFString2.of((att.fileName || "attachment.bin").replace(/[^\x20-\x7E]/g, "_")),
11048
+ UF: PDFHexString2.fromText(att.fileName || "attachment.bin"),
9422
11049
  EF: {
9423
11050
  F: efRef,
9424
11051
  UF: efRef
9425
11052
  }
9426
11053
  };
9427
11054
  if (att.description) {
9428
- filespecObj.Desc = PDFHexString.fromText(att.description);
11055
+ filespecObj.Desc = PDFHexString2.fromText(att.description);
9429
11056
  }
9430
11057
  const filespecRef = pdfDoc.context.register(pdfDoc.context.obj(filespecObj));
9431
- namesArr.push(PDFHexString.fromText(att.fileName || "attachment.bin"), filespecRef);
11058
+ namesArr.push(PDFHexString2.fromText(att.fileName || "attachment.bin"), filespecRef);
9432
11059
  }
9433
11060
  const efTreeRef = pdfDoc.context.register(
9434
11061
  pdfDoc.context.obj({
9435
11062
  Names: namesArr
9436
11063
  })
9437
11064
  );
9438
- const existingNames = pdfDoc.context.lookupMaybe(pdfDoc.catalog.get(PDFName2.of("Names")), PDFDict2);
11065
+ const existingNames = pdfDoc.context.lookupMaybe(pdfDoc.catalog.get(PDFName3.of("Names")), PDFDict3);
9439
11066
  if (existingNames) {
9440
- existingNames.set(PDFName2.of("EmbeddedFiles"), efTreeRef);
11067
+ existingNames.set(PDFName3.of("EmbeddedFiles"), efTreeRef);
9441
11068
  } else {
9442
11069
  pdfDoc.catalog.set(
9443
- PDFName2.of("Names"),
11070
+ PDFName3.of("Names"),
9444
11071
  pdfDoc.context.obj({
9445
11072
  EmbeddedFiles: efTreeRef
9446
11073
  })
@@ -9484,7 +11111,7 @@ function attachPdfAComplianceMetadata(pdfDoc, snapshot, includePdfUa) {
9484
11111
  Length: xmpBytes.byteLength
9485
11112
  });
9486
11113
  const metadataRef = pdfDoc.context.register(metadataStream);
9487
- pdfDoc.catalog.set(PDFName2.of("Metadata"), metadataRef);
11114
+ pdfDoc.catalog.set(PDFName3.of("Metadata"), metadataRef);
9488
11115
  const srgbHeaderBytes = new TextEncoder().encode("sRGB IEC61966-2.1 ICC Output Profile");
9489
11116
  const iccStream = pdfDoc.context.flateStream(srgbHeaderBytes, {
9490
11117
  N: 3,
@@ -9495,13 +11122,13 @@ function attachPdfAComplianceMetadata(pdfDoc, snapshot, includePdfUa) {
9495
11122
  pdfDoc.context.obj({
9496
11123
  Type: "OutputIntent",
9497
11124
  S: "GTS_PDFA1",
9498
- OutputConditionIdentifier: PDFString.of("sRGB IEC61966-2.1"),
9499
- RegistryName: PDFString.of("http://www.color.org"),
9500
- Info: PDFString.of("sRGB IEC61966-2.1"),
11125
+ OutputConditionIdentifier: PDFString2.of("sRGB IEC61966-2.1"),
11126
+ RegistryName: PDFString2.of("http://www.color.org"),
11127
+ Info: PDFString2.of("sRGB IEC61966-2.1"),
9501
11128
  DestOutputProfile: iccRef
9502
11129
  })
9503
11130
  );
9504
- pdfDoc.catalog.set(PDFName2.of("OutputIntents"), pdfDoc.context.obj([outputIntentRef]));
11131
+ pdfDoc.catalog.set(PDFName3.of("OutputIntents"), pdfDoc.context.obj([outputIntentRef]));
9505
11132
  }
9506
11133
  function resolveElementStructRole(el) {
9507
11134
  switch (el.type) {
@@ -9533,9 +11160,9 @@ function resolveElementStructRole(el) {
9533
11160
  }
9534
11161
  }
9535
11162
  function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9536
- pdfDoc.catalog.set(PDFName2.of("Lang"), PDFString.of(snapshot.locale ? String(snapshot.locale) : "zh-CN"));
9537
- pdfDoc.catalog.set(PDFName2.of("MarkInfo"), pdfDoc.context.obj({ Marked: PDFBool.True }));
9538
- pdfDoc.catalog.set(PDFName2.of("ViewerPreferences"), pdfDoc.context.obj({ DisplayDocTitle: PDFBool.True }));
11163
+ pdfDoc.catalog.set(PDFName3.of("Lang"), PDFString2.of(snapshot.locale ? String(snapshot.locale) : "zh-CN"));
11164
+ pdfDoc.catalog.set(PDFName3.of("MarkInfo"), pdfDoc.context.obj({ Marked: PDFBool.True }));
11165
+ pdfDoc.catalog.set(PDFName3.of("ViewerPreferences"), pdfDoc.context.obj({ DisplayDocTitle: PDFBool.True }));
9539
11166
  if (!snapshot.metadata?.sanitized && snapshot.name) {
9540
11167
  pdfDoc.setTitle(snapshot.name);
9541
11168
  }
@@ -9547,16 +11174,16 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9547
11174
  const elemRef = pdfDoc.context.nextRef();
9548
11175
  const elemDict = {
9549
11176
  Type: "StructElem",
9550
- S: PDFName2.of(item.role),
11177
+ S: PDFName3.of(item.role),
9551
11178
  P: docElemRef,
9552
11179
  Pg: item.pageRef,
9553
- K: PDFNumber2.of(item.mcid)
11180
+ K: PDFNumber3.of(item.mcid)
9554
11181
  };
9555
11182
  if (item.altText) {
9556
- elemDict.Alt = PDFHexString.fromText(item.altText);
11183
+ elemDict.Alt = PDFHexString2.fromText(item.altText);
9557
11184
  }
9558
11185
  if (item.title) {
9559
- elemDict.T = PDFHexString.fromText(item.title);
11186
+ elemDict.T = PDFHexString2.fromText(item.title);
9560
11187
  }
9561
11188
  pdfDoc.context.assign(elemRef, pdfDoc.context.obj(elemDict));
9562
11189
  childElemRefs.push(elemRef);
@@ -9571,7 +11198,7 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9571
11198
  docElemRef,
9572
11199
  pdfDoc.context.obj({
9573
11200
  Type: "StructElem",
9574
- S: PDFName2.of("Document"),
11201
+ S: PDFName3.of("Document"),
9575
11202
  P: structTreeRootRef,
9576
11203
  K: childElemRefs
9577
11204
  })
@@ -9579,7 +11206,7 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9579
11206
  const numsList = [];
9580
11207
  for (let p = 0; p < totalPages; p++) {
9581
11208
  const refsForPage = (byPageMcid.get(p) ?? []).filter(Boolean);
9582
- numsList.push(PDFNumber2.of(p), pdfDoc.context.obj(refsForPage));
11209
+ numsList.push(PDFNumber3.of(p), pdfDoc.context.obj(refsForPage));
9583
11210
  }
9584
11211
  const parentTreeRef = pdfDoc.context.register(pdfDoc.context.obj({ Nums: numsList }));
9585
11212
  pdfDoc.context.assign(
@@ -9591,14 +11218,14 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9591
11218
  ParentTreeNextKey: totalPages
9592
11219
  })
9593
11220
  );
9594
- pdfDoc.catalog.set(PDFName2.of("StructTreeRoot"), structTreeRootRef);
11221
+ pdfDoc.catalog.set(PDFName3.of("StructTreeRoot"), structTreeRootRef);
9595
11222
  }
9596
11223
  function pruneUnreferencedObjectsAndCompressStreams(pdfDoc) {
9597
11224
  for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
9598
- if (obj instanceof PDFRawStream2) {
9599
- const typeName = obj.dict.get(PDFName2.of("Type"));
9600
- const isMetadata = typeName instanceof PDFName2 && typeName.decodeText() === "Metadata";
9601
- const hasFilter = Boolean(obj.dict.get(PDFName2.of("Filter")));
11225
+ if (obj instanceof PDFRawStream3) {
11226
+ const typeName = obj.dict.get(PDFName3.of("Type"));
11227
+ const isMetadata = typeName instanceof PDFName3 && typeName.decodeText() === "Metadata";
11228
+ const hasFilter = Boolean(obj.dict.get(PDFName3.of("Filter")));
9602
11229
  if (!isMetadata && !hasFilter && obj.contents.byteLength > 64) {
9603
11230
  const compressed = pdfDoc.context.flateStream(obj.contents);
9604
11231
  for (const [k, v] of obj.dict.entries()) {
@@ -9615,26 +11242,26 @@ function pruneUnreferencedObjectsAndCompressStreams(pdfDoc) {
9615
11242
  const refToString = (r) => `${r.objectNumber}:${r.generationNumber}`;
9616
11243
  const visit = (node) => {
9617
11244
  if (!node) return;
9618
- if (node instanceof PDFRef2) {
11245
+ if (node instanceof PDFRef3) {
9619
11246
  const key = refToString(node);
9620
11247
  if (reachable.has(key)) return;
9621
11248
  reachable.add(key);
9622
11249
  visit(pdfDoc.context.lookup(node));
9623
11250
  return;
9624
11251
  }
9625
- if (node instanceof PDFDict2) {
11252
+ if (node instanceof PDFDict3) {
9626
11253
  for (const [, val] of node.entries()) {
9627
11254
  visit(val);
9628
11255
  }
9629
11256
  return;
9630
11257
  }
9631
- if (node instanceof PDFArray2) {
11258
+ if (node instanceof PDFArray3) {
9632
11259
  for (let i = 0; i < node.size(); i++) {
9633
11260
  visit(node.get(i));
9634
11261
  }
9635
11262
  return;
9636
11263
  }
9637
- if (node instanceof PDFRawStream2 || node instanceof PDFStream2) {
11264
+ if (node instanceof PDFRawStream3 || node instanceof PDFStream3) {
9638
11265
  visit(node.dict);
9639
11266
  }
9640
11267
  };
@@ -9667,10 +11294,10 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
9667
11294
  pdfPage.pushOperators(
9668
11295
  pushGraphicsState2(),
9669
11296
  beginText(),
9670
- PDFOperator.of("Tr", [PDFNumber2.of(3)]),
11297
+ PDFOperator.of("Tr", [PDFNumber3.of(3)]),
9671
11298
  setFontAndSize(fontKey, fs),
9672
11299
  moveText(span.left, baselineY),
9673
- showText(PDFHexString.of(hexStr)),
11300
+ showText(PDFHexString2.of(hexStr)),
9674
11301
  endText(),
9675
11302
  popGraphicsState2()
9676
11303
  );
@@ -9683,10 +11310,10 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
9683
11310
  pdfPage.pushOperators(
9684
11311
  pushGraphicsState2(),
9685
11312
  beginText(),
9686
- PDFOperator.of("Tr", [PDFNumber2.of(3)]),
11313
+ PDFOperator.of("Tr", [PDFNumber3.of(3)]),
9687
11314
  setFontAndSize(fontKey, fs),
9688
11315
  moveText(span.left, baselineY),
9689
- showText(PDFHexString.of(asciiHex)),
11316
+ showText(PDFHexString2.of(asciiHex)),
9690
11317
  endText(),
9691
11318
  popGraphicsState2()
9692
11319
  );
@@ -9757,7 +11384,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9757
11384
  const optimizeSize = Boolean(options?.optimizeSize);
9758
11385
  const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
9759
11386
  throwIfExportAborted();
9760
- const pdfDoc = await PDFDocument2.create();
11387
+ const pdfDoc = await PDFDocument3.create();
9761
11388
  if (snapshot.metadata?.sanitized) {
9762
11389
  pdfDoc.setTitle("");
9763
11390
  pdfDoc.setAuthor("");
@@ -9957,7 +11584,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9957
11584
  if (!excludeBasePdf && snapshot.sourceDocumentRef?.dataUri) {
9958
11585
  try {
9959
11586
  const srcBytes = dataUriToBytes(snapshot.sourceDocumentRef.dataUri);
9960
- sourcePdfDoc = await PDFDocument2.load(srcBytes);
11587
+ sourcePdfDoc = await PDFDocument3.load(srcBytes);
9961
11588
  } catch {
9962
11589
  sourcePdfDoc = null;
9963
11590
  }
@@ -10171,21 +11798,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10171
11798
  const [copied] = await pdfDoc.copyPages(sourcePdfDoc, [pageMeta.sourcePageNumber - 1]);
10172
11799
  pdfPage = pdfDoc.addPage(copied);
10173
11800
  if (snapshot.metadata?.importedAcroFormBase) {
10174
- const existingAnnots = pdfDoc.context.lookupMaybe(pdfPage.node.get(PDFName2.of("Annots")), PDFArray2);
11801
+ const existingAnnots = pdfDoc.context.lookupMaybe(pdfPage.node.get(PDFName3.of("Annots")), PDFArray3);
10175
11802
  if (existingAnnots) {
10176
11803
  const filtered = [];
10177
11804
  for (let ai = 0; ai < existingAnnots.size(); ai++) {
10178
11805
  const aRef = existingAnnots.get(ai);
10179
- const aDict = pdfDoc.context.lookupMaybe(aRef, PDFDict2);
10180
- const sub = aDict?.get(PDFName2.of("Subtype"));
10181
- if (!(sub instanceof PDFName2 && sub.decodeText() === "Widget")) {
11806
+ const aDict = pdfDoc.context.lookupMaybe(aRef, PDFDict3);
11807
+ const sub = aDict?.get(PDFName3.of("Subtype"));
11808
+ if (!(sub instanceof PDFName3 && sub.decodeText() === "Widget")) {
10182
11809
  filtered.push(aRef);
10183
11810
  }
10184
11811
  }
10185
11812
  if (filtered.length > 0) {
10186
- pdfPage.node.set(PDFName2.of("Annots"), pdfDoc.context.obj(filtered));
11813
+ pdfPage.node.set(PDFName3.of("Annots"), pdfDoc.context.obj(filtered));
10187
11814
  } else {
10188
- pdfPage.node.delete(PDFName2.of("Annots"));
11815
+ pdfPage.node.delete(PDFName3.of("Annots"));
10189
11816
  }
10190
11817
  }
10191
11818
  }
@@ -10196,7 +11823,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10196
11823
  let size = pageMeta.pageSize ?? snapshot.document.pageSize;
10197
11824
  if (excludeBasePdf && snapshot.sourceDocumentRef?.dataUri && !pageMeta.pageSize) {
10198
11825
  try {
10199
- const tempSrc = await PDFDocument2.load(dataUriToBytes(snapshot.sourceDocumentRef.dataUri));
11826
+ const tempSrc = await PDFDocument3.load(dataUriToBytes(snapshot.sourceDocumentRef.dataUri));
10200
11827
  const pIdx0 = Math.max(0, (pageMeta.sourcePageNumber ?? 1) - 1);
10201
11828
  if (pIdx0 < tempSrc.getPageCount()) {
10202
11829
  const refSz = tempSrc.getPage(pIdx0).getSize();
@@ -10223,9 +11850,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10223
11850
  pdfPage.setRotation(degrees2(pageMeta.rotation));
10224
11851
  }
10225
11852
  if (pageMeta.cropBox) {
10226
- const cb = pageMeta.cropBox;
10227
- const cropY = Math.max(0, pageHeight - cb.top - cb.height);
10228
- pdfPage.setCropBox(cb.left, cropY, cb.width, cb.height);
11853
+ const cb = resolvePdfCropBoxPt(pageMeta.cropBox);
11854
+ if (cb) {
11855
+ const cropY = Math.max(0, pageHeight - cb.top - cb.height);
11856
+ pdfPage.setCropBox(cb.left, cropY, cb.width, cb.height);
11857
+ }
10229
11858
  }
10230
11859
  if (isCopiedBasePage && suppressedNativeRects.length > 0) {
10231
11860
  for (const sRect of suppressedNativeRects) {
@@ -10240,8 +11869,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10240
11869
  }
10241
11870
  }
10242
11871
  if (accessibilityTagged) {
10243
- pdfPage.node.set(PDFName2.of("StructParents"), PDFNumber2.of(pIndex));
10244
- pdfPage.node.set(PDFName2.of("Tabs"), PDFName2.of("S"));
11872
+ pdfPage.node.set(PDFName3.of("StructParents"), PDFNumber3.of(pIndex));
11873
+ pdfPage.node.set(PDFName3.of("Tabs"), PDFName3.of("S"));
10245
11874
  }
10246
11875
  let nextPageMcid = 0;
10247
11876
  const activeDynamicRange = planItem.dynamicSplitRanges ? planItem.dynamicSplitRanges[chunkIndex] : void 0;
@@ -10296,9 +11925,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10296
11925
  let hasOpenCenterTransform = false;
10297
11926
  if (ocgEntry) {
10298
11927
  const propsDict = ensurePagePropertiesDict(pdfDoc, pdfPage);
10299
- propsDict.set(PDFName2.of(ocgEntry.propName), ocgEntry.ocgRef);
11928
+ propsDict.set(PDFName3.of(ocgEntry.propName), ocgEntry.ocgRef);
10300
11929
  pdfPage.pushOperators(
10301
- PDFOperator.of("BDC", [PDFName2.of("OC"), PDFName2.of(ocgEntry.propName)])
11930
+ PDFOperator.of("BDC", [PDFName3.of("OC"), PDFName3.of(ocgEntry.propName)])
10302
11931
  );
10303
11932
  openBdcCount++;
10304
11933
  }
@@ -10306,10 +11935,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10306
11935
  const mcid = nextPageMcid++;
10307
11936
  const mcPropName = `MC_${mcid}`;
10308
11937
  const propsDict = ensurePagePropertiesDict(pdfDoc, pdfPage);
10309
- propsDict.set(PDFName2.of(mcPropName), pdfDoc.context.obj({ MCID: PDFNumber2.of(mcid) }));
11938
+ propsDict.set(PDFName3.of(mcPropName), pdfDoc.context.obj({ MCID: PDFNumber3.of(mcid) }));
10310
11939
  const role = resolveElementStructRole(el);
10311
11940
  pdfPage.pushOperators(
10312
- PDFOperator.of("BDC", [PDFName2.of(role), PDFName2.of(mcPropName)])
11941
+ PDFOperator.of("BDC", [PDFName3.of(role), PDFName3.of(mcPropName)])
10313
11942
  );
10314
11943
  openBdcCount++;
10315
11944
  taggedStructItems.push({
@@ -10525,60 +12154,123 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10525
12154
  { colorType: elColorType }
10526
12155
  );
10527
12156
  } else if (el.type === "stamp" /* STAMP */) {
10528
- const sealColor = parseHexColor(el.color) ?? { r: 0.86, g: 0.15, b: 0.15, a: 1 };
10529
- const sealPdfCol = toPdfLibColor(sealColor, elColorType);
10530
- if (el.stampShape === "rect") {
10531
- pdfPage.drawRectangle({
10532
- x: left,
10533
- y: pdfY,
12157
+ if (el.svgContent) {
12158
+ drawVectorSvgOnPdfPage(
12159
+ pdfPage,
12160
+ pageHeight,
12161
+ left,
12162
+ top,
10534
12163
  width,
10535
12164
  height,
10536
- borderColor: sealPdfCol,
10537
- borderWidth: 2,
10538
- opacity: (el.opacity ?? 0.85) * sealColor.a
10539
- });
12165
+ el.svgContent,
12166
+ el.opacity ?? 0.9,
12167
+ elColorType
12168
+ );
12169
+ const stampTexts = extractSvgTextDescriptors(el.svgContent, width, height);
12170
+ for (const td of stampTexts) {
12171
+ try {
12172
+ await drawTextBox(
12173
+ pdfDoc,
12174
+ pdfPage,
12175
+ pageHeight,
12176
+ td.text,
12177
+ left + td.leftPt,
12178
+ top + td.topPt,
12179
+ td.widthPt,
12180
+ td.heightPt,
12181
+ {
12182
+ fontSize: td.fontSizePt,
12183
+ fontWeight: td.bold ? "bold" : "normal",
12184
+ color: td.color,
12185
+ textAlign: td.align,
12186
+ verticalAlign: "middle",
12187
+ padding: 0
12188
+ },
12189
+ cjkState,
12190
+ { noWrapSingleLine: true, colorType: elColorType }
12191
+ );
12192
+ } catch {
12193
+ await drawTextBox(
12194
+ pdfDoc,
12195
+ pdfPage,
12196
+ pageHeight,
12197
+ td.text,
12198
+ left + td.leftPt,
12199
+ top + td.topPt,
12200
+ td.widthPt,
12201
+ td.heightPt,
12202
+ {
12203
+ fontSize: td.fontSizePt,
12204
+ fontWeight: td.bold ? "bold" : "normal",
12205
+ color: td.color,
12206
+ textAlign: td.align,
12207
+ verticalAlign: "middle",
12208
+ padding: 0
12209
+ },
12210
+ null,
12211
+ { noWrapSingleLine: true, colorType: elColorType }
12212
+ );
12213
+ }
12214
+ }
10540
12215
  } else {
10541
- pdfPage.drawEllipse({
10542
- x: left + width / 2,
10543
- y: pdfY + height / 2,
10544
- xScale: width / 2,
10545
- yScale: height / 2,
10546
- borderColor: sealPdfCol,
10547
- borderWidth: 2,
10548
- opacity: (el.opacity ?? 0.85) * sealColor.a
10549
- });
10550
- pdfPage.drawEllipse({
10551
- x: left + width / 2,
10552
- y: pdfY + height / 2,
10553
- xScale: Math.max(4, width / 2 - 3.5),
10554
- yScale: Math.max(4, height / 2 - 3.5),
10555
- borderColor: sealPdfCol,
10556
- borderWidth: 0.75,
10557
- opacity: (el.opacity ?? 0.85) * sealColor.a
10558
- });
10559
- }
10560
- const stampText = el.secondaryText ? `${el.primaryText}
12216
+ const sealColor = parseHexColor(el.color) ?? { r: 0.86, g: 0.15, b: 0.15, a: 1 };
12217
+ const sealPdfCol = toPdfLibColor(sealColor, elColorType);
12218
+ if (el.stampShape === "rect" || el.stampShape === "pill") {
12219
+ pdfPage.drawRectangle({
12220
+ x: left,
12221
+ y: pdfY,
12222
+ width,
12223
+ height,
12224
+ borderColor: sealPdfCol,
12225
+ borderWidth: 2,
12226
+ opacity: (el.opacity ?? 0.85) * sealColor.a
12227
+ });
12228
+ } else {
12229
+ pdfPage.drawEllipse({
12230
+ x: left + width / 2,
12231
+ y: pdfY + height / 2,
12232
+ xScale: width / 2,
12233
+ yScale: height / 2,
12234
+ borderColor: sealPdfCol,
12235
+ borderWidth: 2,
12236
+ opacity: (el.opacity ?? 0.85) * sealColor.a
12237
+ });
12238
+ pdfPage.drawEllipse({
12239
+ x: left + width / 2,
12240
+ y: pdfY + height / 2,
12241
+ xScale: Math.max(4, width / 2 - 3.5),
12242
+ yScale: Math.max(4, height / 2 - 3.5),
12243
+ borderColor: sealPdfCol,
12244
+ borderWidth: 0.75,
12245
+ opacity: (el.opacity ?? 0.85) * sealColor.a
12246
+ });
12247
+ }
12248
+ const signerFooter = [el.signer, el.dateText].filter(Boolean).join(" \xB7 ");
12249
+ const baseStampText = el.secondaryText ? `${el.primaryText}
10561
12250
  \u2605 ${el.secondaryText}` : el.primaryText;
10562
- await drawTextBox(
10563
- pdfDoc,
10564
- pdfPage,
10565
- pageHeight,
10566
- stampText,
10567
- left + 6,
10568
- top + 6,
10569
- width - 12,
10570
- height - 12,
10571
- {
10572
- fontSize: 10,
10573
- fontWeight: "bold",
10574
- color: el.color ?? "#dc2626",
10575
- textAlign: "center",
10576
- verticalAlign: "middle",
10577
- lineHeight: 1.35
10578
- },
10579
- cjkState,
10580
- { colorType: elColorType }
10581
- );
12251
+ const stampText = signerFooter ? `${baseStampText}
12252
+ ${signerFooter}` : baseStampText;
12253
+ await drawTextBox(
12254
+ pdfDoc,
12255
+ pdfPage,
12256
+ pageHeight,
12257
+ stampText,
12258
+ left + 6,
12259
+ top + 6,
12260
+ width - 12,
12261
+ height - 12,
12262
+ {
12263
+ fontSize: 10,
12264
+ fontWeight: "bold",
12265
+ color: el.color ?? "#dc2626",
12266
+ textAlign: "center",
12267
+ verticalAlign: "middle",
12268
+ lineHeight: 1.35
12269
+ },
12270
+ cjkState,
12271
+ { colorType: elColorType }
12272
+ );
12273
+ }
10582
12274
  } else if (el.type === "ink" /* INK */) {
10583
12275
  const stroke2 = parseHexColor(el.strokeColor) ?? { r: 0.94, g: 0.27, b: 0.27, a: 1 };
10584
12276
  const strokeCol = toPdfLibColor(stroke2, elColorType);
@@ -10664,9 +12356,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10664
12356
  if (textEl.locked) tf.enableReadOnly();
10665
12357
  if (textEl.required) tf.enableRequired();
10666
12358
  tf.acroField.dict.set(
10667
- PDFName2.of("YudaoMeta"),
12359
+ PDFName3.of("YudaoMeta"),
10668
12360
  pdfDoc.context.obj({
10669
- ElementType: PDFName2.of("text"),
12361
+ ElementType: PDFName3.of("text"),
10670
12362
  Left: left,
10671
12363
  Top: top,
10672
12364
  Width: width,
@@ -10686,10 +12378,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10686
12378
  txtCol
10687
12379
  });
10688
12380
  const daStr = `/FCjk ${fmtPdfNum(fsVal)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
10689
- tf.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12381
+ tf.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10690
12382
  for (const w of tf.acroField.getWidgets()) {
10691
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
10692
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12383
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
12384
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10693
12385
  }
10694
12386
  } else {
10695
12387
  tf.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -10820,6 +12512,32 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10820
12512
  svgEl.opacity ?? 1,
10821
12513
  elColorType
10822
12514
  );
12515
+ const svgTextNodes = extractSvgTextDescriptors(resolvedSvg, width, height);
12516
+ for (const td of svgTextNodes) {
12517
+ try {
12518
+ await drawTextBox(
12519
+ pdfDoc,
12520
+ pdfPage,
12521
+ pageHeight,
12522
+ td.text,
12523
+ left + td.leftPt,
12524
+ top + td.topPt,
12525
+ td.widthPt,
12526
+ td.heightPt,
12527
+ {
12528
+ fontSize: td.fontSizePt,
12529
+ fontWeight: td.bold ? "bold" : "normal",
12530
+ color: td.color,
12531
+ textAlign: td.align,
12532
+ verticalAlign: "middle",
12533
+ padding: 0
12534
+ },
12535
+ !hasNonAscii(td.text) ? cjkState : null,
12536
+ { noWrapSingleLine: true, colorType: elColorType }
12537
+ );
12538
+ } catch {
12539
+ }
12540
+ }
10823
12541
  } else if (el.type === "circleMark" /* CIRCLE_MARK */) {
10824
12542
  const cmEl = el;
10825
12543
  const cmKey = cmEl.formFieldName || cmEl.fieldKey || cmEl.bindingField;
@@ -10894,21 +12612,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10894
12612
  if (dtEl.locked) tf.enableReadOnly();
10895
12613
  if (dtEl.required) tf.enableRequired();
10896
12614
  tf.acroField.dict.set(
10897
- PDFName2.of("TU"),
10898
- PDFHexString.fromText(
12615
+ PDFName3.of("TU"),
12616
+ PDFHexString2.fromText(
10899
12617
  `dateTime:${dtEl.dateKind || "date"}|${dtEl.format || "YYYY-MM-DD"}|${dtEl.locale || ""}`
10900
12618
  )
10901
12619
  );
10902
12620
  tf.acroField.dict.set(
10903
- PDFName2.of("YudaoMeta"),
12621
+ PDFName3.of("YudaoMeta"),
10904
12622
  pdfDoc.context.obj({
10905
- ElementType: PDFName2.of("dateTime"),
10906
- DateKind: PDFString.of(dtEl.dateKind || "date"),
10907
- Format: PDFHexString.fromText(dtEl.format || "YYYY-MM-DD"),
10908
- ...dtEl.locale ? { Locale: PDFString.of(dtEl.locale) } : {},
10909
- RawValue: PDFHexString.fromText(rawDtVal),
12623
+ ElementType: PDFName3.of("dateTime"),
12624
+ DateKind: PDFString2.of(dtEl.dateKind || "date"),
12625
+ Format: PDFHexString2.fromText(dtEl.format || "YYYY-MM-DD"),
12626
+ ...dtEl.locale ? { Locale: PDFString2.of(dtEl.locale) } : {},
12627
+ RawValue: PDFHexString2.fromText(rawDtVal),
10910
12628
  FontSize: dtFontSize,
10911
- Align: PDFString.of(dtAlign),
12629
+ Align: PDFString2.of(dtAlign),
10912
12630
  ...dtEl.characterSpacing !== void 0 ? { CharacterSpacing: dtEl.characterSpacing } : {},
10913
12631
  Left: left,
10914
12632
  Top: top,
@@ -10929,10 +12647,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10929
12647
  txtCol
10930
12648
  });
10931
12649
  const daStr = `/FCjk ${fmtPdfNum(dtFontSize)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
10932
- tf.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12650
+ tf.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10933
12651
  for (const w of tf.acroField.getWidgets()) {
10934
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
10935
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12652
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
12653
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10936
12654
  }
10937
12655
  } else {
10938
12656
  tf.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -10995,14 +12713,14 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10995
12713
  if (cbEl.required) cb.enableRequired();
10996
12714
  cb.defaultUpdateAppearances();
10997
12715
  cb.acroField.dict.set(
10998
- PDFName2.of("TU"),
10999
- PDFHexString.fromText(cbEl.label || fieldName)
12716
+ PDFName3.of("TU"),
12717
+ PDFHexString2.fromText(cbEl.label || fieldName)
11000
12718
  );
11001
12719
  cb.acroField.dict.set(
11002
- PDFName2.of("YudaoMeta"),
12720
+ PDFName3.of("YudaoMeta"),
11003
12721
  pdfDoc.context.obj({
11004
- ElementType: PDFName2.of("checkbox"),
11005
- Label: PDFHexString.fromText(cbEl.label || ""),
12722
+ ElementType: PDFName3.of("checkbox"),
12723
+ Label: PDFHexString2.fromText(cbEl.label || ""),
11006
12724
  BoxWidth: boxSz,
11007
12725
  Left: left,
11008
12726
  Top: top,
@@ -11133,10 +12851,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11133
12851
  if (rgEl.required) rg.enableRequired();
11134
12852
  rg.defaultUpdateAppearances();
11135
12853
  rg.acroField.dict.set(
11136
- PDFName2.of("YudaoMeta"),
12854
+ PDFName3.of("YudaoMeta"),
11137
12855
  pdfDoc.context.obj({
11138
- ElementType: PDFName2.of("radioGroup"),
11139
- Direction: PDFString.of(rgEl.direction || "horizontal"),
12856
+ ElementType: PDFName3.of("radioGroup"),
12857
+ Direction: PDFString2.of(rgEl.direction || "horizontal"),
11140
12858
  Left: left,
11141
12859
  Top: top,
11142
12860
  Width: width,
@@ -11204,10 +12922,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11204
12922
  if (selEl.locked) dd.enableReadOnly();
11205
12923
  if (selEl.required) dd.enableRequired();
11206
12924
  dd.acroField.dict.set(
11207
- PDFName2.of("YudaoMeta"),
12925
+ PDFName3.of("YudaoMeta"),
11208
12926
  pdfDoc.context.obj({
11209
- ElementType: PDFName2.of("select"),
11210
- ...selEl.placeholder ? { Placeholder: PDFHexString.fromText(selEl.placeholder) } : {},
12927
+ ElementType: PDFName3.of("select"),
12928
+ ...selEl.placeholder ? { Placeholder: PDFHexString2.fromText(selEl.placeholder) } : {},
11211
12929
  Left: left,
11212
12930
  Top: top,
11213
12931
  Width: width,
@@ -11227,10 +12945,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11227
12945
  txtCol
11228
12946
  });
11229
12947
  const daStr = `/FCjk ${fmtPdfNum(fsVal)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
11230
- dd.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12948
+ dd.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
11231
12949
  for (const w of dd.acroField.getWidgets()) {
11232
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
11233
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12950
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
12951
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
11234
12952
  }
11235
12953
  } else {
11236
12954
  dd.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -11270,8 +12988,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11270
12988
  Type: "Annot",
11271
12989
  Subtype: "Widget",
11272
12990
  FT: "Sig",
11273
- T: PDFHexString.fromText(fieldName),
11274
- TU: PDFHexString.fromText(sigEl.label || fieldName),
12991
+ T: PDFHexString2.fromText(fieldName),
12992
+ TU: PDFHexString2.fromText(sigEl.label || fieldName),
11275
12993
  Rect: [left, pdfY, left + width, pdfY + height],
11276
12994
  P: pdfPage.ref,
11277
12995
  F: 4,
@@ -11279,12 +12997,12 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11279
12997
  AP: { N: sigApRef },
11280
12998
  MK: { R: rotDeg },
11281
12999
  YudaoMeta: {
11282
- ElementType: PDFName2.of("signature"),
11283
- Label: PDFHexString.fromText(sigEl.label || "Signature"),
11284
- ...sigEl.signerName ? { SignerName: PDFHexString.fromText(sigEl.signerName) } : {},
11285
- ...sigEl.signedAt ? { SignedAt: PDFString.of(sigEl.signedAt) } : {},
11286
- ...sigEl.reason ? { Reason: PDFHexString.fromText(sigEl.reason) } : {},
11287
- ...sigEl.signatureDataUri ? { SignatureDataUri: PDFString.of(sigEl.signatureDataUri) } : {},
13000
+ ElementType: PDFName3.of("signature"),
13001
+ Label: PDFHexString2.fromText(sigEl.label || "Signature"),
13002
+ ...sigEl.signerName ? { SignerName: PDFHexString2.fromText(sigEl.signerName) } : {},
13003
+ ...sigEl.signedAt ? { SignedAt: PDFString2.of(sigEl.signedAt) } : {},
13004
+ ...sigEl.reason ? { Reason: PDFHexString2.fromText(sigEl.reason) } : {},
13005
+ ...sigEl.signatureDataUri ? { SignatureDataUri: PDFString2.of(sigEl.signatureDataUri) } : {},
11288
13006
  Left: left,
11289
13007
  Top: top,
11290
13008
  Width: width,
@@ -11295,11 +13013,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11295
13013
  if (sigEl.signerName || sigEl.signatureDataUri) {
11296
13014
  sigWidgetObj.V = pdfDoc.context.obj({
11297
13015
  Type: "Sig",
11298
- Filter: PDFName2.of("Adobe.PPKLite"),
11299
- SubFilter: PDFName2.of("adbe.pkcs7.detached"),
11300
- Name: PDFHexString.fromText(sigEl.signerName || sigEl.label || "Signed"),
11301
- ...sigEl.signedAt ? { M: PDFString.of(sigEl.signedAt) } : {},
11302
- ...sigEl.reason ? { Reason: PDFHexString.fromText(sigEl.reason) } : {}
13016
+ Filter: PDFName3.of("Adobe.PPKLite"),
13017
+ SubFilter: PDFName3.of("adbe.pkcs7.detached"),
13018
+ Name: PDFHexString2.fromText(sigEl.signerName || sigEl.label || "Signed"),
13019
+ ...sigEl.signedAt ? { M: PDFString2.of(sigEl.signedAt) } : {},
13020
+ ...sigEl.reason ? { Reason: PDFHexString2.fromText(sigEl.reason) } : {}
11303
13021
  });
11304
13022
  }
11305
13023
  const sigRef = pdfDoc.context.register(pdfDoc.context.obj(sigWidgetObj));
@@ -11618,19 +13336,33 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11618
13336
  });
11619
13337
  }
11620
13338
  const pdfSubtype = annotType === "highlight" ? "Highlight" : annotType === "underline" ? "Underline" : annotType === "strikeout" ? "StrikeOut" : annotType === "squiggly" ? "Squiggly" : "Text";
13339
+ const effectiveStatus = annotEl.reviewStatus ?? annotEl.status;
11621
13340
  const replyLines = (annotEl.replies ?? []).map((r) => `[${r.author}] ${r.content}`);
11622
13341
  const threadSummary = [
11623
- annotEl.status ? `[${annotEl.status.toUpperCase()}] ${annotEl.comment ?? ""}`.trim() : annotEl.comment ?? "",
13342
+ effectiveStatus ? `[${effectiveStatus.toUpperCase()}] ${annotEl.comment ?? ""}`.trim() : annotEl.comment ?? "",
11624
13343
  ...replyLines
11625
13344
  ].filter(Boolean).join("\n");
13345
+ const pdfReviewStateMap = {
13346
+ accepted: "Accepted",
13347
+ rejected: "Rejected",
13348
+ completed: "Completed",
13349
+ cancelled: "Cancelled",
13350
+ resolved: "Completed",
13351
+ open: "None"
13352
+ };
13353
+ const pdfReviewState = effectiveStatus ? pdfReviewStateMap[effectiveStatus] : void 0;
11626
13354
  const annotDictEntries = {
11627
13355
  Type: "Annot",
11628
13356
  Subtype: pdfSubtype,
11629
13357
  Rect: [left, pdfY, left + width, pdfY + height],
11630
13358
  C: [col.r, col.g, col.b],
11631
13359
  CA: op,
11632
- T: PDFHexString.fromText(annotEl.author || "Reviewer"),
11633
- Contents: PDFHexString.fromText(threadSummary)
13360
+ T: PDFHexString2.fromText(annotEl.author || "Reviewer"),
13361
+ Contents: PDFHexString2.fromText(threadSummary),
13362
+ ...pdfReviewState ? {
13363
+ StateModel: PDFString2.of("Review"),
13364
+ State: PDFString2.of(pdfReviewState)
13365
+ } : {}
11634
13366
  };
11635
13367
  if (pdfSubtype !== "Text") {
11636
13368
  annotDictEntries.QuadPoints = [
@@ -11801,7 +13533,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11801
13533
  setFillingRgbColor(0.78, 0.81, 0.86),
11802
13534
  setFontAndSize(fontKey, wmSize),
11803
13535
  rotateAndSkewTextDegreesAndTranslate(wmAngle, 0, 0, wx, wy),
11804
- showText(PDFHexString.of(hexWm)),
13536
+ showText(PDFHexString2.of(hexWm)),
11805
13537
  endText(),
11806
13538
  popGraphicsState2()
11807
13539
  );
@@ -11849,7 +13581,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11849
13581
  }
11850
13582
  return void 0;
11851
13583
  };
11852
- return walk(snapshot.metadata?.bookmarks);
13584
+ return walk(snapshot.bookmarks ?? snapshot.metadata?.bookmarks);
11853
13585
  };
11854
13586
  for (const linkItem of deferredLinkAnnotations) {
11855
13587
  const hostPage = allPages[linkItem.hostPageIndex];
@@ -11864,9 +13596,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11864
13596
  const targetPage = allPages[clampedIdx];
11865
13597
  const destArr = pdfDoc.context.obj([
11866
13598
  targetPage.ref,
11867
- PDFName2.of("XYZ"),
11868
- PDFNumber2.of(elDest.x),
11869
- PDFNumber2.of(elDest.topY),
13599
+ PDFName3.of("XYZ"),
13600
+ PDFNumber3.of(elDest.x),
13601
+ PDFNumber3.of(elDest.topY),
11870
13602
  null
11871
13603
  ]);
11872
13604
  const actionDict = pdfDoc.context.obj({
@@ -11895,9 +13627,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11895
13627
  const targetPage = allPages[clampedIdx];
11896
13628
  const destArr = pdfDoc.context.obj([
11897
13629
  targetPage.ref,
11898
- PDFName2.of("XYZ"),
11899
- PDFNumber2.of(0),
11900
- PDFNumber2.of(targetPage.getHeight()),
13630
+ PDFName3.of("XYZ"),
13631
+ PDFNumber3.of(0),
13632
+ PDFNumber3.of(targetPage.getHeight()),
11901
13633
  null
11902
13634
  ]);
11903
13635
  const actionDict = pdfDoc.context.obj({
@@ -11925,7 +13657,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11925
13657
  const actionDict = pdfDoc.context.obj({
11926
13658
  Type: "Action",
11927
13659
  S: "URI",
11928
- URI: PDFString.of(trimmedUrl)
13660
+ URI: PDFString2.of(trimmedUrl)
11929
13661
  });
11930
13662
  const linkAnnot = pdfDoc.context.obj({
11931
13663
  Type: "Annot",
@@ -11938,7 +13670,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11938
13670
  } else if (typeof linkItem.linkPageIndex === "number" && linkItem.linkPageIndex >= 0 && allPages.length > 0) {
11939
13671
  const clampedIdx = Math.min(allPages.length - 1, Math.floor(linkItem.linkPageIndex));
11940
13672
  const targetPage = allPages[clampedIdx];
11941
- const destArr = pdfDoc.context.obj([targetPage.ref, PDFName2.of("XYZ"), null, null, null]);
13673
+ const destArr = pdfDoc.context.obj([targetPage.ref, PDFName3.of("XYZ"), null, null, null]);
11942
13674
  const linkAnnot = pdfDoc.context.obj({
11943
13675
  Type: "Annot",
11944
13676
  Subtype: "Link",
@@ -11950,8 +13682,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11950
13682
  }
11951
13683
  }
11952
13684
  }
11953
- if (snapshot.metadata?.bookmarks && snapshot.metadata.bookmarks.length > 0) {
11954
- attachPdfOutlinesTree(pdfDoc, snapshot.metadata.bookmarks);
13685
+ const effectiveBookmarks = snapshot.bookmarks ?? snapshot.metadata?.bookmarks;
13686
+ if (effectiveBookmarks && effectiveBookmarks.length > 0) {
13687
+ attachPdfOutlinesTree(pdfDoc, effectiveBookmarks);
11955
13688
  }
11956
13689
  const attachments = snapshot.attachments ?? snapshot.metadata?.attachments ?? [];
11957
13690
  if (attachments.length > 0) {
@@ -11963,28 +13696,28 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11963
13696
  const pieceDict = {};
11964
13697
  if (sigEnv) {
11965
13698
  pieceDict.UniverSignature = {
11966
- LastModified: PDFString.of(sigEnv.signedAt || (/* @__PURE__ */ new Date()).toISOString()),
13699
+ LastModified: PDFString2.of(sigEnv.signedAt || (/* @__PURE__ */ new Date()).toISOString()),
11967
13700
  Private: pdfDoc.context.obj({
11968
- Algorithm: PDFName2.of("SHA-256"),
11969
- Signer: PDFHexString.fromText(sigEnv.signerName),
11970
- CertificateSubject: PDFHexString.fromText(sigEnv.certificateSubject),
11971
- ContentDigest: PDFString.of(sigEnv.contentDigestHex),
11972
- EnvelopeDigest: PDFString.of(sigEnv.envelopeDigestHex)
13701
+ Algorithm: PDFName3.of("SHA-256"),
13702
+ Signer: PDFHexString2.fromText(sigEnv.signerName),
13703
+ CertificateSubject: PDFHexString2.fromText(sigEnv.certificateSubject),
13704
+ ContentDigest: PDFString2.of(sigEnv.contentDigestHex),
13705
+ EnvelopeDigest: PDFString2.of(sigEnv.envelopeDigestHex)
11973
13706
  })
11974
13707
  };
11975
13708
  }
11976
13709
  if (secPerms) {
11977
13710
  pieceDict.UniverSecurity = {
11978
- LastModified: PDFString.of((/* @__PURE__ */ new Date()).toISOString()),
13711
+ LastModified: PDFString2.of((/* @__PURE__ */ new Date()).toISOString()),
11979
13712
  Private: pdfDoc.context.obj({
11980
13713
  AllowPrint: secPerms.allowPrint !== false ? PDFBool.True : PDFBool.False,
11981
13714
  AllowCopy: secPerms.allowCopy !== false ? PDFBool.True : PDFBool.False,
11982
13715
  AllowModify: secPerms.allowModify !== false ? PDFBool.True : PDFBool.False,
11983
- ...secPerms.openPasswordHash ? { OpenPasswordHash: PDFString.of(secPerms.openPasswordHash) } : {}
13716
+ ...secPerms.openPasswordHash ? { OpenPasswordHash: PDFString2.of(secPerms.openPasswordHash) } : {}
11984
13717
  })
11985
13718
  };
11986
13719
  }
11987
- pdfDoc.catalog.set(PDFName2.of("PieceInfo"), pdfDoc.context.obj(pieceDict));
13720
+ pdfDoc.catalog.set(PDFName3.of("PieceInfo"), pdfDoc.context.obj(pieceDict));
11988
13721
  }
11989
13722
  if (accessibilityTagged) {
11990
13723
  attachTaggedStructTreeRoot(pdfDoc, snapshot, taggedStructItems, totalPhysicalPages);
@@ -11995,66 +13728,76 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11995
13728
  if (interactiveForm && hasAnyAcroWidget) {
11996
13729
  const acroDict = pdfDoc.getForm().acroForm.dict;
11997
13730
  const helv = await ensureAcroHelvetica();
11998
- let drDict = pdfDoc.context.lookupMaybe(acroDict.get(PDFName2.of("DR")), PDFDict2);
13731
+ let drDict = pdfDoc.context.lookupMaybe(acroDict.get(PDFName3.of("DR")), PDFDict3);
11999
13732
  if (!drDict) {
12000
13733
  drDict = pdfDoc.context.obj({});
12001
- acroDict.set(PDFName2.of("DR"), drDict);
13734
+ acroDict.set(PDFName3.of("DR"), drDict);
12002
13735
  }
12003
- let fontDict = pdfDoc.context.lookupMaybe(drDict.get(PDFName2.of("Font")), PDFDict2);
13736
+ let fontDict = pdfDoc.context.lookupMaybe(drDict.get(PDFName3.of("Font")), PDFDict3);
12004
13737
  if (!fontDict) {
12005
13738
  fontDict = pdfDoc.context.obj({});
12006
- drDict.set(PDFName2.of("Font"), fontDict);
13739
+ drDict.set(PDFName3.of("Font"), fontDict);
12007
13740
  }
12008
- fontDict.set(PDFName2.of("Helv"), helv.ref);
13741
+ fontDict.set(PDFName3.of("Helv"), helv.ref);
12009
13742
  if (acroCjkState) {
12010
- fontDict.set(PDFName2.of("FCjk"), acroCjkState.type0FontRef);
13743
+ fontDict.set(PDFName3.of("FCjk"), acroCjkState.type0FontRef);
12011
13744
  }
12012
13745
  acroDict.set(
12013
- PDFName2.of("DA"),
12014
- PDFString.of(acroCjkState ? "/FCjk 11 Tf 0 0 0 rg" : "/Helv 11 Tf 0 0 0 rg")
13746
+ PDFName3.of("DA"),
13747
+ PDFString2.of(acroCjkState ? "/FCjk 11 Tf 0 0 0 rg" : "/Helv 11 Tf 0 0 0 rg")
12015
13748
  );
12016
- acroDict.delete(PDFName2.of("NeedAppearances"));
13749
+ acroDict.delete(PDFName3.of("NeedAppearances"));
12017
13750
  }
12018
13751
  if (optimizeSize) {
12019
13752
  pruneUnreferencedObjectsAndCompressStreams(pdfDoc);
12020
13753
  }
13754
+ const effectiveSecurity = options?.security ?? snapshot.security ?? snapshot.metadata?.security;
13755
+ const shouldEncrypt = isPdfSecurityActive(effectiveSecurity);
12021
13756
  throwIfExportAborted();
13757
+ if (shouldEncrypt && !options?.diagnosticGridOverlay) {
13758
+ await applyPdfSecurityToDocument(pdfDoc, effectiveSecurity);
13759
+ const encryptedSavedBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false }) : await pdfDoc.save({ useObjectStreams: false });
13760
+ throwIfExportAborted();
13761
+ return encryptedSavedBytes;
13762
+ }
12022
13763
  const savedPdfBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ updateFieldAppearances: false }) : await pdfDoc.save();
12023
13764
  throwIfExportAborted();
12024
13765
  if (options?.diagnosticGridOverlay) {
12025
13766
  const gridOpts = typeof options.diagnosticGridOverlay === "object" ? options.diagnosticGridOverlay : void 0;
12026
- return await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
13767
+ const overlaidBytes = await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
13768
+ return shouldEncrypt ? await encryptPdfBytes(overlaidBytes, effectiveSecurity) : overlaidBytes;
12027
13769
  }
12028
13770
  return savedPdfBytes;
12029
13771
  }
13772
+ var exportPdfUnitToBytes = exportPdfBytes;
12030
13773
  function decodePdfObjAsString(obj) {
12031
13774
  if (!obj) return "";
12032
- if (obj instanceof PDFHexString || obj instanceof PDFString || obj instanceof PDFName2) {
13775
+ if (obj instanceof PDFHexString2 || obj instanceof PDFString2 || obj instanceof PDFName3) {
12033
13776
  return obj.decodeText();
12034
13777
  }
12035
13778
  return "";
12036
13779
  }
12037
13780
  function extractSigDictValue(doc, fieldOrWidgetDict) {
12038
- const metaDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName2.of("YudaoMeta")), PDFDict2);
13781
+ const metaDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName3.of("YudaoMeta")), PDFDict3);
12039
13782
  if (metaDict) {
12040
- const dataUri = decodePdfObjAsString(metaDict.get(PDFName2.of("SignatureDataUri")));
13783
+ const dataUri = decodePdfObjAsString(metaDict.get(PDFName3.of("SignatureDataUri")));
12041
13784
  if (dataUri) return dataUri;
12042
- const signer = decodePdfObjAsString(metaDict.get(PDFName2.of("SignerName")));
13785
+ const signer = decodePdfObjAsString(metaDict.get(PDFName3.of("SignerName")));
12043
13786
  if (signer) return signer;
12044
13787
  }
12045
- const vDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName2.of("V")), PDFDict2);
13788
+ const vDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName3.of("V")), PDFDict3);
12046
13789
  if (vDict) {
12047
- const signerName = decodePdfObjAsString(vDict.get(PDFName2.of("Name")));
13790
+ const signerName = decodePdfObjAsString(vDict.get(PDFName3.of("Name")));
12048
13791
  if (signerName) return signerName;
12049
- if (vDict.get(PDFName2.of("Contents")) || vDict.get(PDFName2.of("Type"))) {
13792
+ if (vDict.get(PDFName3.of("Contents")) || vDict.get(PDFName3.of("Type"))) {
12050
13793
  return "signed";
12051
13794
  }
12052
13795
  }
12053
- const vStr = decodePdfObjAsString(fieldOrWidgetDict.get(PDFName2.of("V")));
13796
+ const vStr = decodePdfObjAsString(fieldOrWidgetDict.get(PDFName3.of("V")));
12054
13797
  return vStr || "";
12055
13798
  }
12056
13799
  async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12057
- const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
13800
+ const doc = await PDFDocument3.load(pdfBytes, { ignoreEncryption: true });
12058
13801
  const form = doc.getForm();
12059
13802
  const fields = form.getFields();
12060
13803
  const values = {};
@@ -12073,7 +13816,7 @@ async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12073
13816
  } else if (field instanceof PDFRadioGroup) {
12074
13817
  values[name] = field.getSelected() ?? "";
12075
13818
  } else {
12076
- const ft = decodePdfObjAsString(field.acroField.dict.get(PDFName2.of("FT")));
13819
+ const ft = decodePdfObjAsString(field.acroField.dict.get(PDFName3.of("FT")));
12077
13820
  if (ft === "Sig") {
12078
13821
  values[name] = extractSigDictValue(doc, field.acroField.dict);
12079
13822
  }
@@ -12083,17 +13826,17 @@ async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12083
13826
  const annots = page.node.Annots();
12084
13827
  if (!annots) continue;
12085
13828
  for (let i = 0; i < annots.size(); i++) {
12086
- const wDict = doc.context.lookupMaybe(annots.get(i), PDFDict2);
13829
+ const wDict = doc.context.lookupMaybe(annots.get(i), PDFDict3);
12087
13830
  if (!wDict) continue;
12088
- if (decodePdfObjAsString(wDict.get(PDFName2.of("Subtype"))) !== "Widget") continue;
12089
- const tName = decodePdfObjAsString(wDict.get(PDFName2.of("T")));
13831
+ if (decodePdfObjAsString(wDict.get(PDFName3.of("Subtype"))) !== "Widget") continue;
13832
+ const tName = decodePdfObjAsString(wDict.get(PDFName3.of("T")));
12090
13833
  if (!tName || Object.prototype.hasOwnProperty.call(values, tName)) continue;
12091
- const ft = decodePdfObjAsString(wDict.get(PDFName2.of("FT")));
13834
+ const ft = decodePdfObjAsString(wDict.get(PDFName3.of("FT")));
12092
13835
  if (ft === "Sig") {
12093
13836
  values[tName] = extractSigDictValue(doc, wDict);
12094
13837
  } else if (ft === "Ch") {
12095
- const vObj = wDict.get(PDFName2.of("V"));
12096
- const vArr = doc.context.lookupMaybe(vObj, PDFArray2);
13838
+ const vObj = wDict.get(PDFName3.of("V"));
13839
+ const vArr = doc.context.lookupMaybe(vObj, PDFArray3);
12097
13840
  if (vArr) {
12098
13841
  const items = [];
12099
13842
  for (let k = 0; k < vArr.size(); k++) {
@@ -12136,7 +13879,7 @@ function extractPdfFormValues(snapshot) {
12136
13879
  return out;
12137
13880
  }
12138
13881
  function fillPdfFormValues(snapshot, values) {
12139
- const next = Tools2.deepClone(snapshot);
13882
+ const next = Tools3.deepClone(snapshot);
12140
13883
  for (const pageId of next.document.pageOrder) {
12141
13884
  const map = next.editState.elementsByPage[pageId] ?? {};
12142
13885
  for (const el of Object.values(map)) {
@@ -12179,14 +13922,18 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12179
13922
  if (records.length === 1) {
12180
13923
  return exportPdfBytes(snapshot, records[0], options);
12181
13924
  }
12182
- const mergedPdf = await PDFDocument2.create();
13925
+ const mergedPdf = await PDFDocument3.create();
12183
13926
  let runningStartPage = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
12184
13927
  let runningBatesNumber = Math.max(0, Math.floor(snapshot.metadata?.batesConfig?.startNumber ?? 1));
13928
+ const effectiveSecurity = options?.security ?? snapshot.security ?? snapshot.metadata?.security;
13929
+ const recordOptions = isPdfSecurityActive(effectiveSecurity) ? { ...options ?? {}, security: { enabled: false } } : options;
12185
13930
  for (let i = 0; i < records.length; i++) {
12186
13931
  const recordSnap = {
12187
13932
  ...snapshot,
13933
+ ...isPdfSecurityActive(effectiveSecurity) ? { security: { enabled: false } } : {},
12188
13934
  metadata: {
12189
13935
  ...snapshot.metadata ?? {},
13936
+ ...isPdfSecurityActive(effectiveSecurity) ? { security: { enabled: false } } : {},
12190
13937
  startPageNumber: runningStartPage,
12191
13938
  ...snapshot.metadata?.batesConfig ? {
12192
13939
  batesConfig: {
@@ -12196,8 +13943,8 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12196
13943
  } : {}
12197
13944
  }
12198
13945
  };
12199
- const subBytes = await exportPdfBytes(recordSnap, records[i], options);
12200
- const subDoc = await PDFDocument2.load(subBytes);
13946
+ const subBytes = await exportPdfBytes(recordSnap, records[i], recordOptions);
13947
+ const subDoc = await PDFDocument3.load(subBytes);
12201
13948
  const copiedPages = await mergedPdf.copyPages(subDoc, subDoc.getPageIndices());
12202
13949
  for (const page of copiedPages) {
12203
13950
  mergedPdf.addPage(page);
@@ -12206,11 +13953,15 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12206
13953
  runningStartPage += subPageCount;
12207
13954
  runningBatesNumber += subPageCount;
12208
13955
  }
13956
+ if (isPdfSecurityActive(effectiveSecurity)) {
13957
+ await applyPdfSecurityToDocument(mergedPdf, effectiveSecurity);
13958
+ return await mergedPdf.save({ useObjectStreams: false });
13959
+ }
12209
13960
  return await mergedPdf.save();
12210
13961
  }
12211
13962
  async function exportCalibrationGridPdfBytes(pageSize) {
12212
13963
  const sz = pageSize ?? PDF_PAGE_PRESETS.A4;
12213
- const pdfDoc = await PDFDocument2.create();
13964
+ const pdfDoc = await PDFDocument3.create();
12214
13965
  const page = pdfDoc.addPage([sz.width, sz.height]);
12215
13966
  const fontRegular = await pdfDoc.embedFont(StandardFonts.Helvetica);
12216
13967
  const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
@@ -12377,7 +14128,7 @@ async function exportCalibrationGridPdfBytes(pageSize) {
12377
14128
  return await pdfDoc.save();
12378
14129
  }
12379
14130
  async function overlayDiagnosticGridOnPdfBytes(pdfBytes, snapshot, options) {
12380
- const pdfDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
14131
+ const pdfDoc = await PDFDocument3.load(pdfBytes, { ignoreEncryption: true });
12381
14132
  const pages = pdfDoc.getPages();
12382
14133
  if (pages.length === 0) {
12383
14134
  return await pdfDoc.save({ updateFieldAppearances: false });
@@ -16170,6 +17921,7 @@ export {
16170
17921
  PdfTableCellVerticalAlign,
16171
17922
  PDF_TABLE_THEME_PRESETS,
16172
17923
  PDF_PAGE_PRESETS,
17924
+ resolvePdfCropBoxPt,
16173
17925
  PdfElementType,
16174
17926
  PdfImageSourceType,
16175
17927
  PdfTableBorderStyle,
@@ -16211,6 +17963,13 @@ export {
16211
17963
  fromPdfmeTemplate,
16212
17964
  exportToPdfmeTemplate,
16213
17965
  importFromPdfmeTemplate,
17966
+ PDF_STANDARD_STAMP_PRESETS,
17967
+ PDF_STANDARD_STAMP_PRESET_MAP,
17968
+ getPdfStandardStampPreset,
17969
+ buildPdfApprovalStampSvg,
17970
+ extractSvgTextDescriptors,
17971
+ createPdfApprovalStampSvgElement,
17972
+ createPdfApprovalStampElement,
16214
17973
  svgToDataUri,
16215
17974
  parseGs1ApplicationIdentifiers,
16216
17975
  formatGs1HumanReadable,
@@ -16245,6 +18004,25 @@ export {
16245
18004
  encodeBarcodeByFormat,
16246
18005
  renderBarcodeSvgByFormat,
16247
18006
  renderBarcodeSvgDataUrlByFormat,
18007
+ PdfSecurityError,
18008
+ PDF_PASSWORD_PADDING,
18009
+ md5Bytes,
18010
+ rc4Bytes,
18011
+ bytesToHex,
18012
+ hexToBytes,
18013
+ padPdfPassword,
18014
+ encodePdfPermissionFlags,
18015
+ decodePdfPermissionFlags,
18016
+ isPdfSecurityActive,
18017
+ computeOwnerPasswordValue,
18018
+ computeFileEncryptionKeyFromPadded,
18019
+ computeUserPasswordValue,
18020
+ buildObjectEncryptionKey,
18021
+ applyPdfSecurityToDocument,
18022
+ encryptPdfBytes,
18023
+ inspectPdfEncryption,
18024
+ decryptPdfBytes,
18025
+ verifyAndDecryptPdfBytes,
16248
18026
  parsePdfContentStreamTextOps,
16249
18027
  extractNativeTextSpansFromPdfBytes,
16250
18028
  rectsIntersect,
@@ -16257,6 +18035,10 @@ export {
16257
18035
  rotatePdfPagesBytes,
16258
18036
  movePdfPageBytes,
16259
18037
  organizePdfBytes,
18038
+ formatPdfPageIndicesLabel,
18039
+ parsePdfPageRangeSpec,
18040
+ splitPdfUnitByRanges,
18041
+ splitPdfBytesByRanges,
16260
18042
  parseObjectPositionRatios,
16261
18043
  computeImageFitPlacement,
16262
18044
  computeElementCenterTransformMatrix,
@@ -16287,6 +18069,7 @@ export {
16287
18069
  paginatePdfTableRows,
16288
18070
  formatBatesNumber,
16289
18071
  exportPdfBytes,
18072
+ exportPdfUnitToBytes,
16290
18073
  extractAcroFormValuesFromPdfBytes,
16291
18074
  extractPdfFormValues,
16292
18075
  fillPdfFormValues,
@@ -16337,4 +18120,4 @@ export {
16337
18120
  renderJsxToPdfmeTemplate,
16338
18121
  exportJsxToPdfBytes
16339
18122
  };
16340
- //# sourceMappingURL=chunk-EMSHTYYU.js.map
18123
+ //# sourceMappingURL=chunk-PQUNQAVL.js.map