@yudaocode/univer-pdfs 1.6.218 → 1.6.219
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/lib/cjs/index.js +4761 -2984
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/jsx/index.js +1871 -1609
- package/lib/cjs/jsx/index.js.map +1 -1
- package/lib/es/{chunk-SUXA7HBV.js → chunk-PQUNQAVL.js} +2655 -1951
- package/lib/es/chunk-PQUNQAVL.js.map +1 -0
- package/lib/es/index.js +1508 -430
- package/lib/es/index.js.map +1 -1
- package/lib/es/jsx/index.js +1 -1
- package/lib/types/index.d.ts +154 -4
- package/lib/types/jsx/index.d.ts +2 -2
- package/lib/types/jsx/jsx-dev-runtime.d.ts +1 -1
- package/lib/types/jsx/jsx-runtime.d.ts +1 -1
- package/lib/types/{jsx-dev-runtime-DsfnOIFS.d.ts → jsx-dev-runtime-B1jMa7VW.d.ts} +51 -4
- package/package.json +1 -1
- package/lib/es/chunk-SUXA7HBV.js.map +0 -1
|
@@ -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";
|
|
@@ -3215,7 +3231,7 @@ var exportToPdfmeTemplate = toPdfmeTemplate;
|
|
|
3215
3231
|
var importFromPdfmeTemplate = fromPdfmeTemplate;
|
|
3216
3232
|
|
|
3217
3233
|
// src/exporter/pdf-exporter.ts
|
|
3218
|
-
import { Tools as
|
|
3234
|
+
import { Tools as Tools3 } from "@univerjs/core";
|
|
3219
3235
|
import {
|
|
3220
3236
|
appendBezierCurve,
|
|
3221
3237
|
beginText,
|
|
@@ -3264,6 +3280,281 @@ import {
|
|
|
3264
3280
|
} from "pdf-lib";
|
|
3265
3281
|
import QRCode2 from "qrcode";
|
|
3266
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/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
|
+
|
|
3267
3558
|
// src/exporter/pdf-2d-barcodes.ts
|
|
3268
3559
|
function encodeBase64Utf8(str) {
|
|
3269
3560
|
const bytes = new TextEncoder().encode(str);
|
|
@@ -4904,2082 +5195,2378 @@ function renderBarcodeSvgDataUrlByFormat(format, raw, options) {
|
|
|
4904
5195
|
}
|
|
4905
5196
|
|
|
4906
5197
|
// src/exporter/pdf-native-text.ts
|
|
5198
|
+
import { generateRandomId as generateRandomId3, Tools as Tools2 } from "@univerjs/core";
|
|
4907
5199
|
import {
|
|
4908
5200
|
decodePDFRawStream,
|
|
4909
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 {
|
|
4910
5214
|
PDFArray,
|
|
4911
5215
|
PDFDict,
|
|
4912
5216
|
PDFDocument,
|
|
5217
|
+
PDFHexString,
|
|
4913
5218
|
PDFName,
|
|
4914
5219
|
PDFNumber,
|
|
4915
5220
|
PDFRawStream,
|
|
4916
5221
|
PDFRef,
|
|
4917
|
-
PDFStream
|
|
5222
|
+
PDFStream,
|
|
5223
|
+
PDFString
|
|
4918
5224
|
} from "pdf-lib";
|
|
4919
|
-
var
|
|
4920
|
-
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
133: 8230,
|
|
4925
|
-
134: 8224,
|
|
4926
|
-
135: 8225,
|
|
4927
|
-
136: 710,
|
|
4928
|
-
137: 8240,
|
|
4929
|
-
138: 352,
|
|
4930
|
-
139: 8249,
|
|
4931
|
-
140: 338,
|
|
4932
|
-
142: 381,
|
|
4933
|
-
145: 8216,
|
|
4934
|
-
146: 8217,
|
|
4935
|
-
147: 8220,
|
|
4936
|
-
148: 8221,
|
|
4937
|
-
149: 8226,
|
|
4938
|
-
150: 8211,
|
|
4939
|
-
151: 8212,
|
|
4940
|
-
152: 732,
|
|
4941
|
-
153: 8482,
|
|
4942
|
-
154: 353,
|
|
4943
|
-
155: 8250,
|
|
4944
|
-
156: 339,
|
|
4945
|
-
158: 382,
|
|
4946
|
-
159: 376
|
|
4947
|
-
};
|
|
4948
|
-
function multiplyPdfMatrix(m1, m2) {
|
|
4949
|
-
return [
|
|
4950
|
-
m1[0] * m2[0] + m1[1] * m2[2],
|
|
4951
|
-
m1[0] * m2[1] + m1[1] * m2[3],
|
|
4952
|
-
m1[2] * m2[0] + m1[3] * m2[2],
|
|
4953
|
-
m1[2] * m2[1] + m1[3] * m2[3],
|
|
4954
|
-
m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
|
|
4955
|
-
m1[4] * m2[1] + m1[5] * m2[3] + m2[5]
|
|
4956
|
-
];
|
|
4957
|
-
}
|
|
4958
|
-
function decodeSingleStreamObject(doc, objOrRef) {
|
|
4959
|
-
const resolved = objOrRef instanceof PDFRef ? doc.context.lookup(objOrRef) : objOrRef;
|
|
4960
|
-
if (!resolved) return new Uint8Array(0);
|
|
4961
|
-
if (resolved instanceof PDFRawStream) {
|
|
4962
|
-
try {
|
|
4963
|
-
const decoded = decodePDFRawStream(resolved).decode();
|
|
4964
|
-
return decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded);
|
|
4965
|
-
} catch {
|
|
4966
|
-
return resolved.contents;
|
|
4967
|
-
}
|
|
5225
|
+
var PdfSecurityError = class extends Error {
|
|
5226
|
+
constructor(code, message) {
|
|
5227
|
+
super(message);
|
|
5228
|
+
this.name = "PdfSecurityError";
|
|
5229
|
+
this.code = code;
|
|
4968
5230
|
}
|
|
4969
|
-
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
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;
|
|
4977
5345
|
}
|
|
4978
|
-
return
|
|
5346
|
+
return table;
|
|
5347
|
+
})();
|
|
5348
|
+
function rotl32(x, n) {
|
|
5349
|
+
return (x << n | x >>> 32 - n) >>> 0;
|
|
4979
5350
|
}
|
|
4980
|
-
function
|
|
4981
|
-
const
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
|
|
4985
|
-
|
|
4986
|
-
|
|
4987
|
-
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
|
|
4998
|
-
|
|
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);
|
|
4999
5372
|
}
|
|
5000
|
-
|
|
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;
|
|
5001
5403
|
}
|
|
5002
|
-
|
|
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;
|
|
5003
5411
|
}
|
|
5004
|
-
function
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
|
|
5008
|
-
|
|
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];
|
|
5009
5436
|
}
|
|
5010
5437
|
return out;
|
|
5011
5438
|
}
|
|
5012
|
-
function
|
|
5013
|
-
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
return String.fromCodePoint(parseInt(cleaned, 16) || 32);
|
|
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();
|
|
5017
5443
|
}
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
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;
|
|
5021
5452
|
}
|
|
5022
|
-
return
|
|
5453
|
+
return out;
|
|
5023
5454
|
}
|
|
5024
|
-
function
|
|
5025
|
-
|
|
5026
|
-
let
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
const pairRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
|
|
5032
|
-
let m;
|
|
5033
|
-
while ((m = pairRe.exec(body)) !== null) {
|
|
5034
|
-
if (m[1].length >= 4) bytesPerCode = 2;
|
|
5035
|
-
const srcCode = parseInt(m[1], 16);
|
|
5036
|
-
const dstStr = decodeUtf16BeHex(m[2]);
|
|
5037
|
-
if (!Number.isNaN(srcCode) && dstStr) {
|
|
5038
|
-
map.set(srcCode, dstStr);
|
|
5039
|
-
}
|
|
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;
|
|
5040
5462
|
}
|
|
5041
5463
|
}
|
|
5042
|
-
|
|
5043
|
-
|
|
5044
|
-
const body = blockMatch[1];
|
|
5045
|
-
const arrayRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([^\]]*)\]/g;
|
|
5046
|
-
let am;
|
|
5047
|
-
while ((am = arrayRangeRe.exec(body)) !== null) {
|
|
5048
|
-
if (am[1].length >= 4) bytesPerCode = 2;
|
|
5049
|
-
const start = parseInt(am[1], 16);
|
|
5050
|
-
const end = parseInt(am[2], 16);
|
|
5051
|
-
const targets = Array.from(am[3].matchAll(/<([0-9A-Fa-f]+)>/g)).map((x) => decodeUtf16BeHex(x[1]));
|
|
5052
|
-
for (let code = start; code <= end && code - start < targets.length; code++) {
|
|
5053
|
-
if (targets[code - start]) {
|
|
5054
|
-
map.set(code, targets[code - start]);
|
|
5055
|
-
}
|
|
5056
|
-
}
|
|
5057
|
-
}
|
|
5058
|
-
const directRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
|
|
5059
|
-
let dm;
|
|
5060
|
-
while ((dm = directRangeRe.exec(body)) !== null) {
|
|
5061
|
-
if (dm[1].length >= 4) bytesPerCode = 2;
|
|
5062
|
-
const start = parseInt(dm[1], 16);
|
|
5063
|
-
const end = parseInt(dm[2], 16);
|
|
5064
|
-
const baseStr = decodeUtf16BeHex(dm[3]);
|
|
5065
|
-
const baseCp = baseStr.codePointAt(0) ?? 32;
|
|
5066
|
-
if (end >= start && end - start <= 16384) {
|
|
5067
|
-
for (let code = start; code <= end; code++) {
|
|
5068
|
-
map.set(code, String.fromCodePoint(baseCp + (code - start)));
|
|
5069
|
-
}
|
|
5070
|
-
}
|
|
5071
|
-
}
|
|
5464
|
+
if (hasHighCodePoint) {
|
|
5465
|
+
return new TextEncoder().encode(password);
|
|
5072
5466
|
}
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
const fonts = /* @__PURE__ */ new Map();
|
|
5077
|
-
if (!resourcesDict) return fonts;
|
|
5078
|
-
const fontObj = resourcesDict.get(PDFName.of("Font"));
|
|
5079
|
-
const fontDict = doc.context.lookupMaybe(fontObj, PDFDict);
|
|
5080
|
-
if (!fontDict) return fonts;
|
|
5081
|
-
for (const [keyObj, valObj] of fontDict.entries()) {
|
|
5082
|
-
const cleanKey = keyObj.decodeText ? keyObj.decodeText() : keyObj.asString().replace(/^\//, "");
|
|
5083
|
-
const fDict = doc.context.lookupMaybe(valObj, PDFDict);
|
|
5084
|
-
if (!fDict) continue;
|
|
5085
|
-
const subtypeObj = fDict.get(PDFName.of("Subtype"));
|
|
5086
|
-
const subtype = subtypeObj instanceof PDFName ? subtypeObj.decodeText() : "";
|
|
5087
|
-
const encObj = fDict.get(PDFName.of("Encoding"));
|
|
5088
|
-
const encoding = encObj instanceof PDFName ? encObj.decodeText() : "";
|
|
5089
|
-
const isUtf16Cid = /UTF16|UCS2/i.test(encoding);
|
|
5090
|
-
let toUnicode = /* @__PURE__ */ new Map();
|
|
5091
|
-
let bytesPerCode = subtype === "Type0" ? 2 : 1;
|
|
5092
|
-
const toUniEntry = fDict.get(PDFName.of("ToUnicode"));
|
|
5093
|
-
if (toUniEntry) {
|
|
5094
|
-
const cmapBytes = decodeSingleStreamObject(doc, toUniEntry);
|
|
5095
|
-
if (cmapBytes.byteLength > 0) {
|
|
5096
|
-
const parsed = parseToUnicodeCMap(bytesToLatin1String(cmapBytes));
|
|
5097
|
-
toUnicode = parsed.map;
|
|
5098
|
-
if (parsed.bytesPerCode === 2 || subtype === "Type0") {
|
|
5099
|
-
bytesPerCode = 2;
|
|
5100
|
-
}
|
|
5101
|
-
}
|
|
5102
|
-
}
|
|
5103
|
-
fonts.set(cleanKey, {
|
|
5104
|
-
subtype,
|
|
5105
|
-
encoding,
|
|
5106
|
-
isUtf16Cid,
|
|
5107
|
-
bytesPerCode,
|
|
5108
|
-
toUnicode
|
|
5109
|
-
});
|
|
5467
|
+
const out = new Uint8Array(password.length);
|
|
5468
|
+
for (let i = 0; i < password.length; i++) {
|
|
5469
|
+
out[i] = password.charCodeAt(i) & 255;
|
|
5110
5470
|
}
|
|
5111
|
-
return
|
|
5471
|
+
return out;
|
|
5112
5472
|
}
|
|
5113
|
-
function
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
out += String.fromCharCode(b);
|
|
5121
|
-
}
|
|
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);
|
|
5122
5480
|
}
|
|
5123
5481
|
return out;
|
|
5124
5482
|
}
|
|
5125
|
-
function
|
|
5126
|
-
const
|
|
5127
|
-
|
|
5128
|
-
|
|
5129
|
-
|
|
5130
|
-
|
|
5131
|
-
|
|
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;
|
|
5132
5502
|
}
|
|
5133
|
-
return
|
|
5503
|
+
return mask | 0;
|
|
5134
5504
|
}
|
|
5135
|
-
function
|
|
5136
|
-
|
|
5137
|
-
|
|
5138
|
-
|
|
5139
|
-
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
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);
|
|
5156
5538
|
}
|
|
5157
|
-
|
|
5158
|
-
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
out += String.fromCharCode(code);
|
|
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;
|
|
5167
5548
|
}
|
|
5549
|
+
encrypted = rc4Bytes(derivedKey, encrypted);
|
|
5168
5550
|
}
|
|
5169
|
-
return { text: out, glyphCount: bytes.length };
|
|
5170
|
-
}
|
|
5171
|
-
if (fontInfo?.isUtf16Cid || fontInfo?.subtype === "Type0" && bytes.length % 2 === 0) {
|
|
5172
|
-
const text2 = decodeUtf16BeBytes(bytes, 0);
|
|
5173
|
-
return { text: text2, glyphCount: Math.floor(bytes.length / 2) };
|
|
5174
5551
|
}
|
|
5175
|
-
|
|
5176
|
-
return { text, glyphCount: bytes.length };
|
|
5552
|
+
return encrypted;
|
|
5177
5553
|
}
|
|
5178
|
-
function
|
|
5179
|
-
|
|
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);
|
|
5180
5574
|
}
|
|
5181
|
-
function
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5190
|
-
|
|
5191
|
-
|
|
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;
|
|
5192
5595
|
}
|
|
5193
|
-
function
|
|
5194
|
-
|
|
5195
|
-
|
|
5196
|
-
|
|
5197
|
-
|
|
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;
|
|
5198
5613
|
}
|
|
5199
|
-
function
|
|
5200
|
-
const
|
|
5201
|
-
let
|
|
5202
|
-
|
|
5203
|
-
|
|
5204
|
-
|
|
5205
|
-
|
|
5206
|
-
|
|
5207
|
-
|
|
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;
|
|
5208
5630
|
}
|
|
5209
|
-
|
|
5210
|
-
|
|
5211
|
-
|
|
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;
|
|
5212
5690
|
}
|
|
5213
|
-
continue;
|
|
5214
5691
|
}
|
|
5215
|
-
|
|
5692
|
+
bytes.push(parseInt(oct, 8) & 255);
|
|
5693
|
+
} else {
|
|
5694
|
+
bytes.push(next);
|
|
5216
5695
|
}
|
|
5217
|
-
|
|
5218
|
-
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
5232
|
-
|
|
5233
|
-
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
} else if (b === 40) {
|
|
5248
|
-
depth++;
|
|
5249
|
-
out.push(b);
|
|
5250
|
-
} else if (b === 41) {
|
|
5251
|
-
depth--;
|
|
5252
|
-
if (depth > 0) out.push(b);
|
|
5253
|
-
} else {
|
|
5254
|
-
out.push(b);
|
|
5255
|
-
}
|
|
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);
|
|
5256
5726
|
}
|
|
5257
|
-
return { type: "literal", bytes: new Uint8Array(out), start, end: pos };
|
|
5258
5727
|
}
|
|
5259
|
-
|
|
5260
|
-
|
|
5261
|
-
|
|
5262
|
-
|
|
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;
|
|
5263
5735
|
}
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
const hv = hexCharVal(bytes[pos++]);
|
|
5268
|
-
if (hv >= 0) nibbles.push(hv);
|
|
5736
|
+
const next = transformPdfObjectStringsWithRc4(val, objKey);
|
|
5737
|
+
if (next !== val) {
|
|
5738
|
+
obj.set(key, next);
|
|
5269
5739
|
}
|
|
5270
|
-
|
|
5271
|
-
|
|
5272
|
-
|
|
5273
|
-
|
|
5274
|
-
|
|
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
|
+
}
|
|
5275
5761
|
}
|
|
5276
|
-
return { type: "hex", bytes: hexBytes, start, end: pos };
|
|
5277
5762
|
}
|
|
5278
|
-
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
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);
|
|
5282
5821
|
}
|
|
5283
|
-
pos++;
|
|
5284
|
-
return { type: "op", op: ">", start, end: pos };
|
|
5285
5822
|
}
|
|
5286
|
-
|
|
5287
|
-
|
|
5288
|
-
|
|
5289
|
-
|
|
5290
|
-
|
|
5291
|
-
|
|
5292
|
-
|
|
5293
|
-
|
|
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;
|
|
5294
5871
|
}
|
|
5295
|
-
const child = readToken();
|
|
5296
|
-
if (!child) break;
|
|
5297
|
-
items.push(child);
|
|
5298
5872
|
}
|
|
5299
|
-
|
|
5873
|
+
continue;
|
|
5300
5874
|
}
|
|
5301
|
-
if (ch ===
|
|
5302
|
-
|
|
5303
|
-
|
|
5875
|
+
if (ch === 40) {
|
|
5876
|
+
inLiteral = true;
|
|
5877
|
+
literalDepth = 1;
|
|
5878
|
+
continue;
|
|
5304
5879
|
}
|
|
5305
|
-
if (ch ===
|
|
5306
|
-
|
|
5307
|
-
|
|
5308
|
-
while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
|
|
5309
|
-
if (bytes[pos] === 35 && pos + 2 < len) {
|
|
5310
|
-
const h1 = hexCharVal(bytes[pos + 1]);
|
|
5311
|
-
const h2 = hexCharVal(bytes[pos + 2]);
|
|
5312
|
-
if (h1 >= 0 && h2 >= 0) {
|
|
5313
|
-
name += String.fromCharCode(h1 << 4 | h2);
|
|
5314
|
-
pos += 3;
|
|
5315
|
-
continue;
|
|
5316
|
-
}
|
|
5317
|
-
}
|
|
5318
|
-
name += String.fromCharCode(bytes[pos++]);
|
|
5880
|
+
if (ch === 37) {
|
|
5881
|
+
while (i < text.length && text.charCodeAt(i) !== 10 && text.charCodeAt(i) !== 13) {
|
|
5882
|
+
i++;
|
|
5319
5883
|
}
|
|
5320
|
-
|
|
5884
|
+
continue;
|
|
5321
5885
|
}
|
|
5322
|
-
|
|
5323
|
-
|
|
5324
|
-
|
|
5886
|
+
if (ch === 60 && text.charCodeAt(i + 1) === 60) {
|
|
5887
|
+
depth++;
|
|
5888
|
+
i++;
|
|
5889
|
+
continue;
|
|
5325
5890
|
}
|
|
5326
|
-
if (
|
|
5327
|
-
|
|
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
|
+
}
|
|
5328
5897
|
}
|
|
5329
|
-
if (word === "ID") {
|
|
5330
|
-
if (pos < len && isPdfWhitespace(bytes[pos])) pos++;
|
|
5331
|
-
while (pos + 1 < len) {
|
|
5332
|
-
if (bytes[pos] === 69 && bytes[pos + 1] === 73 && (pos === 0 || isPdfWhitespace(bytes[pos - 1])) && (pos + 2 >= len || isPdfWhitespace(bytes[pos + 2]) || isPdfDelimiter(bytes[pos + 2]))) {
|
|
5333
|
-
pos += 2;
|
|
5334
|
-
return { type: "op", op: "EI", start, end: pos };
|
|
5335
|
-
}
|
|
5336
|
-
pos++;
|
|
5337
|
-
}
|
|
5338
|
-
}
|
|
5339
|
-
return { type: "op", op: word, start, end: pos };
|
|
5340
|
-
};
|
|
5341
|
-
const tokens = [];
|
|
5342
|
-
let tok;
|
|
5343
|
-
while ((tok = readToken()) !== null) {
|
|
5344
|
-
tokens.push(tok);
|
|
5345
5898
|
}
|
|
5346
|
-
return
|
|
5899
|
+
return null;
|
|
5347
5900
|
}
|
|
5348
|
-
function
|
|
5349
|
-
const
|
|
5350
|
-
const
|
|
5351
|
-
|
|
5352
|
-
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
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));
|
|
5356
5912
|
}
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
charSpacing: 0,
|
|
5370
|
-
wordSpacing: 0,
|
|
5371
|
-
horizScaling: 100,
|
|
5372
|
-
leading: 0,
|
|
5373
|
-
textRise: 0
|
|
5374
|
-
};
|
|
5375
|
-
let textMatrix = [1, 0, 0, 1, 0, 0];
|
|
5376
|
-
let textLineMatrix = [1, 0, 0, 1, 0, 0];
|
|
5377
|
-
const operands = [];
|
|
5378
|
-
const emitTextSpan = (rawText, textSpaceAdvance, opStart, opEnd) => {
|
|
5379
|
-
const trimmed = rawText.replace(/\0/g, "");
|
|
5380
|
-
if (!trimmed.trim()) {
|
|
5381
|
-
textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
|
|
5382
|
-
return;
|
|
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++;
|
|
5383
5925
|
}
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
const by = combined[5] + state.textRise;
|
|
5387
|
-
const scaleX = Math.hypot(combined[0], combined[1]) || 1;
|
|
5388
|
-
const scaleY = Math.hypot(combined[2], combined[3]) || 1;
|
|
5389
|
-
const effectiveFontSize = Math.round(Math.max(1, (Math.abs(state.fontSize) || 12) * scaleY) * 100) / 100;
|
|
5390
|
-
const widthPt = Math.max(4, Math.abs(textSpaceAdvance * scaleX));
|
|
5391
|
-
const heightPt = Math.max(8, effectiveFontSize * 1.2);
|
|
5392
|
-
const left = Math.round((bx - mediaBox.x) * 100) / 100;
|
|
5393
|
-
const top = Math.round(Math.max(0, mediaBox.height - (by - mediaBox.y) - effectiveFontSize * 0.85) * 100) / 100;
|
|
5394
|
-
results.push({
|
|
5395
|
-
text: trimmed,
|
|
5396
|
-
left,
|
|
5397
|
-
top,
|
|
5398
|
-
width: Math.round(widthPt * 100) / 100,
|
|
5399
|
-
height: Math.round(heightPt * 100) / 100,
|
|
5400
|
-
fontSize: effectiveFontSize,
|
|
5401
|
-
...isTopLevelStream ? { streamStartOffset: opStart, streamEndOffset: opEnd } : {}
|
|
5402
|
-
});
|
|
5403
|
-
textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
|
|
5404
|
-
};
|
|
5405
|
-
for (const tok of tokens) {
|
|
5406
|
-
if (tok.type !== "op") {
|
|
5407
|
-
operands.push(tok);
|
|
5408
|
-
continue;
|
|
5926
|
+
if (depth === 0) {
|
|
5927
|
+
return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
|
|
5409
5928
|
}
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5423
|
-
|
|
5424
|
-
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
case "BT": {
|
|
5432
|
-
textMatrix = [1, 0, 0, 1, 0, 0];
|
|
5433
|
-
textLineMatrix = [1, 0, 0, 1, 0, 0];
|
|
5434
|
-
break;
|
|
5435
|
-
}
|
|
5436
|
-
case "ET": {
|
|
5437
|
-
break;
|
|
5438
|
-
}
|
|
5439
|
-
case "Tf": {
|
|
5440
|
-
if (operands.length >= 2) {
|
|
5441
|
-
const nameTok = operands[operands.length - 2];
|
|
5442
|
-
const sizeTok = operands[operands.length - 1];
|
|
5443
|
-
if (nameTok.type === "name") state.fontName = nameTok.value;
|
|
5444
|
-
if (sizeTok.type === "number") state.fontSize = sizeTok.num;
|
|
5445
|
-
}
|
|
5446
|
-
break;
|
|
5447
|
-
}
|
|
5448
|
-
case "Tc": {
|
|
5449
|
-
const last = operands[operands.length - 1];
|
|
5450
|
-
if (last?.type === "number") state.charSpacing = last.num;
|
|
5451
|
-
break;
|
|
5452
|
-
}
|
|
5453
|
-
case "Tw": {
|
|
5454
|
-
const last = operands[operands.length - 1];
|
|
5455
|
-
if (last?.type === "number") state.wordSpacing = last.num;
|
|
5456
|
-
break;
|
|
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;
|
|
5457
5950
|
}
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
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;
|
|
5461
5975
|
break;
|
|
5462
5976
|
}
|
|
5463
|
-
|
|
5464
|
-
|
|
5465
|
-
if (last?.type === "number") state.leading = last.num;
|
|
5466
|
-
break;
|
|
5977
|
+
if (candidate && !containerDict) {
|
|
5978
|
+
containerDict = candidate;
|
|
5467
5979
|
}
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
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");
|
|
5472
6031
|
}
|
|
5473
|
-
case "Td":
|
|
5474
|
-
case "TD": {
|
|
5475
|
-
if (operands.length >= 2) {
|
|
5476
|
-
const txTok = operands[operands.length - 2];
|
|
5477
|
-
const tyTok = operands[operands.length - 1];
|
|
5478
|
-
const tx = txTok.type === "number" ? txTok.num : 0;
|
|
5479
|
-
const ty = tyTok.type === "number" ? tyTok.num : 0;
|
|
5480
|
-
if (op === "TD") state.leading = -ty;
|
|
5481
|
-
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, tx, ty], textLineMatrix);
|
|
5482
|
-
textMatrix = [...textLineMatrix];
|
|
5483
|
-
}
|
|
5484
|
-
break;
|
|
5485
|
-
}
|
|
5486
|
-
case "Tm": {
|
|
5487
|
-
if (operands.length >= 6) {
|
|
5488
|
-
const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
|
|
5489
|
-
textMatrix = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
|
|
5490
|
-
textLineMatrix = [...textMatrix];
|
|
5491
|
-
}
|
|
5492
|
-
break;
|
|
5493
|
-
}
|
|
5494
|
-
case "T*": {
|
|
5495
|
-
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
|
|
5496
|
-
textMatrix = [...textLineMatrix];
|
|
5497
|
-
break;
|
|
5498
|
-
}
|
|
5499
|
-
case "Tj":
|
|
5500
|
-
case "'":
|
|
5501
|
-
case '"': {
|
|
5502
|
-
if (op === "'" || op === '"') {
|
|
5503
|
-
if (op === '"' && operands.length >= 3) {
|
|
5504
|
-
const twTok = operands[operands.length - 3];
|
|
5505
|
-
const tcTok = operands[operands.length - 2];
|
|
5506
|
-
if (twTok.type === "number") state.wordSpacing = twTok.num;
|
|
5507
|
-
if (tcTok.type === "number") state.charSpacing = tcTok.num;
|
|
5508
|
-
}
|
|
5509
|
-
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
|
|
5510
|
-
textMatrix = [...textLineMatrix];
|
|
5511
|
-
}
|
|
5512
|
-
const strTok = operands[operands.length - 1];
|
|
5513
|
-
if (strTok && (strTok.type === "literal" || strTok.type === "hex")) {
|
|
5514
|
-
const fontInfo = fonts.get(state.fontName);
|
|
5515
|
-
const { text } = decodePdfStringBytes(strTok.bytes, fontInfo);
|
|
5516
|
-
const adv = estimateTextAdvanceInTextSpace(text, state);
|
|
5517
|
-
emitTextSpan(text, adv, opStart, opEnd);
|
|
5518
|
-
}
|
|
5519
|
-
break;
|
|
5520
|
-
}
|
|
5521
|
-
case "TJ": {
|
|
5522
|
-
const arrTok = operands[operands.length - 1];
|
|
5523
|
-
if (arrTok?.type === "array") {
|
|
5524
|
-
const fontInfo = fonts.get(state.fontName);
|
|
5525
|
-
const fs = Math.abs(state.fontSize) || 12;
|
|
5526
|
-
const scaleH = state.horizScaling / 100;
|
|
5527
|
-
let joined = "";
|
|
5528
|
-
let totalAdv = 0;
|
|
5529
|
-
for (const item of arrTok.items) {
|
|
5530
|
-
if (item.type === "literal" || item.type === "hex") {
|
|
5531
|
-
const { text } = decodePdfStringBytes(item.bytes, fontInfo);
|
|
5532
|
-
joined += text;
|
|
5533
|
-
totalAdv += estimateTextAdvanceInTextSpace(text, state);
|
|
5534
|
-
} else if (item.type === "number") {
|
|
5535
|
-
const shift = -item.num / 1e3 * fs * scaleH;
|
|
5536
|
-
totalAdv += shift;
|
|
5537
|
-
if (item.num < -180 && joined.length > 0 && !joined.endsWith(" ")) {
|
|
5538
|
-
joined += " ";
|
|
5539
|
-
}
|
|
5540
|
-
}
|
|
5541
|
-
}
|
|
5542
|
-
emitTextSpan(joined, totalAdv, opStart, opEnd);
|
|
5543
|
-
}
|
|
5544
|
-
break;
|
|
5545
|
-
}
|
|
5546
|
-
case "Do": {
|
|
5547
|
-
const nameTok = operands[operands.length - 1];
|
|
5548
|
-
if (nameTok?.type === "name" && resourcesDict) {
|
|
5549
|
-
const xObjEntry = resourcesDict.get(PDFName.of("XObject"));
|
|
5550
|
-
const xObjDict = doc.context.lookupMaybe(xObjEntry, PDFDict);
|
|
5551
|
-
const targetObj = xObjDict?.get(PDFName.of(nameTok.value));
|
|
5552
|
-
const resolvedXObj = targetObj instanceof PDFRef ? doc.context.lookup(targetObj) : targetObj;
|
|
5553
|
-
if (resolvedXObj instanceof PDFRawStream) {
|
|
5554
|
-
const subType = resolvedXObj.dict.get(PDFName.of("Subtype"));
|
|
5555
|
-
if (subType instanceof PDFName && subType.decodeText() === "Form") {
|
|
5556
|
-
const formBytes = decodeSingleStreamObject(doc, resolvedXObj);
|
|
5557
|
-
const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName.of("Resources")), PDFDict) ?? resourcesDict;
|
|
5558
|
-
let formMat = [...state.ctm];
|
|
5559
|
-
const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName.of("Matrix")), PDFArray);
|
|
5560
|
-
if (matArr && matArr.size() >= 6) {
|
|
5561
|
-
const nums = [];
|
|
5562
|
-
for (let k = 0; k < 6; k++) {
|
|
5563
|
-
const nObj = matArr.get(k);
|
|
5564
|
-
nums.push(nObj instanceof PDFNumber ? nObj.asNumber() : 0);
|
|
5565
|
-
}
|
|
5566
|
-
formMat = multiplyPdfMatrix(
|
|
5567
|
-
[nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]],
|
|
5568
|
-
state.ctm
|
|
5569
|
-
);
|
|
5570
|
-
}
|
|
5571
|
-
const subSpans = parsePdfContentStreamTextOps(
|
|
5572
|
-
doc,
|
|
5573
|
-
formBytes,
|
|
5574
|
-
formRes,
|
|
5575
|
-
mediaBox,
|
|
5576
|
-
formMat,
|
|
5577
|
-
false,
|
|
5578
|
-
depth + 1
|
|
5579
|
-
);
|
|
5580
|
-
results.push(...subSpans);
|
|
5581
|
-
}
|
|
5582
|
-
}
|
|
5583
|
-
}
|
|
5584
|
-
break;
|
|
5585
|
-
}
|
|
5586
|
-
default:
|
|
5587
|
-
break;
|
|
5588
6032
|
}
|
|
5589
|
-
operands.length = 0;
|
|
5590
6033
|
}
|
|
5591
|
-
return
|
|
6034
|
+
return {
|
|
6035
|
+
filter,
|
|
6036
|
+
version,
|
|
6037
|
+
revision,
|
|
6038
|
+
keyLength,
|
|
6039
|
+
pSigned,
|
|
6040
|
+
oBytes,
|
|
6041
|
+
uBytes,
|
|
6042
|
+
fileId: fileId ?? new Uint8Array(0)
|
|
6043
|
+
};
|
|
5592
6044
|
}
|
|
5593
|
-
|
|
5594
|
-
const
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5599
|
-
|
|
5600
|
-
|
|
5601
|
-
|
|
5602
|
-
|
|
5603
|
-
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
|
|
5609
|
-
|
|
5610
|
-
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
const content = await page.getTextContent();
|
|
5620
|
-
const spans = [];
|
|
5621
|
-
let idx = 0;
|
|
5622
|
-
for (const item of content.items ?? []) {
|
|
5623
|
-
const str = typeof item.str === "string" ? item.str : "";
|
|
5624
|
-
if (!str.trim() || !Array.isArray(item.transform)) continue;
|
|
5625
|
-
const tr = item.transform;
|
|
5626
|
-
const fontSize = Math.round((Math.hypot(tr[2] ?? 0, tr[3] ?? 12) || 12) * 100) / 100;
|
|
5627
|
-
const width = Math.round(Math.max(4, Number(item.width) || str.length * fontSize * 0.55) * 100) / 100;
|
|
5628
|
-
const height = Math.round(Math.max(8, Number(item.height) || fontSize * 1.2) * 100) / 100;
|
|
5629
|
-
const left = Math.round((Number(tr[4]) || 0) * 100) / 100;
|
|
5630
|
-
const baselineFromBottom = Number(tr[5]) || 0;
|
|
5631
|
-
const top = Math.round(Math.max(0, viewport.height - baselineFromBottom - fontSize * 0.85) * 100) / 100;
|
|
5632
|
-
idx++;
|
|
5633
|
-
spans.push({
|
|
5634
|
-
id: `native-${pageId}-${idx}`,
|
|
5635
|
-
pageId,
|
|
5636
|
-
pageIndex: i,
|
|
5637
|
-
text: str,
|
|
5638
|
-
left,
|
|
5639
|
-
top,
|
|
5640
|
-
width,
|
|
5641
|
-
height,
|
|
5642
|
-
fontSize,
|
|
5643
|
-
suppressed: false
|
|
5644
|
-
});
|
|
5645
|
-
}
|
|
5646
|
-
out[pageId] = spans;
|
|
5647
|
-
}
|
|
5648
|
-
if (typeof pdfDoc.destroy === "function") {
|
|
5649
|
-
await pdfDoc.destroy();
|
|
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);
|
|
5650
6071
|
}
|
|
5651
|
-
return out;
|
|
5652
|
-
} catch {
|
|
5653
|
-
return null;
|
|
5654
6072
|
}
|
|
6073
|
+
return {
|
|
6074
|
+
filter,
|
|
6075
|
+
version,
|
|
6076
|
+
revision,
|
|
6077
|
+
keyLength,
|
|
6078
|
+
pSigned,
|
|
6079
|
+
oBytes,
|
|
6080
|
+
uBytes,
|
|
6081
|
+
fileId
|
|
6082
|
+
};
|
|
5655
6083
|
}
|
|
5656
|
-
|
|
5657
|
-
const
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
const pageId = effectivePageIds[pIdx];
|
|
5665
|
-
const mediaBox = page.getMediaBox();
|
|
5666
|
-
const contentsBytes = decodeContentsEntry(doc, page.node.Contents());
|
|
5667
|
-
const resourcesDict = page.node.Resources();
|
|
5668
|
-
const rawOps = parsePdfContentStreamTextOps(doc, contentsBytes, resourcesDict, mediaBox);
|
|
5669
|
-
const pageSpans = rawOps.map((op, sIdx) => ({
|
|
5670
|
-
id: `native-${pageId}-${sIdx + 1}`,
|
|
5671
|
-
pageId,
|
|
5672
|
-
pageIndex: pIdx,
|
|
5673
|
-
text: op.text,
|
|
5674
|
-
left: op.left,
|
|
5675
|
-
top: op.top,
|
|
5676
|
-
width: op.width,
|
|
5677
|
-
height: op.height,
|
|
5678
|
-
fontSize: op.fontSize,
|
|
5679
|
-
suppressed: false
|
|
5680
|
-
}));
|
|
5681
|
-
if (pageSpans.length === 0 && contentsBytes.byteLength > 0) {
|
|
5682
|
-
anyPageEmpty = true;
|
|
5683
|
-
}
|
|
5684
|
-
spansByPage[pageId] = pageSpans;
|
|
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
|
+
};
|
|
5685
6092
|
}
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
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;
|
|
5695
6105
|
}
|
|
5696
|
-
return
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
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
|
+
};
|
|
5704
6116
|
}
|
|
5705
|
-
function
|
|
5706
|
-
|
|
5707
|
-
const
|
|
5708
|
-
|
|
5709
|
-
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
);
|
|
5714
|
-
if (matchingOps.length === 0) return 0;
|
|
5715
|
-
const sanitized = contentsBytes.slice();
|
|
5716
|
-
for (const op of matchingOps) {
|
|
5717
|
-
for (let i = op.streamStartOffset; i < op.streamEndOffset; i++) {
|
|
5718
|
-
if (sanitized[i] !== 10 && sanitized[i] !== 13) {
|
|
5719
|
-
sanitized[i] = 32;
|
|
5720
|
-
}
|
|
5721
|
-
}
|
|
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);
|
|
5722
6125
|
}
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
page.node.set(PDFName.of("Contents"), newRef);
|
|
5726
|
-
return matchingOps.length;
|
|
5727
|
-
}
|
|
5728
|
-
async function mergePdfBytes(pdfList) {
|
|
5729
|
-
if (!Array.isArray(pdfList) || pdfList.length === 0) {
|
|
5730
|
-
throw new Error("[UniverPdfs] mergePdfBytes requires at least one PDF Uint8Array.");
|
|
6126
|
+
if (!meta) {
|
|
6127
|
+
return pdfBytes.slice();
|
|
5731
6128
|
}
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
const copiedPages = await mergedDoc.copyPages(srcDoc, indices);
|
|
5738
|
-
for (const page of copiedPages) {
|
|
5739
|
-
mergedDoc.addPage(page);
|
|
5740
|
-
}
|
|
5741
|
-
}
|
|
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
|
+
);
|
|
5742
6134
|
}
|
|
5743
|
-
|
|
5744
|
-
|
|
5745
|
-
|
|
5746
|
-
|
|
5747
|
-
|
|
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
|
+
);
|
|
5748
6152
|
}
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
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
|
|
5758
6175
|
);
|
|
5759
6176
|
}
|
|
5760
|
-
const clampedEnd = Math.min(totalPages, end);
|
|
5761
|
-
const indices = [];
|
|
5762
|
-
for (let p = start; p <= clampedEnd; p++) {
|
|
5763
|
-
indices.push(p - 1);
|
|
5764
|
-
}
|
|
5765
|
-
const subDoc = await PDFDocument.create();
|
|
5766
|
-
const copiedPages = await subDoc.copyPages(srcDoc, indices);
|
|
5767
|
-
for (const page of copiedPages) {
|
|
5768
|
-
subDoc.addPage(page);
|
|
5769
|
-
}
|
|
5770
|
-
outputs.push(await subDoc.save());
|
|
5771
6177
|
}
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
if (!trimmed || trimmed.toLowerCase() === "all" || trimmed === "*") {
|
|
5778
|
-
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
|
6178
|
+
if (!encryptionKey) {
|
|
6179
|
+
throw new PdfSecurityError(
|
|
6180
|
+
"PDF_INVALID_PASSWORD",
|
|
6181
|
+
"Incorrect password for encrypted PDF document."
|
|
6182
|
+
);
|
|
5779
6183
|
}
|
|
5780
|
-
const
|
|
5781
|
-
const
|
|
5782
|
-
const
|
|
5783
|
-
if (
|
|
5784
|
-
throw new Error(`[UniverPdfs] Page number ${p} is out of bounds (1..${totalPages}).`);
|
|
5785
|
-
}
|
|
5786
|
-
if (!seen.has(p)) {
|
|
5787
|
-
seen.add(p);
|
|
5788
|
-
out.push(p);
|
|
5789
|
-
}
|
|
5790
|
-
};
|
|
5791
|
-
const parts = trimmed.split(",").map((s) => s.trim()).filter(Boolean);
|
|
5792
|
-
for (const part of parts) {
|
|
5793
|
-
const rangeMatch = /^(\d+)\s*-\s*(\d*)$/.exec(part);
|
|
5794
|
-
if (rangeMatch) {
|
|
5795
|
-
const start = parseInt(rangeMatch[1], 10);
|
|
5796
|
-
const end = rangeMatch[2] ? parseInt(rangeMatch[2], 10) : totalPages;
|
|
5797
|
-
if (start < 1 || end < start || end > totalPages) {
|
|
5798
|
-
throw new Error(`[UniverPdfs] Invalid page range "${part}" for ${totalPages}-page document.`);
|
|
5799
|
-
}
|
|
5800
|
-
for (let p = start; p <= end; p++) {
|
|
5801
|
-
addPage(p);
|
|
5802
|
-
}
|
|
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) {
|
|
5803
6188
|
continue;
|
|
5804
6189
|
}
|
|
5805
|
-
if (
|
|
5806
|
-
addPage(parseInt(part, 10));
|
|
6190
|
+
if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
|
|
5807
6191
|
continue;
|
|
5808
6192
|
}
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
|
|
5817
|
-
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
if (!seen.has(p)) {
|
|
5825
|
-
seen.add(p);
|
|
5826
|
-
out.push(p);
|
|
5827
|
-
}
|
|
5828
|
-
}
|
|
5829
|
-
return out;
|
|
5830
|
-
}
|
|
5831
|
-
async function removePdfPagesBytes(pdfBytes, pagesToRemove) {
|
|
5832
|
-
const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
|
|
5833
|
-
const totalPages = srcDoc.getPageCount();
|
|
5834
|
-
const removeSet = new Set(resolveOneBasedPages(pagesToRemove, totalPages));
|
|
5835
|
-
const keepIndices = [];
|
|
5836
|
-
for (let p = 1; p <= totalPages; p++) {
|
|
5837
|
-
if (!removeSet.has(p)) {
|
|
5838
|
-
keepIndices.push(p - 1);
|
|
5839
|
-
}
|
|
5840
|
-
}
|
|
5841
|
-
if (keepIndices.length === 0) {
|
|
5842
|
-
throw new Error("[UniverPdfs] Cannot remove all pages from a PDF document.");
|
|
5843
|
-
}
|
|
5844
|
-
const outDoc = await PDFDocument.create();
|
|
5845
|
-
const copied = await outDoc.copyPages(srcDoc, keepIndices);
|
|
5846
|
-
for (const page of copied) {
|
|
5847
|
-
outDoc.addPage(page);
|
|
5848
|
-
}
|
|
5849
|
-
return await outDoc.save();
|
|
5850
|
-
}
|
|
5851
|
-
async function insertPdfPagesBytes(basePdfBytes, insertPdfBytes, atPageIndex, sourcePages) {
|
|
5852
|
-
const baseDoc = await PDFDocument.load(basePdfBytes, { ignoreEncryption: true });
|
|
5853
|
-
const insertDoc = await PDFDocument.load(insertPdfBytes, { ignoreEncryption: true });
|
|
5854
|
-
const baseCount = baseDoc.getPageCount();
|
|
5855
|
-
const insertTotal = insertDoc.getPageCount();
|
|
5856
|
-
const targetIdx = atPageIndex === void 0 ? baseCount : Math.max(0, Math.min(baseCount, Math.floor(atPageIndex)));
|
|
5857
|
-
const srcOneBased = sourcePages ? resolveOneBasedPages(sourcePages, insertTotal) : Array.from({ length: insertTotal }, (_, i) => i + 1);
|
|
5858
|
-
const outDoc = await PDFDocument.create();
|
|
5859
|
-
const beforeIndices = Array.from({ length: targetIdx }, (_, i) => i);
|
|
5860
|
-
const afterIndices = Array.from({ length: baseCount - targetIdx }, (_, i) => targetIdx + i);
|
|
5861
|
-
if (beforeIndices.length > 0) {
|
|
5862
|
-
for (const pg of await outDoc.copyPages(baseDoc, beforeIndices)) {
|
|
5863
|
-
outDoc.addPage(pg);
|
|
5864
|
-
}
|
|
5865
|
-
}
|
|
5866
|
-
if (srcOneBased.length > 0) {
|
|
5867
|
-
for (const pg of await outDoc.copyPages(insertDoc, srcOneBased.map((p) => p - 1))) {
|
|
5868
|
-
outDoc.addPage(pg);
|
|
5869
|
-
}
|
|
5870
|
-
}
|
|
5871
|
-
if (afterIndices.length > 0) {
|
|
5872
|
-
for (const pg of await outDoc.copyPages(baseDoc, afterIndices)) {
|
|
5873
|
-
outDoc.addPage(pg);
|
|
5874
|
-
}
|
|
5875
|
-
}
|
|
5876
|
-
return await outDoc.save();
|
|
5877
|
-
}
|
|
5878
|
-
async function rotatePdfPagesBytes(pdfBytes, angleDeg, pages, options) {
|
|
5879
|
-
const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
|
|
5880
|
-
const totalPages = doc.getPageCount();
|
|
5881
|
-
const targets = pages ? resolveOneBasedPages(pages, totalPages) : Array.from({ length: totalPages }, (_, i) => i + 1);
|
|
5882
|
-
const isRelative = options?.relative !== false;
|
|
5883
|
-
for (const pNum of targets) {
|
|
5884
|
-
const page = doc.getPage(pNum - 1);
|
|
5885
|
-
const curAngle = page.getRotation().angle || 0;
|
|
5886
|
-
const nextAngle = isRelative ? ((curAngle + angleDeg) % 360 + 360) % 360 : (angleDeg % 360 + 360) % 360;
|
|
5887
|
-
page.setRotation(degrees(nextAngle));
|
|
5888
|
-
}
|
|
5889
|
-
return await doc.save();
|
|
5890
|
-
}
|
|
5891
|
-
async function movePdfPageBytes(pdfBytes, fromPage, toPage) {
|
|
5892
|
-
const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
|
|
5893
|
-
const totalPages = srcDoc.getPageCount();
|
|
5894
|
-
const fromIdx = Math.floor(fromPage) - 1;
|
|
5895
|
-
const toIdx = Math.floor(toPage) - 1;
|
|
5896
|
-
if (fromIdx < 0 || fromIdx >= totalPages || toIdx < 0 || toIdx >= totalPages) {
|
|
5897
|
-
throw new Error(
|
|
5898
|
-
`[UniverPdfs] movePdfPageBytes indices (${fromPage} -> ${toPage}) out of bounds (1..${totalPages}).`
|
|
5899
|
-
);
|
|
5900
|
-
}
|
|
5901
|
-
if (fromIdx === toIdx) {
|
|
5902
|
-
return await srcDoc.save();
|
|
5903
|
-
}
|
|
5904
|
-
const order = Array.from({ length: totalPages }, (_, i) => i);
|
|
5905
|
-
const [moved] = order.splice(fromIdx, 1);
|
|
5906
|
-
order.splice(toIdx, 0, moved);
|
|
5907
|
-
const outDoc = await PDFDocument.create();
|
|
5908
|
-
for (const pg of await outDoc.copyPages(srcDoc, order)) {
|
|
5909
|
-
outDoc.addPage(pg);
|
|
5910
|
-
}
|
|
5911
|
-
return await outDoc.save();
|
|
5912
|
-
}
|
|
5913
|
-
async function organizePdfBytes(pdfBytes, planOrOptions) {
|
|
5914
|
-
if (!Array.isArray(planOrOptions) && planOrOptions.actions?.length) {
|
|
5915
|
-
let working = pdfBytes;
|
|
5916
|
-
for (const act of planOrOptions.actions) {
|
|
5917
|
-
if (act.type === "remove") {
|
|
5918
|
-
working = await removePdfPagesBytes(working, act.pages);
|
|
5919
|
-
} else if (act.type === "rotate") {
|
|
5920
|
-
working = await rotatePdfPagesBytes(working, act.angle, act.pages, { relative: act.relative });
|
|
5921
|
-
} else if (act.type === "move") {
|
|
5922
|
-
working = await movePdfPageBytes(working, act.fromPage, act.toPage);
|
|
5923
|
-
} else if (act.type === "duplicate") {
|
|
5924
|
-
const doc = await PDFDocument.load(working, { ignoreEncryption: true });
|
|
5925
|
-
const total = doc.getPageCount();
|
|
5926
|
-
const p = Math.floor(act.pageNumber);
|
|
5927
|
-
if (p < 1 || p > total) {
|
|
5928
|
-
throw new Error(`[UniverPdfs] Cannot duplicate page ${act.pageNumber} (1..${total}).`);
|
|
5929
|
-
}
|
|
5930
|
-
const plan = [];
|
|
5931
|
-
for (let i = 1; i <= total; i++) {
|
|
5932
|
-
if (i === p && act.insertAfter === false) plan.push(p);
|
|
5933
|
-
plan.push(i);
|
|
5934
|
-
if (i === p && act.insertAfter !== false) plan.push(p);
|
|
5935
|
-
}
|
|
5936
|
-
working = await organizePdfBytes(working, plan);
|
|
5937
|
-
}
|
|
5938
|
-
}
|
|
5939
|
-
if (!planOrOptions.pages) {
|
|
5940
|
-
return working;
|
|
5941
|
-
}
|
|
5942
|
-
return organizePdfBytes(working, planOrOptions.pages);
|
|
5943
|
-
}
|
|
5944
|
-
const pageSpecs = Array.isArray(planOrOptions) ? planOrOptions : planOrOptions.pages ?? [];
|
|
5945
|
-
if (pageSpecs.length === 0) {
|
|
5946
|
-
throw new Error("[UniverPdfs] organizePdfBytes requires at least one output page specification.");
|
|
5947
|
-
}
|
|
5948
|
-
const srcDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
|
|
5949
|
-
const totalPages = srcDoc.getPageCount();
|
|
5950
|
-
const outDoc = await PDFDocument.create();
|
|
5951
|
-
for (const spec of pageSpecs) {
|
|
5952
|
-
const pNum = typeof spec === "number" ? Math.floor(spec) : Math.floor(spec.pageNumber);
|
|
5953
|
-
if (pNum < 1 || pNum > totalPages) {
|
|
5954
|
-
throw new Error(`[UniverPdfs] organizePdfBytes pageNumber ${pNum} out of bounds (1..${totalPages}).`);
|
|
5955
|
-
}
|
|
5956
|
-
const [copiedPage] = await outDoc.copyPages(srcDoc, [pNum - 1]);
|
|
5957
|
-
if (typeof spec === "object") {
|
|
5958
|
-
if (spec.rotation !== void 0) {
|
|
5959
|
-
const absAngle = (spec.rotation % 360 + 360) % 360;
|
|
5960
|
-
copiedPage.setRotation(degrees(absAngle));
|
|
5961
|
-
} else if (spec.addRotation !== void 0) {
|
|
5962
|
-
const curAngle = copiedPage.getRotation().angle || 0;
|
|
5963
|
-
const nextAngle = ((curAngle + spec.addRotation) % 360 + 360) % 360;
|
|
5964
|
-
copiedPage.setRotation(degrees(nextAngle));
|
|
5965
|
-
}
|
|
5966
|
-
}
|
|
5967
|
-
outDoc.addPage(copiedPage);
|
|
5968
|
-
}
|
|
5969
|
-
return await outDoc.save();
|
|
5970
|
-
}
|
|
5971
|
-
|
|
5972
|
-
// src/exporter/pdf-security.ts
|
|
5973
|
-
import {
|
|
5974
|
-
PDFArray as PDFArray2,
|
|
5975
|
-
PDFDict as PDFDict2,
|
|
5976
|
-
PDFDocument as PDFDocument2,
|
|
5977
|
-
PDFHexString,
|
|
5978
|
-
PDFName as PDFName2,
|
|
5979
|
-
PDFNumber as PDFNumber2,
|
|
5980
|
-
PDFRawStream as PDFRawStream2,
|
|
5981
|
-
PDFRef as PDFRef2,
|
|
5982
|
-
PDFStream as PDFStream2,
|
|
5983
|
-
PDFString
|
|
5984
|
-
} from "pdf-lib";
|
|
5985
|
-
var PdfSecurityError = class extends Error {
|
|
5986
|
-
constructor(code, message) {
|
|
5987
|
-
super(message);
|
|
5988
|
-
this.name = "PdfSecurityError";
|
|
5989
|
-
this.code = code;
|
|
5990
|
-
}
|
|
5991
|
-
};
|
|
5992
|
-
var PDF_PASSWORD_PADDING = new Uint8Array([
|
|
5993
|
-
40,
|
|
5994
|
-
191,
|
|
5995
|
-
78,
|
|
5996
|
-
94,
|
|
5997
|
-
78,
|
|
5998
|
-
117,
|
|
5999
|
-
138,
|
|
6000
|
-
65,
|
|
6001
|
-
100,
|
|
6002
|
-
0,
|
|
6003
|
-
78,
|
|
6004
|
-
86,
|
|
6005
|
-
255,
|
|
6006
|
-
250,
|
|
6007
|
-
1,
|
|
6008
|
-
8,
|
|
6009
|
-
46,
|
|
6010
|
-
46,
|
|
6011
|
-
0,
|
|
6012
|
-
182,
|
|
6013
|
-
208,
|
|
6014
|
-
104,
|
|
6015
|
-
62,
|
|
6016
|
-
128,
|
|
6017
|
-
47,
|
|
6018
|
-
12,
|
|
6019
|
-
169,
|
|
6020
|
-
254,
|
|
6021
|
-
100,
|
|
6022
|
-
83,
|
|
6023
|
-
105,
|
|
6024
|
-
122
|
|
6025
|
-
]);
|
|
6026
|
-
var DEFAULT_ALL_PERMISSIONS = Object.freeze({
|
|
6027
|
-
print: true,
|
|
6028
|
-
highResPrint: true,
|
|
6029
|
-
modify: true,
|
|
6030
|
-
copy: true,
|
|
6031
|
-
annotate: true,
|
|
6032
|
-
fillForms: true,
|
|
6033
|
-
assemble: true
|
|
6034
|
-
});
|
|
6035
|
-
var MD5_SHIFTS = [
|
|
6036
|
-
7,
|
|
6037
|
-
12,
|
|
6038
|
-
17,
|
|
6039
|
-
22,
|
|
6040
|
-
7,
|
|
6041
|
-
12,
|
|
6042
|
-
17,
|
|
6043
|
-
22,
|
|
6044
|
-
7,
|
|
6045
|
-
12,
|
|
6046
|
-
17,
|
|
6047
|
-
22,
|
|
6048
|
-
7,
|
|
6049
|
-
12,
|
|
6050
|
-
17,
|
|
6051
|
-
22,
|
|
6052
|
-
5,
|
|
6053
|
-
9,
|
|
6054
|
-
14,
|
|
6055
|
-
20,
|
|
6056
|
-
5,
|
|
6057
|
-
9,
|
|
6058
|
-
14,
|
|
6059
|
-
20,
|
|
6060
|
-
5,
|
|
6061
|
-
9,
|
|
6062
|
-
14,
|
|
6063
|
-
20,
|
|
6064
|
-
5,
|
|
6065
|
-
9,
|
|
6066
|
-
14,
|
|
6067
|
-
20,
|
|
6068
|
-
4,
|
|
6069
|
-
11,
|
|
6070
|
-
16,
|
|
6071
|
-
23,
|
|
6072
|
-
4,
|
|
6073
|
-
11,
|
|
6074
|
-
16,
|
|
6075
|
-
23,
|
|
6076
|
-
4,
|
|
6077
|
-
11,
|
|
6078
|
-
16,
|
|
6079
|
-
23,
|
|
6080
|
-
4,
|
|
6081
|
-
11,
|
|
6082
|
-
16,
|
|
6083
|
-
23,
|
|
6084
|
-
6,
|
|
6085
|
-
10,
|
|
6086
|
-
15,
|
|
6087
|
-
21,
|
|
6088
|
-
6,
|
|
6089
|
-
10,
|
|
6090
|
-
15,
|
|
6091
|
-
21,
|
|
6092
|
-
6,
|
|
6093
|
-
10,
|
|
6094
|
-
15,
|
|
6095
|
-
21,
|
|
6096
|
-
6,
|
|
6097
|
-
10,
|
|
6098
|
-
15,
|
|
6099
|
-
21
|
|
6100
|
-
];
|
|
6101
|
-
var MD5_K = (() => {
|
|
6102
|
-
const table = new Uint32Array(64);
|
|
6103
|
-
for (let i = 0; i < 64; i++) {
|
|
6104
|
-
table[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
|
|
6105
|
-
}
|
|
6106
|
-
return table;
|
|
6107
|
-
})();
|
|
6108
|
-
function rotl32(x, n) {
|
|
6109
|
-
return (x << n | x >>> 32 - n) >>> 0;
|
|
6110
|
-
}
|
|
6111
|
-
function md5Bytes(data) {
|
|
6112
|
-
const msgLen = data.byteLength;
|
|
6113
|
-
const rem = (msgLen + 9) % 64;
|
|
6114
|
-
const padZeroes = rem === 0 ? 0 : 64 - rem;
|
|
6115
|
-
const totalLen = msgLen + 9 + padZeroes;
|
|
6116
|
-
const buf = new Uint8Array(totalLen);
|
|
6117
|
-
buf.set(data, 0);
|
|
6118
|
-
buf[msgLen] = 128;
|
|
6119
|
-
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
6120
|
-
const bitLenLow = msgLen * 8 >>> 0;
|
|
6121
|
-
const bitLenHigh = Math.floor(msgLen * 8 / 4294967296) >>> 0;
|
|
6122
|
-
view.setUint32(totalLen - 8, bitLenLow, true);
|
|
6123
|
-
view.setUint32(totalLen - 4, bitLenHigh, true);
|
|
6124
|
-
let a0 = 1732584193;
|
|
6125
|
-
let b0 = 4023233417;
|
|
6126
|
-
let c0 = 2562383102;
|
|
6127
|
-
let d0 = 271733878;
|
|
6128
|
-
const M = new Uint32Array(16);
|
|
6129
|
-
for (let offset = 0; offset < totalLen; offset += 64) {
|
|
6130
|
-
for (let j = 0; j < 16; j++) {
|
|
6131
|
-
M[j] = view.getUint32(offset + j * 4, true);
|
|
6132
|
-
}
|
|
6133
|
-
let A = a0;
|
|
6134
|
-
let B = b0;
|
|
6135
|
-
let C = c0;
|
|
6136
|
-
let D = d0;
|
|
6137
|
-
for (let i = 0; i < 64; i++) {
|
|
6138
|
-
let F;
|
|
6139
|
-
let g;
|
|
6140
|
-
if (i < 16) {
|
|
6141
|
-
F = B & C | ~B & D;
|
|
6142
|
-
g = i;
|
|
6143
|
-
} else if (i < 32) {
|
|
6144
|
-
F = D & B | ~D & C;
|
|
6145
|
-
g = (5 * i + 1) % 16;
|
|
6146
|
-
} else if (i < 48) {
|
|
6147
|
-
F = B ^ C ^ D;
|
|
6148
|
-
g = (3 * i + 5) % 16;
|
|
6149
|
-
} else {
|
|
6150
|
-
F = C ^ (B | ~D);
|
|
6151
|
-
g = 7 * i % 16;
|
|
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);
|
|
6152
6208
|
}
|
|
6153
|
-
const sum = A + F + MD5_K[i] + M[g] >>> 0;
|
|
6154
|
-
A = D;
|
|
6155
|
-
D = C;
|
|
6156
|
-
C = B;
|
|
6157
|
-
B = B + rotl32(sum, MD5_SHIFTS[i]) >>> 0;
|
|
6158
6209
|
}
|
|
6159
|
-
a0 = a0 + A >>> 0;
|
|
6160
|
-
b0 = b0 + B >>> 0;
|
|
6161
|
-
c0 = c0 + C >>> 0;
|
|
6162
|
-
d0 = d0 + D >>> 0;
|
|
6163
6210
|
}
|
|
6164
|
-
|
|
6165
|
-
|
|
6166
|
-
|
|
6167
|
-
|
|
6168
|
-
|
|
6169
|
-
outView.setUint32(12, d0, true);
|
|
6170
|
-
return out;
|
|
6211
|
+
delete doc.context.trailerInfo.Encrypt;
|
|
6212
|
+
if (encryptRef) {
|
|
6213
|
+
doc.context.delete(encryptRef);
|
|
6214
|
+
}
|
|
6215
|
+
return await doc.save({ useObjectStreams: false, updateFieldAppearances: false });
|
|
6171
6216
|
}
|
|
6172
|
-
function
|
|
6173
|
-
const
|
|
6174
|
-
if (
|
|
6175
|
-
|
|
6176
|
-
for (let i2 = 0; i2 < 256; i2++) {
|
|
6177
|
-
S[i2] = i2;
|
|
6217
|
+
async function verifyAndDecryptPdfBytes(pdfBytes, password) {
|
|
6218
|
+
const inspection = inspectPdfEncryption(pdfBytes);
|
|
6219
|
+
if (!inspection.encrypted) {
|
|
6220
|
+
return pdfBytes;
|
|
6178
6221
|
}
|
|
6179
|
-
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
|
|
6222
|
+
return decryptPdfBytes(pdfBytes, password);
|
|
6223
|
+
}
|
|
6224
|
+
|
|
6225
|
+
// src/exporter/pdf-native-text.ts
|
|
6226
|
+
var WIN_ANSI_EXTENDED = {
|
|
6227
|
+
128: 8364,
|
|
6228
|
+
130: 8218,
|
|
6229
|
+
131: 402,
|
|
6230
|
+
132: 8222,
|
|
6231
|
+
133: 8230,
|
|
6232
|
+
134: 8224,
|
|
6233
|
+
135: 8225,
|
|
6234
|
+
136: 710,
|
|
6235
|
+
137: 8240,
|
|
6236
|
+
138: 352,
|
|
6237
|
+
139: 8249,
|
|
6238
|
+
140: 338,
|
|
6239
|
+
142: 381,
|
|
6240
|
+
145: 8216,
|
|
6241
|
+
146: 8217,
|
|
6242
|
+
147: 8220,
|
|
6243
|
+
148: 8221,
|
|
6244
|
+
149: 8226,
|
|
6245
|
+
150: 8211,
|
|
6246
|
+
151: 8212,
|
|
6247
|
+
152: 732,
|
|
6248
|
+
153: 8482,
|
|
6249
|
+
154: 353,
|
|
6250
|
+
155: 8250,
|
|
6251
|
+
156: 339,
|
|
6252
|
+
158: 382,
|
|
6253
|
+
159: 376
|
|
6254
|
+
};
|
|
6255
|
+
function multiplyPdfMatrix(m1, m2) {
|
|
6256
|
+
return [
|
|
6257
|
+
m1[0] * m2[0] + m1[1] * m2[2],
|
|
6258
|
+
m1[0] * m2[1] + m1[1] * m2[3],
|
|
6259
|
+
m1[2] * m2[0] + m1[3] * m2[2],
|
|
6260
|
+
m1[2] * m2[1] + m1[3] * m2[3],
|
|
6261
|
+
m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
|
|
6262
|
+
m1[4] * m2[1] + m1[5] * m2[3] + m2[5]
|
|
6263
|
+
];
|
|
6264
|
+
}
|
|
6265
|
+
function decodeSingleStreamObject(doc, objOrRef) {
|
|
6266
|
+
const resolved = objOrRef instanceof PDFRef2 ? doc.context.lookup(objOrRef) : objOrRef;
|
|
6267
|
+
if (!resolved) return new Uint8Array(0);
|
|
6268
|
+
if (resolved instanceof PDFRawStream2) {
|
|
6269
|
+
try {
|
|
6270
|
+
const decoded = decodePDFRawStream(resolved).decode();
|
|
6271
|
+
return decoded instanceof Uint8Array ? decoded : new Uint8Array(decoded);
|
|
6272
|
+
} catch {
|
|
6273
|
+
return resolved.contents;
|
|
6274
|
+
}
|
|
6185
6275
|
}
|
|
6186
|
-
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
|
|
6190
|
-
|
|
6191
|
-
|
|
6192
|
-
|
|
6193
|
-
|
|
6194
|
-
S[j] = tmp;
|
|
6195
|
-
out[k] = data[k] ^ S[S[i] + S[j] & 255];
|
|
6276
|
+
if (resolved instanceof PDFStream2) {
|
|
6277
|
+
const anyStream = resolved;
|
|
6278
|
+
if (typeof anyStream.getUnencodedContents === "function") {
|
|
6279
|
+
return anyStream.getUnencodedContents();
|
|
6280
|
+
}
|
|
6281
|
+
if (typeof anyStream.getContents === "function") {
|
|
6282
|
+
return anyStream.getContents();
|
|
6283
|
+
}
|
|
6196
6284
|
}
|
|
6197
|
-
return
|
|
6285
|
+
return new Uint8Array(0);
|
|
6198
6286
|
}
|
|
6199
|
-
function
|
|
6200
|
-
|
|
6201
|
-
|
|
6202
|
-
|
|
6287
|
+
function decodeContentsEntry(doc, contentsEntry) {
|
|
6288
|
+
const resolved = contentsEntry instanceof PDFRef2 ? doc.context.lookup(contentsEntry) : contentsEntry;
|
|
6289
|
+
if (!resolved) return new Uint8Array(0);
|
|
6290
|
+
if (resolved instanceof PDFArray2) {
|
|
6291
|
+
const parts = [];
|
|
6292
|
+
let total = 0;
|
|
6293
|
+
for (let i = 0; i < resolved.size(); i++) {
|
|
6294
|
+
const part = decodeSingleStreamObject(doc, resolved.get(i));
|
|
6295
|
+
if (part.byteLength > 0) {
|
|
6296
|
+
parts.push(part);
|
|
6297
|
+
total += part.byteLength + 1;
|
|
6298
|
+
}
|
|
6299
|
+
}
|
|
6300
|
+
const merged = new Uint8Array(total);
|
|
6301
|
+
let offset = 0;
|
|
6302
|
+
for (const part of parts) {
|
|
6303
|
+
merged.set(part, offset);
|
|
6304
|
+
offset += part.byteLength;
|
|
6305
|
+
merged[offset++] = 10;
|
|
6306
|
+
}
|
|
6307
|
+
return merged;
|
|
6203
6308
|
}
|
|
6204
|
-
return
|
|
6309
|
+
return decodeSingleStreamObject(doc, resolved);
|
|
6205
6310
|
}
|
|
6206
|
-
function
|
|
6207
|
-
|
|
6208
|
-
const
|
|
6209
|
-
|
|
6210
|
-
|
|
6211
|
-
out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16) || 0;
|
|
6311
|
+
function bytesToLatin1String(bytes) {
|
|
6312
|
+
let out = "";
|
|
6313
|
+
const chunk = 16384;
|
|
6314
|
+
for (let i = 0; i < bytes.length; i += chunk) {
|
|
6315
|
+
out += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
6212
6316
|
}
|
|
6213
6317
|
return out;
|
|
6214
6318
|
}
|
|
6215
|
-
function
|
|
6216
|
-
|
|
6217
|
-
|
|
6218
|
-
|
|
6219
|
-
|
|
6220
|
-
|
|
6221
|
-
|
|
6319
|
+
function decodeUtf16BeHex(hex) {
|
|
6320
|
+
const cleaned = hex.replace(/\s+/g, "");
|
|
6321
|
+
if (!cleaned) return "";
|
|
6322
|
+
if (cleaned.length <= 2) {
|
|
6323
|
+
return String.fromCodePoint(parseInt(cleaned, 16) || 32);
|
|
6324
|
+
}
|
|
6325
|
+
const codeUnits = [];
|
|
6326
|
+
for (let i = 0; i + 3 < cleaned.length; i += 4) {
|
|
6327
|
+
codeUnits.push(parseInt(cleaned.slice(i, i + 4), 16));
|
|
6328
|
+
}
|
|
6329
|
+
return String.fromCharCode(...codeUnits);
|
|
6330
|
+
}
|
|
6331
|
+
function parseToUnicodeCMap(cmapText) {
|
|
6332
|
+
const map = /* @__PURE__ */ new Map();
|
|
6333
|
+
let bytesPerCode = 1;
|
|
6334
|
+
const bfCharRe = /beginbfchar([\s\S]*?)endbfchar/g;
|
|
6335
|
+
let blockMatch;
|
|
6336
|
+
while ((blockMatch = bfCharRe.exec(cmapText)) !== null) {
|
|
6337
|
+
const body = blockMatch[1];
|
|
6338
|
+
const pairRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
|
|
6339
|
+
let m;
|
|
6340
|
+
while ((m = pairRe.exec(body)) !== null) {
|
|
6341
|
+
if (m[1].length >= 4) bytesPerCode = 2;
|
|
6342
|
+
const srcCode = parseInt(m[1], 16);
|
|
6343
|
+
const dstStr = decodeUtf16BeHex(m[2]);
|
|
6344
|
+
if (!Number.isNaN(srcCode) && dstStr) {
|
|
6345
|
+
map.set(srcCode, dstStr);
|
|
6346
|
+
}
|
|
6222
6347
|
}
|
|
6223
6348
|
}
|
|
6224
|
-
|
|
6225
|
-
|
|
6349
|
+
const bfRangeRe = /beginbfrange([\s\S]*?)endbfrange/g;
|
|
6350
|
+
while ((blockMatch = bfRangeRe.exec(cmapText)) !== null) {
|
|
6351
|
+
const body = blockMatch[1];
|
|
6352
|
+
const arrayRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([^\]]*)\]/g;
|
|
6353
|
+
let am;
|
|
6354
|
+
while ((am = arrayRangeRe.exec(body)) !== null) {
|
|
6355
|
+
if (am[1].length >= 4) bytesPerCode = 2;
|
|
6356
|
+
const start = parseInt(am[1], 16);
|
|
6357
|
+
const end = parseInt(am[2], 16);
|
|
6358
|
+
const targets = Array.from(am[3].matchAll(/<([0-9A-Fa-f]+)>/g)).map((x) => decodeUtf16BeHex(x[1]));
|
|
6359
|
+
for (let code = start; code <= end && code - start < targets.length; code++) {
|
|
6360
|
+
if (targets[code - start]) {
|
|
6361
|
+
map.set(code, targets[code - start]);
|
|
6362
|
+
}
|
|
6363
|
+
}
|
|
6364
|
+
}
|
|
6365
|
+
const directRangeRe = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g;
|
|
6366
|
+
let dm;
|
|
6367
|
+
while ((dm = directRangeRe.exec(body)) !== null) {
|
|
6368
|
+
if (dm[1].length >= 4) bytesPerCode = 2;
|
|
6369
|
+
const start = parseInt(dm[1], 16);
|
|
6370
|
+
const end = parseInt(dm[2], 16);
|
|
6371
|
+
const baseStr = decodeUtf16BeHex(dm[3]);
|
|
6372
|
+
const baseCp = baseStr.codePointAt(0) ?? 32;
|
|
6373
|
+
if (end >= start && end - start <= 16384) {
|
|
6374
|
+
for (let code = start; code <= end; code++) {
|
|
6375
|
+
map.set(code, String.fromCodePoint(baseCp + (code - start)));
|
|
6376
|
+
}
|
|
6377
|
+
}
|
|
6378
|
+
}
|
|
6226
6379
|
}
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6380
|
+
return { map, bytesPerCode };
|
|
6381
|
+
}
|
|
6382
|
+
function extractResourcesFontMap(doc, resourcesDict) {
|
|
6383
|
+
const fonts = /* @__PURE__ */ new Map();
|
|
6384
|
+
if (!resourcesDict) return fonts;
|
|
6385
|
+
const fontObj = resourcesDict.get(PDFName2.of("Font"));
|
|
6386
|
+
const fontDict = doc.context.lookupMaybe(fontObj, PDFDict2);
|
|
6387
|
+
if (!fontDict) return fonts;
|
|
6388
|
+
for (const [keyObj, valObj] of fontDict.entries()) {
|
|
6389
|
+
const cleanKey = keyObj.decodeText ? keyObj.decodeText() : keyObj.asString().replace(/^\//, "");
|
|
6390
|
+
const fDict = doc.context.lookupMaybe(valObj, PDFDict2);
|
|
6391
|
+
if (!fDict) continue;
|
|
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() : "";
|
|
6396
|
+
const isUtf16Cid = /UTF16|UCS2/i.test(encoding);
|
|
6397
|
+
let toUnicode = /* @__PURE__ */ new Map();
|
|
6398
|
+
let bytesPerCode = subtype === "Type0" ? 2 : 1;
|
|
6399
|
+
const toUniEntry = fDict.get(PDFName2.of("ToUnicode"));
|
|
6400
|
+
if (toUniEntry) {
|
|
6401
|
+
const cmapBytes = decodeSingleStreamObject(doc, toUniEntry);
|
|
6402
|
+
if (cmapBytes.byteLength > 0) {
|
|
6403
|
+
const parsed = parseToUnicodeCMap(bytesToLatin1String(cmapBytes));
|
|
6404
|
+
toUnicode = parsed.map;
|
|
6405
|
+
if (parsed.bytesPerCode === 2 || subtype === "Type0") {
|
|
6406
|
+
bytesPerCode = 2;
|
|
6407
|
+
}
|
|
6408
|
+
}
|
|
6409
|
+
}
|
|
6410
|
+
fonts.set(cleanKey, {
|
|
6411
|
+
subtype,
|
|
6412
|
+
encoding,
|
|
6413
|
+
isUtf16Cid,
|
|
6414
|
+
bytesPerCode,
|
|
6415
|
+
toUnicode
|
|
6416
|
+
});
|
|
6417
|
+
}
|
|
6418
|
+
return fonts;
|
|
6419
|
+
}
|
|
6420
|
+
function decodeWinAnsiBytes(bytes) {
|
|
6421
|
+
let out = "";
|
|
6422
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
6423
|
+
const b = bytes[i];
|
|
6424
|
+
if (b in WIN_ANSI_EXTENDED) {
|
|
6425
|
+
out += String.fromCharCode(WIN_ANSI_EXTENDED[b]);
|
|
6426
|
+
} else if (b >= 32 || b === 9 || b === 10 || b === 13) {
|
|
6427
|
+
out += String.fromCharCode(b);
|
|
6428
|
+
}
|
|
6230
6429
|
}
|
|
6231
6430
|
return out;
|
|
6232
6431
|
}
|
|
6233
|
-
function
|
|
6234
|
-
const
|
|
6235
|
-
|
|
6236
|
-
|
|
6237
|
-
|
|
6238
|
-
|
|
6239
|
-
|
|
6432
|
+
function decodeUtf16BeBytes(bytes, startOffset = 0) {
|
|
6433
|
+
const units = [];
|
|
6434
|
+
for (let i = startOffset; i + 1 < bytes.length; i += 2) {
|
|
6435
|
+
const u = bytes[i] << 8 | bytes[i + 1];
|
|
6436
|
+
if (u !== 65279 && u > 0) {
|
|
6437
|
+
units.push(u);
|
|
6438
|
+
}
|
|
6240
6439
|
}
|
|
6241
|
-
return
|
|
6440
|
+
return String.fromCharCode(...units);
|
|
6242
6441
|
}
|
|
6243
|
-
function
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
6247
|
-
|
|
6248
|
-
const allowFillForms = permissions?.fillForms !== false;
|
|
6249
|
-
const allowAssemble = permissions?.assemble !== false;
|
|
6250
|
-
const allowHighResPrint = permissions?.highResPrint !== void 0 ? Boolean(permissions.highResPrint) : allowPrint;
|
|
6251
|
-
let mask = 4294963392 | 1 << 9;
|
|
6252
|
-
if (allowPrint) mask |= 1 << 2;
|
|
6253
|
-
if (allowModify) mask |= 1 << 3;
|
|
6254
|
-
if (allowCopy) mask |= 1 << 4;
|
|
6255
|
-
if (allowAnnotate) mask |= 1 << 5;
|
|
6256
|
-
if (revision >= 3) {
|
|
6257
|
-
if (allowFillForms) mask |= 1 << 8;
|
|
6258
|
-
if (allowAssemble) mask |= 1 << 10;
|
|
6259
|
-
if (allowHighResPrint && allowPrint) mask |= 1 << 11;
|
|
6260
|
-
} else {
|
|
6261
|
-
mask |= 1 << 8 | 1 << 10 | 1 << 11;
|
|
6442
|
+
function decodePdfStringBytes(bytes, fontInfo) {
|
|
6443
|
+
if (bytes.length === 0) return { text: "", glyphCount: 0 };
|
|
6444
|
+
if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) {
|
|
6445
|
+
const text2 = decodeUtf16BeBytes(bytes, 2);
|
|
6446
|
+
return { text: text2, glyphCount: text2.length };
|
|
6262
6447
|
}
|
|
6263
|
-
|
|
6448
|
+
if (fontInfo && fontInfo.toUnicode.size > 0) {
|
|
6449
|
+
if (fontInfo.bytesPerCode === 2 && bytes.length >= 2) {
|
|
6450
|
+
let out2 = "";
|
|
6451
|
+
let count = 0;
|
|
6452
|
+
for (let i = 0; i + 1 < bytes.length; i += 2) {
|
|
6453
|
+
const code = bytes[i] << 8 | bytes[i + 1];
|
|
6454
|
+
count++;
|
|
6455
|
+
const mapped = fontInfo.toUnicode.get(code);
|
|
6456
|
+
if (mapped !== void 0) {
|
|
6457
|
+
out2 += mapped;
|
|
6458
|
+
} else if (code >= 32 && code !== 65279) {
|
|
6459
|
+
out2 += String.fromCharCode(code);
|
|
6460
|
+
}
|
|
6461
|
+
}
|
|
6462
|
+
return { text: out2, glyphCount: count };
|
|
6463
|
+
}
|
|
6464
|
+
let out = "";
|
|
6465
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
6466
|
+
const code = bytes[i];
|
|
6467
|
+
const mapped = fontInfo.toUnicode.get(code);
|
|
6468
|
+
if (mapped !== void 0) {
|
|
6469
|
+
out += mapped;
|
|
6470
|
+
} else if (code in WIN_ANSI_EXTENDED) {
|
|
6471
|
+
out += String.fromCharCode(WIN_ANSI_EXTENDED[code]);
|
|
6472
|
+
} else if (code >= 32) {
|
|
6473
|
+
out += String.fromCharCode(code);
|
|
6474
|
+
}
|
|
6475
|
+
}
|
|
6476
|
+
return { text: out, glyphCount: bytes.length };
|
|
6477
|
+
}
|
|
6478
|
+
if (fontInfo?.isUtf16Cid || fontInfo?.subtype === "Type0" && bytes.length % 2 === 0) {
|
|
6479
|
+
const text2 = decodeUtf16BeBytes(bytes, 0);
|
|
6480
|
+
return { text: text2, glyphCount: Math.floor(bytes.length / 2) };
|
|
6481
|
+
}
|
|
6482
|
+
const text = decodeWinAnsiBytes(bytes);
|
|
6483
|
+
return { text, glyphCount: bytes.length };
|
|
6264
6484
|
}
|
|
6265
|
-
function
|
|
6266
|
-
|
|
6267
|
-
const modify = (pMask & 1 << 3) !== 0;
|
|
6268
|
-
const copy = (pMask & 1 << 4) !== 0;
|
|
6269
|
-
const annotate = (pMask & 1 << 5) !== 0;
|
|
6270
|
-
const fillForms = revision >= 3 ? (pMask & 1 << 8) !== 0 : annotate;
|
|
6271
|
-
const assemble = revision >= 3 ? (pMask & 1 << 10) !== 0 : modify;
|
|
6272
|
-
const highResPrint = revision >= 3 ? print && (pMask & 1 << 11) !== 0 : print;
|
|
6273
|
-
return {
|
|
6274
|
-
print,
|
|
6275
|
-
highResPrint,
|
|
6276
|
-
modify,
|
|
6277
|
-
copy,
|
|
6278
|
-
annotate,
|
|
6279
|
-
fillForms,
|
|
6280
|
-
assemble
|
|
6281
|
-
};
|
|
6485
|
+
function isPdfWhitespace(ch) {
|
|
6486
|
+
return ch === 0 || ch === 9 || ch === 10 || ch === 12 || ch === 13 || ch === 32;
|
|
6282
6487
|
}
|
|
6283
|
-
function
|
|
6284
|
-
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
|
|
6289
|
-
|
|
6488
|
+
function isPdfDelimiter(ch) {
|
|
6489
|
+
return ch === 40 || // (
|
|
6490
|
+
ch === 41 || // )
|
|
6491
|
+
ch === 60 || // <
|
|
6492
|
+
ch === 62 || // >
|
|
6493
|
+
ch === 91 || // [
|
|
6494
|
+
ch === 93 || // ]
|
|
6495
|
+
ch === 123 || // {
|
|
6496
|
+
ch === 125 || // }
|
|
6497
|
+
ch === 47 || // /
|
|
6498
|
+
ch === 37;
|
|
6290
6499
|
}
|
|
6291
|
-
function
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6500
|
+
function hexCharVal(c) {
|
|
6501
|
+
if (c >= 48 && c <= 57) return c - 48;
|
|
6502
|
+
if (c >= 65 && c <= 70) return c - 65 + 10;
|
|
6503
|
+
if (c >= 97 && c <= 102) return c - 97 + 10;
|
|
6504
|
+
return -1;
|
|
6505
|
+
}
|
|
6506
|
+
function tokenizeContentStream(bytes) {
|
|
6507
|
+
const len = bytes.length;
|
|
6508
|
+
let pos = 0;
|
|
6509
|
+
const readToken = () => {
|
|
6510
|
+
while (pos < len) {
|
|
6511
|
+
const c = bytes[pos];
|
|
6512
|
+
if (isPdfWhitespace(c)) {
|
|
6513
|
+
pos++;
|
|
6514
|
+
continue;
|
|
6515
|
+
}
|
|
6516
|
+
if (c === 37) {
|
|
6517
|
+
while (pos < len && bytes[pos] !== 10 && bytes[pos] !== 13) {
|
|
6518
|
+
pos++;
|
|
6519
|
+
}
|
|
6520
|
+
continue;
|
|
6521
|
+
}
|
|
6522
|
+
break;
|
|
6298
6523
|
}
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6524
|
+
if (pos >= len) return null;
|
|
6525
|
+
const start = pos;
|
|
6526
|
+
const ch = bytes[pos];
|
|
6527
|
+
if (ch === 40) {
|
|
6528
|
+
pos++;
|
|
6529
|
+
let depth = 1;
|
|
6530
|
+
const out = [];
|
|
6531
|
+
while (pos < len && depth > 0) {
|
|
6532
|
+
const b = bytes[pos++];
|
|
6533
|
+
if (b === 92) {
|
|
6534
|
+
if (pos >= len) break;
|
|
6535
|
+
const next = bytes[pos++];
|
|
6536
|
+
if (next === 110) out.push(10);
|
|
6537
|
+
else if (next === 114) out.push(13);
|
|
6538
|
+
else if (next === 116) out.push(9);
|
|
6539
|
+
else if (next === 98) out.push(8);
|
|
6540
|
+
else if (next === 102) out.push(12);
|
|
6541
|
+
else if (next === 40 || next === 41 || next === 92) out.push(next);
|
|
6542
|
+
else if (next === 13) {
|
|
6543
|
+
if (pos < len && bytes[pos] === 10) pos++;
|
|
6544
|
+
} else if (next === 10) {
|
|
6545
|
+
} else if (next >= 48 && next <= 55) {
|
|
6546
|
+
let oct = next - 48;
|
|
6547
|
+
for (let k = 0; k < 2 && pos < len && bytes[pos] >= 48 && bytes[pos] <= 55; k++) {
|
|
6548
|
+
oct = (oct << 3) + (bytes[pos++] - 48);
|
|
6549
|
+
}
|
|
6550
|
+
out.push(oct & 255);
|
|
6551
|
+
} else {
|
|
6552
|
+
out.push(next);
|
|
6553
|
+
}
|
|
6554
|
+
} else if (b === 40) {
|
|
6555
|
+
depth++;
|
|
6556
|
+
out.push(b);
|
|
6557
|
+
} else if (b === 41) {
|
|
6558
|
+
depth--;
|
|
6559
|
+
if (depth > 0) out.push(b);
|
|
6560
|
+
} else {
|
|
6561
|
+
out.push(b);
|
|
6562
|
+
}
|
|
6563
|
+
}
|
|
6564
|
+
return { type: "literal", bytes: new Uint8Array(out), start, end: pos };
|
|
6565
|
+
}
|
|
6566
|
+
if (ch === 60) {
|
|
6567
|
+
if (pos + 1 < len && bytes[pos + 1] === 60) {
|
|
6568
|
+
pos += 2;
|
|
6569
|
+
return { type: "dictStart", start, end: pos };
|
|
6570
|
+
}
|
|
6571
|
+
pos++;
|
|
6572
|
+
const nibbles = [];
|
|
6573
|
+
while (pos < len && bytes[pos] !== 62) {
|
|
6574
|
+
const hv = hexCharVal(bytes[pos++]);
|
|
6575
|
+
if (hv >= 0) nibbles.push(hv);
|
|
6576
|
+
}
|
|
6577
|
+
if (pos < len && bytes[pos] === 62) pos++;
|
|
6578
|
+
if (nibbles.length % 2 === 1) nibbles.push(0);
|
|
6579
|
+
const hexBytes = new Uint8Array(nibbles.length / 2);
|
|
6580
|
+
for (let i = 0; i < hexBytes.length; i++) {
|
|
6581
|
+
hexBytes[i] = nibbles[i * 2] << 4 | nibbles[i * 2 + 1];
|
|
6582
|
+
}
|
|
6583
|
+
return { type: "hex", bytes: hexBytes, start, end: pos };
|
|
6584
|
+
}
|
|
6585
|
+
if (ch === 62) {
|
|
6586
|
+
if (pos + 1 < len && bytes[pos + 1] === 62) {
|
|
6587
|
+
pos += 2;
|
|
6588
|
+
return { type: "dictEnd", start, end: pos };
|
|
6589
|
+
}
|
|
6590
|
+
pos++;
|
|
6591
|
+
return { type: "op", op: ">", start, end: pos };
|
|
6592
|
+
}
|
|
6593
|
+
if (ch === 91) {
|
|
6594
|
+
pos++;
|
|
6595
|
+
const items = [];
|
|
6596
|
+
while (pos < len) {
|
|
6597
|
+
while (pos < len && isPdfWhitespace(bytes[pos])) pos++;
|
|
6598
|
+
if (pos < len && bytes[pos] === 93) {
|
|
6599
|
+
pos++;
|
|
6600
|
+
break;
|
|
6601
|
+
}
|
|
6602
|
+
const child = readToken();
|
|
6603
|
+
if (!child) break;
|
|
6604
|
+
items.push(child);
|
|
6605
|
+
}
|
|
6606
|
+
return { type: "array", items, start, end: pos };
|
|
6607
|
+
}
|
|
6608
|
+
if (ch === 93) {
|
|
6609
|
+
pos++;
|
|
6610
|
+
return { type: "op", op: "]", start, end: pos };
|
|
6611
|
+
}
|
|
6612
|
+
if (ch === 47) {
|
|
6613
|
+
pos++;
|
|
6614
|
+
let name = "";
|
|
6615
|
+
while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
|
|
6616
|
+
if (bytes[pos] === 35 && pos + 2 < len) {
|
|
6617
|
+
const h1 = hexCharVal(bytes[pos + 1]);
|
|
6618
|
+
const h2 = hexCharVal(bytes[pos + 2]);
|
|
6619
|
+
if (h1 >= 0 && h2 >= 0) {
|
|
6620
|
+
name += String.fromCharCode(h1 << 4 | h2);
|
|
6621
|
+
pos += 3;
|
|
6622
|
+
continue;
|
|
6623
|
+
}
|
|
6624
|
+
}
|
|
6625
|
+
name += String.fromCharCode(bytes[pos++]);
|
|
6308
6626
|
}
|
|
6309
|
-
|
|
6627
|
+
return { type: "name", value: name, start, end: pos };
|
|
6310
6628
|
}
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
|
|
6314
|
-
function computeFileEncryptionKeyFromPadded(paddedUserPassword, oValue, pFlagsSigned, fileId, revision, keyLengthBits) {
|
|
6315
|
-
const buf = new Uint8Array(32 + oValue.byteLength + 4 + fileId.byteLength);
|
|
6316
|
-
let offset = 0;
|
|
6317
|
-
buf.set(paddedUserPassword.subarray(0, 32), offset);
|
|
6318
|
-
offset += 32;
|
|
6319
|
-
buf.set(oValue, offset);
|
|
6320
|
-
offset += oValue.byteLength;
|
|
6321
|
-
buf[offset++] = pFlagsSigned & 255;
|
|
6322
|
-
buf[offset++] = pFlagsSigned >>> 8 & 255;
|
|
6323
|
-
buf[offset++] = pFlagsSigned >>> 16 & 255;
|
|
6324
|
-
buf[offset++] = pFlagsSigned >>> 24 & 255;
|
|
6325
|
-
buf.set(fileId, offset);
|
|
6326
|
-
let hash = md5Bytes(buf);
|
|
6327
|
-
const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
|
|
6328
|
-
if (revision >= 3) {
|
|
6329
|
-
for (let i = 0; i < 50; i++) {
|
|
6330
|
-
hash = md5Bytes(hash.subarray(0, keyByteLen));
|
|
6629
|
+
let word = "";
|
|
6630
|
+
while (pos < len && !isPdfWhitespace(bytes[pos]) && !isPdfDelimiter(bytes[pos])) {
|
|
6631
|
+
word += String.fromCharCode(bytes[pos++]);
|
|
6331
6632
|
}
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
}
|
|
6335
|
-
function computeUserPasswordValue(encryptionKey, fileId, revision) {
|
|
6336
|
-
if (revision === 2) {
|
|
6337
|
-
return rc4Bytes(encryptionKey, PDF_PASSWORD_PADDING);
|
|
6338
|
-
}
|
|
6339
|
-
const hashInput = new Uint8Array(32 + fileId.byteLength);
|
|
6340
|
-
hashInput.set(PDF_PASSWORD_PADDING, 0);
|
|
6341
|
-
hashInput.set(fileId, 32);
|
|
6342
|
-
let check = rc4Bytes(encryptionKey, md5Bytes(hashInput));
|
|
6343
|
-
const keyLen = encryptionKey.byteLength;
|
|
6344
|
-
const derivedKey = new Uint8Array(keyLen);
|
|
6345
|
-
for (let iter = 1; iter <= 19; iter++) {
|
|
6346
|
-
for (let k = 0; k < keyLen; k++) {
|
|
6347
|
-
derivedKey[k] = encryptionKey[k] ^ iter;
|
|
6633
|
+
if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(word)) {
|
|
6634
|
+
return { type: "number", num: parseFloat(word), start, end: pos };
|
|
6348
6635
|
}
|
|
6349
|
-
|
|
6636
|
+
if (word === "ID") {
|
|
6637
|
+
if (pos < len && isPdfWhitespace(bytes[pos])) pos++;
|
|
6638
|
+
while (pos + 1 < len) {
|
|
6639
|
+
if (bytes[pos] === 69 && bytes[pos + 1] === 73 && (pos === 0 || isPdfWhitespace(bytes[pos - 1])) && (pos + 2 >= len || isPdfWhitespace(bytes[pos + 2]) || isPdfDelimiter(bytes[pos + 2]))) {
|
|
6640
|
+
pos += 2;
|
|
6641
|
+
return { type: "op", op: "EI", start, end: pos };
|
|
6642
|
+
}
|
|
6643
|
+
pos++;
|
|
6644
|
+
}
|
|
6645
|
+
}
|
|
6646
|
+
return { type: "op", op: word, start, end: pos };
|
|
6647
|
+
};
|
|
6648
|
+
const tokens = [];
|
|
6649
|
+
let tok;
|
|
6650
|
+
while ((tok = readToken()) !== null) {
|
|
6651
|
+
tokens.push(tok);
|
|
6350
6652
|
}
|
|
6351
|
-
|
|
6352
|
-
out.set(check.subarray(0, 16), 0);
|
|
6353
|
-
out.set(PDF_PASSWORD_PADDING.subarray(0, 16), 16);
|
|
6354
|
-
return out;
|
|
6653
|
+
return tokens;
|
|
6355
6654
|
}
|
|
6356
|
-
function
|
|
6357
|
-
const
|
|
6358
|
-
|
|
6359
|
-
|
|
6360
|
-
|
|
6361
|
-
|
|
6362
|
-
|
|
6363
|
-
|
|
6364
|
-
);
|
|
6365
|
-
const expectedU = computeUserPasswordValue(candidateKey, fileId, revision);
|
|
6366
|
-
const compareLen = revision >= 3 ? 16 : 32;
|
|
6367
|
-
if (uValue.byteLength < compareLen) return null;
|
|
6368
|
-
let diff = 0;
|
|
6369
|
-
for (let i = 0; i < compareLen; i++) {
|
|
6370
|
-
diff |= expectedU[i] ^ uValue[i];
|
|
6655
|
+
function estimateTextAdvanceInTextSpace(text, state) {
|
|
6656
|
+
const fs = Math.abs(state.fontSize) || 12;
|
|
6657
|
+
const scaleH = state.horizScaling / 100;
|
|
6658
|
+
let adv = 0;
|
|
6659
|
+
for (const ch of text) {
|
|
6660
|
+
const cp = ch.codePointAt(0) ?? 32;
|
|
6661
|
+
const glyphW = cp > 127 ? fs : fs * 0.54;
|
|
6662
|
+
adv += (glyphW + state.charSpacing + (cp === 32 ? state.wordSpacing : 0)) * scaleH;
|
|
6371
6663
|
}
|
|
6372
|
-
return
|
|
6664
|
+
return adv;
|
|
6373
6665
|
}
|
|
6374
|
-
function
|
|
6375
|
-
|
|
6376
|
-
|
|
6377
|
-
|
|
6378
|
-
|
|
6379
|
-
|
|
6666
|
+
function parsePdfContentStreamTextOps(doc, streamBytes, resourcesDict, mediaBox, initialCtm = [1, 0, 0, 1, 0, 0], isTopLevelStream = true, depth = 0) {
|
|
6667
|
+
if (streamBytes.byteLength === 0 || depth > 5) return [];
|
|
6668
|
+
const fonts = extractResourcesFontMap(doc, resourcesDict);
|
|
6669
|
+
const tokens = tokenizeContentStream(streamBytes);
|
|
6670
|
+
const results = [];
|
|
6671
|
+
const stateStack = [];
|
|
6672
|
+
let state = {
|
|
6673
|
+
ctm: [...initialCtm],
|
|
6674
|
+
fontName: "",
|
|
6675
|
+
fontSize: 12,
|
|
6676
|
+
charSpacing: 0,
|
|
6677
|
+
wordSpacing: 0,
|
|
6678
|
+
horizScaling: 100,
|
|
6679
|
+
leading: 0,
|
|
6680
|
+
textRise: 0
|
|
6681
|
+
};
|
|
6682
|
+
let textMatrix = [1, 0, 0, 1, 0, 0];
|
|
6683
|
+
let textLineMatrix = [1, 0, 0, 1, 0, 0];
|
|
6684
|
+
const operands = [];
|
|
6685
|
+
const emitTextSpan = (rawText, textSpaceAdvance, opStart, opEnd) => {
|
|
6686
|
+
const trimmed = rawText.replace(/\0/g, "");
|
|
6687
|
+
if (!trimmed.trim()) {
|
|
6688
|
+
textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
|
|
6689
|
+
return;
|
|
6380
6690
|
}
|
|
6381
|
-
|
|
6382
|
-
|
|
6383
|
-
|
|
6384
|
-
|
|
6385
|
-
|
|
6386
|
-
const
|
|
6387
|
-
|
|
6388
|
-
|
|
6389
|
-
|
|
6691
|
+
const combined = multiplyPdfMatrix(textMatrix, state.ctm);
|
|
6692
|
+
const bx = combined[4];
|
|
6693
|
+
const by = combined[5] + state.textRise;
|
|
6694
|
+
const scaleX = Math.hypot(combined[0], combined[1]) || 1;
|
|
6695
|
+
const scaleY = Math.hypot(combined[2], combined[3]) || 1;
|
|
6696
|
+
const effectiveFontSize = Math.round(Math.max(1, (Math.abs(state.fontSize) || 12) * scaleY) * 100) / 100;
|
|
6697
|
+
const widthPt = Math.max(4, Math.abs(textSpaceAdvance * scaleX));
|
|
6698
|
+
const heightPt = Math.max(8, effectiveFontSize * 1.2);
|
|
6699
|
+
const left = Math.round((bx - mediaBox.x) * 100) / 100;
|
|
6700
|
+
const top = Math.round(Math.max(0, mediaBox.height - (by - mediaBox.y) - effectiveFontSize * 0.85) * 100) / 100;
|
|
6701
|
+
results.push({
|
|
6702
|
+
text: trimmed,
|
|
6703
|
+
left,
|
|
6704
|
+
top,
|
|
6705
|
+
width: Math.round(widthPt * 100) / 100,
|
|
6706
|
+
height: Math.round(heightPt * 100) / 100,
|
|
6707
|
+
fontSize: effectiveFontSize,
|
|
6708
|
+
...isTopLevelStream ? { streamStartOffset: opStart, streamEndOffset: opEnd } : {}
|
|
6709
|
+
});
|
|
6710
|
+
textMatrix = multiplyPdfMatrix([1, 0, 0, 1, textSpaceAdvance, 0], textMatrix);
|
|
6711
|
+
};
|
|
6712
|
+
for (const tok of tokens) {
|
|
6713
|
+
if (tok.type !== "op") {
|
|
6714
|
+
operands.push(tok);
|
|
6715
|
+
continue;
|
|
6716
|
+
}
|
|
6717
|
+
const op = tok.op;
|
|
6718
|
+
const opStart = operands.length > 0 ? operands[0].start : tok.start;
|
|
6719
|
+
const opEnd = tok.end;
|
|
6720
|
+
switch (op) {
|
|
6721
|
+
case "q": {
|
|
6722
|
+
stateStack.push({ ...state, ctm: [...state.ctm] });
|
|
6723
|
+
break;
|
|
6724
|
+
}
|
|
6725
|
+
case "Q": {
|
|
6726
|
+
const popped = stateStack.pop();
|
|
6727
|
+
if (popped) state = popped;
|
|
6728
|
+
break;
|
|
6729
|
+
}
|
|
6730
|
+
case "cm": {
|
|
6731
|
+
if (operands.length >= 6) {
|
|
6732
|
+
const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
|
|
6733
|
+
const m = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
|
|
6734
|
+
state.ctm = multiplyPdfMatrix(m, state.ctm);
|
|
6735
|
+
}
|
|
6736
|
+
break;
|
|
6737
|
+
}
|
|
6738
|
+
case "BT": {
|
|
6739
|
+
textMatrix = [1, 0, 0, 1, 0, 0];
|
|
6740
|
+
textLineMatrix = [1, 0, 0, 1, 0, 0];
|
|
6741
|
+
break;
|
|
6742
|
+
}
|
|
6743
|
+
case "ET": {
|
|
6744
|
+
break;
|
|
6745
|
+
}
|
|
6746
|
+
case "Tf": {
|
|
6747
|
+
if (operands.length >= 2) {
|
|
6748
|
+
const nameTok = operands[operands.length - 2];
|
|
6749
|
+
const sizeTok = operands[operands.length - 1];
|
|
6750
|
+
if (nameTok.type === "name") state.fontName = nameTok.value;
|
|
6751
|
+
if (sizeTok.type === "number") state.fontSize = sizeTok.num;
|
|
6752
|
+
}
|
|
6753
|
+
break;
|
|
6754
|
+
}
|
|
6755
|
+
case "Tc": {
|
|
6756
|
+
const last = operands[operands.length - 1];
|
|
6757
|
+
if (last?.type === "number") state.charSpacing = last.num;
|
|
6758
|
+
break;
|
|
6759
|
+
}
|
|
6760
|
+
case "Tw": {
|
|
6761
|
+
const last = operands[operands.length - 1];
|
|
6762
|
+
if (last?.type === "number") state.wordSpacing = last.num;
|
|
6763
|
+
break;
|
|
6764
|
+
}
|
|
6765
|
+
case "Tz": {
|
|
6766
|
+
const last = operands[operands.length - 1];
|
|
6767
|
+
if (last?.type === "number") state.horizScaling = last.num;
|
|
6768
|
+
break;
|
|
6769
|
+
}
|
|
6770
|
+
case "TL": {
|
|
6771
|
+
const last = operands[operands.length - 1];
|
|
6772
|
+
if (last?.type === "number") state.leading = last.num;
|
|
6773
|
+
break;
|
|
6774
|
+
}
|
|
6775
|
+
case "Ts": {
|
|
6776
|
+
const last = operands[operands.length - 1];
|
|
6777
|
+
if (last?.type === "number") state.textRise = last.num;
|
|
6778
|
+
break;
|
|
6779
|
+
}
|
|
6780
|
+
case "Td":
|
|
6781
|
+
case "TD": {
|
|
6782
|
+
if (operands.length >= 2) {
|
|
6783
|
+
const txTok = operands[operands.length - 2];
|
|
6784
|
+
const tyTok = operands[operands.length - 1];
|
|
6785
|
+
const tx = txTok.type === "number" ? txTok.num : 0;
|
|
6786
|
+
const ty = tyTok.type === "number" ? tyTok.num : 0;
|
|
6787
|
+
if (op === "TD") state.leading = -ty;
|
|
6788
|
+
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, tx, ty], textLineMatrix);
|
|
6789
|
+
textMatrix = [...textLineMatrix];
|
|
6790
|
+
}
|
|
6791
|
+
break;
|
|
6792
|
+
}
|
|
6793
|
+
case "Tm": {
|
|
6794
|
+
if (operands.length >= 6) {
|
|
6795
|
+
const nums = operands.slice(-6).map((o) => o.type === "number" ? o.num : 0);
|
|
6796
|
+
textMatrix = [nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]];
|
|
6797
|
+
textLineMatrix = [...textMatrix];
|
|
6798
|
+
}
|
|
6799
|
+
break;
|
|
6800
|
+
}
|
|
6801
|
+
case "T*": {
|
|
6802
|
+
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
|
|
6803
|
+
textMatrix = [...textLineMatrix];
|
|
6804
|
+
break;
|
|
6805
|
+
}
|
|
6806
|
+
case "Tj":
|
|
6807
|
+
case "'":
|
|
6808
|
+
case '"': {
|
|
6809
|
+
if (op === "'" || op === '"') {
|
|
6810
|
+
if (op === '"' && operands.length >= 3) {
|
|
6811
|
+
const twTok = operands[operands.length - 3];
|
|
6812
|
+
const tcTok = operands[operands.length - 2];
|
|
6813
|
+
if (twTok.type === "number") state.wordSpacing = twTok.num;
|
|
6814
|
+
if (tcTok.type === "number") state.charSpacing = tcTok.num;
|
|
6815
|
+
}
|
|
6816
|
+
textLineMatrix = multiplyPdfMatrix([1, 0, 0, 1, 0, -state.leading], textLineMatrix);
|
|
6817
|
+
textMatrix = [...textLineMatrix];
|
|
6818
|
+
}
|
|
6819
|
+
const strTok = operands[operands.length - 1];
|
|
6820
|
+
if (strTok && (strTok.type === "literal" || strTok.type === "hex")) {
|
|
6821
|
+
const fontInfo = fonts.get(state.fontName);
|
|
6822
|
+
const { text } = decodePdfStringBytes(strTok.bytes, fontInfo);
|
|
6823
|
+
const adv = estimateTextAdvanceInTextSpace(text, state);
|
|
6824
|
+
emitTextSpan(text, adv, opStart, opEnd);
|
|
6825
|
+
}
|
|
6826
|
+
break;
|
|
6390
6827
|
}
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
|
|
6398
|
-
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
buf[n + 3] = generationNumber & 255;
|
|
6414
|
-
buf[n + 4] = generationNumber >>> 8 & 255;
|
|
6415
|
-
const digest = md5Bytes(buf);
|
|
6416
|
-
return digest.subarray(0, Math.min(n + 5, 16));
|
|
6417
|
-
}
|
|
6418
|
-
function decodePdfLiteralBodyBytes(body) {
|
|
6419
|
-
const bytes = [];
|
|
6420
|
-
for (let i = 0; i < body.length; i++) {
|
|
6421
|
-
const ch = body.charCodeAt(i) & 255;
|
|
6422
|
-
if (ch !== 92) {
|
|
6423
|
-
bytes.push(ch);
|
|
6424
|
-
continue;
|
|
6425
|
-
}
|
|
6426
|
-
if (i + 1 >= body.length) break;
|
|
6427
|
-
const next = body.charCodeAt(++i) & 255;
|
|
6428
|
-
if (next === 13) {
|
|
6429
|
-
if (i + 1 < body.length && (body.charCodeAt(i + 1) & 255) === 10) i++;
|
|
6430
|
-
} else if (next === 10) {
|
|
6431
|
-
} else if (next === 110) {
|
|
6432
|
-
bytes.push(10);
|
|
6433
|
-
} else if (next === 114) {
|
|
6434
|
-
bytes.push(13);
|
|
6435
|
-
} else if (next === 116) {
|
|
6436
|
-
bytes.push(9);
|
|
6437
|
-
} else if (next === 98) {
|
|
6438
|
-
bytes.push(8);
|
|
6439
|
-
} else if (next === 102) {
|
|
6440
|
-
bytes.push(12);
|
|
6441
|
-
} else if (next >= 48 && next <= 55) {
|
|
6442
|
-
let oct = String.fromCharCode(next);
|
|
6443
|
-
for (let k = 0; k < 2 && i + 1 < body.length; k++) {
|
|
6444
|
-
const peek = body.charCodeAt(i + 1) & 255;
|
|
6445
|
-
if (peek >= 48 && peek <= 55) {
|
|
6446
|
-
oct += String.fromCharCode(peek);
|
|
6447
|
-
i++;
|
|
6448
|
-
} else {
|
|
6449
|
-
break;
|
|
6828
|
+
case "TJ": {
|
|
6829
|
+
const arrTok = operands[operands.length - 1];
|
|
6830
|
+
if (arrTok?.type === "array") {
|
|
6831
|
+
const fontInfo = fonts.get(state.fontName);
|
|
6832
|
+
const fs = Math.abs(state.fontSize) || 12;
|
|
6833
|
+
const scaleH = state.horizScaling / 100;
|
|
6834
|
+
let joined = "";
|
|
6835
|
+
let totalAdv = 0;
|
|
6836
|
+
for (const item of arrTok.items) {
|
|
6837
|
+
if (item.type === "literal" || item.type === "hex") {
|
|
6838
|
+
const { text } = decodePdfStringBytes(item.bytes, fontInfo);
|
|
6839
|
+
joined += text;
|
|
6840
|
+
totalAdv += estimateTextAdvanceInTextSpace(text, state);
|
|
6841
|
+
} else if (item.type === "number") {
|
|
6842
|
+
const shift = -item.num / 1e3 * fs * scaleH;
|
|
6843
|
+
totalAdv += shift;
|
|
6844
|
+
if (item.num < -180 && joined.length > 0 && !joined.endsWith(" ")) {
|
|
6845
|
+
joined += " ";
|
|
6846
|
+
}
|
|
6847
|
+
}
|
|
6848
|
+
}
|
|
6849
|
+
emitTextSpan(joined, totalAdv, opStart, opEnd);
|
|
6450
6850
|
}
|
|
6851
|
+
break;
|
|
6451
6852
|
}
|
|
6452
|
-
|
|
6453
|
-
|
|
6454
|
-
|
|
6853
|
+
case "Do": {
|
|
6854
|
+
const nameTok = operands[operands.length - 1];
|
|
6855
|
+
if (nameTok?.type === "name" && resourcesDict) {
|
|
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") {
|
|
6863
|
+
const formBytes = decodeSingleStreamObject(doc, resolvedXObj);
|
|
6864
|
+
const formRes = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName2.of("Resources")), PDFDict2) ?? resourcesDict;
|
|
6865
|
+
let formMat = [...state.ctm];
|
|
6866
|
+
const matArr = doc.context.lookupMaybe(resolvedXObj.dict.get(PDFName2.of("Matrix")), PDFArray2);
|
|
6867
|
+
if (matArr && matArr.size() >= 6) {
|
|
6868
|
+
const nums = [];
|
|
6869
|
+
for (let k = 0; k < 6; k++) {
|
|
6870
|
+
const nObj = matArr.get(k);
|
|
6871
|
+
nums.push(nObj instanceof PDFNumber2 ? nObj.asNumber() : 0);
|
|
6872
|
+
}
|
|
6873
|
+
formMat = multiplyPdfMatrix(
|
|
6874
|
+
[nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]],
|
|
6875
|
+
state.ctm
|
|
6876
|
+
);
|
|
6877
|
+
}
|
|
6878
|
+
const subSpans = parsePdfContentStreamTextOps(
|
|
6879
|
+
doc,
|
|
6880
|
+
formBytes,
|
|
6881
|
+
formRes,
|
|
6882
|
+
mediaBox,
|
|
6883
|
+
formMat,
|
|
6884
|
+
false,
|
|
6885
|
+
depth + 1
|
|
6886
|
+
);
|
|
6887
|
+
results.push(...subSpans);
|
|
6888
|
+
}
|
|
6889
|
+
}
|
|
6890
|
+
}
|
|
6891
|
+
break;
|
|
6892
|
+
}
|
|
6893
|
+
default:
|
|
6894
|
+
break;
|
|
6455
6895
|
}
|
|
6896
|
+
operands.length = 0;
|
|
6456
6897
|
}
|
|
6457
|
-
return
|
|
6458
|
-
}
|
|
6459
|
-
function extractPdfStringRawBytes(strObj) {
|
|
6460
|
-
if (strObj instanceof PDFHexString) {
|
|
6461
|
-
return strObj.asBytes();
|
|
6462
|
-
}
|
|
6463
|
-
const serialized = strObj.asString();
|
|
6464
|
-
const inner = serialized.startsWith("(") && serialized.endsWith(")") ? serialized.slice(1, -1) : serialized;
|
|
6465
|
-
return decodePdfLiteralBodyBytes(inner);
|
|
6466
|
-
}
|
|
6467
|
-
function isSignatureDict(dict) {
|
|
6468
|
-
const typeVal = dict.get(PDFName2.of("Type"));
|
|
6469
|
-
if (typeVal instanceof PDFName2 && typeVal.asString() === "/Sig") return true;
|
|
6470
|
-
const ftVal = dict.get(PDFName2.of("FT"));
|
|
6471
|
-
if (ftVal instanceof PDFName2 && ftVal.asString() === "/Sig") return true;
|
|
6472
|
-
return false;
|
|
6898
|
+
return results;
|
|
6473
6899
|
}
|
|
6474
|
-
function
|
|
6475
|
-
|
|
6476
|
-
|
|
6477
|
-
|
|
6478
|
-
|
|
6479
|
-
|
|
6480
|
-
|
|
6481
|
-
|
|
6482
|
-
const item = obj.get(i);
|
|
6483
|
-
const next = transformPdfObjectStringsWithRc4(item, objKey);
|
|
6484
|
-
if (next !== item) {
|
|
6485
|
-
obj.set(i, next);
|
|
6486
|
-
}
|
|
6900
|
+
async function tryExtractViaPdfjsFallback(pdfBytes, pageIds) {
|
|
6901
|
+
const globalPdfjs = globalThis?.pdfjsLib;
|
|
6902
|
+
let pdfjsLib = globalPdfjs;
|
|
6903
|
+
if (!pdfjsLib && typeof window !== "undefined" && typeof document !== "undefined") {
|
|
6904
|
+
try {
|
|
6905
|
+
pdfjsLib = await import("pdfjs-dist");
|
|
6906
|
+
} catch {
|
|
6907
|
+
pdfjsLib = null;
|
|
6487
6908
|
}
|
|
6488
|
-
return obj;
|
|
6489
6909
|
}
|
|
6490
|
-
if (
|
|
6491
|
-
|
|
6492
|
-
|
|
6493
|
-
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
|
|
6498
|
-
|
|
6910
|
+
if (!pdfjsLib || typeof pdfjsLib.getDocument !== "function") return null;
|
|
6911
|
+
try {
|
|
6912
|
+
const globalAssets = globalThis?.__YUDAO_UNIVER_PDFJS_ASSETS__;
|
|
6913
|
+
const loadingTask = pdfjsLib.getDocument({
|
|
6914
|
+
data: pdfBytes.slice(),
|
|
6915
|
+
disableWorker: true,
|
|
6916
|
+
isEvalSupported: false,
|
|
6917
|
+
...globalAssets?.cMapUrl ? { cMapUrl: globalAssets.cMapUrl, cMapPacked: globalAssets.cMapPacked ?? true } : {},
|
|
6918
|
+
...globalAssets?.standardFontDataUrl ? { standardFontDataUrl: globalAssets.standardFontDataUrl } : {}
|
|
6919
|
+
});
|
|
6920
|
+
const pdfDoc = await loadingTask.promise;
|
|
6921
|
+
const out = {};
|
|
6922
|
+
for (let i = 0; i < pdfDoc.numPages; i++) {
|
|
6923
|
+
const pageId = pageIds[i] ?? `page-${i + 1}`;
|
|
6924
|
+
const page = await pdfDoc.getPage(i + 1);
|
|
6925
|
+
const viewport = page.getViewport({ scale: 1 });
|
|
6926
|
+
const content = await page.getTextContent();
|
|
6927
|
+
const spans = [];
|
|
6928
|
+
let idx = 0;
|
|
6929
|
+
for (const item of content.items ?? []) {
|
|
6930
|
+
const str = typeof item.str === "string" ? item.str : "";
|
|
6931
|
+
if (!str.trim() || !Array.isArray(item.transform)) continue;
|
|
6932
|
+
const tr = item.transform;
|
|
6933
|
+
const fontSize = Math.round((Math.hypot(tr[2] ?? 0, tr[3] ?? 12) || 12) * 100) / 100;
|
|
6934
|
+
const width = Math.round(Math.max(4, Number(item.width) || str.length * fontSize * 0.55) * 100) / 100;
|
|
6935
|
+
const height = Math.round(Math.max(8, Number(item.height) || fontSize * 1.2) * 100) / 100;
|
|
6936
|
+
const left = Math.round((Number(tr[4]) || 0) * 100) / 100;
|
|
6937
|
+
const baselineFromBottom = Number(tr[5]) || 0;
|
|
6938
|
+
const top = Math.round(Math.max(0, viewport.height - baselineFromBottom - fontSize * 0.85) * 100) / 100;
|
|
6939
|
+
idx++;
|
|
6940
|
+
spans.push({
|
|
6941
|
+
id: `native-${pageId}-${idx}`,
|
|
6942
|
+
pageId,
|
|
6943
|
+
pageIndex: i,
|
|
6944
|
+
text: str,
|
|
6945
|
+
left,
|
|
6946
|
+
top,
|
|
6947
|
+
width,
|
|
6948
|
+
height,
|
|
6949
|
+
fontSize,
|
|
6950
|
+
suppressed: false
|
|
6951
|
+
});
|
|
6499
6952
|
}
|
|
6953
|
+
out[pageId] = spans;
|
|
6500
6954
|
}
|
|
6501
|
-
|
|
6955
|
+
if (typeof pdfDoc.destroy === "function") {
|
|
6956
|
+
await pdfDoc.destroy();
|
|
6957
|
+
}
|
|
6958
|
+
return out;
|
|
6959
|
+
} catch {
|
|
6960
|
+
return null;
|
|
6502
6961
|
}
|
|
6503
|
-
return obj;
|
|
6504
6962
|
}
|
|
6505
|
-
function
|
|
6506
|
-
const
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
|
|
6513
|
-
|
|
6514
|
-
|
|
6515
|
-
|
|
6516
|
-
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6963
|
+
async function extractNativeTextSpansFromPdfBytes(pdfBytes, pageIds) {
|
|
6964
|
+
const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
6965
|
+
const pages = doc.getPages();
|
|
6966
|
+
const effectivePageIds = pages.map((_, idx) => pageIds?.[idx] || `page-${idx + 1}`);
|
|
6967
|
+
const spansByPage = {};
|
|
6968
|
+
let anyPageEmpty = false;
|
|
6969
|
+
for (let pIdx = 0; pIdx < pages.length; pIdx++) {
|
|
6970
|
+
const page = pages[pIdx];
|
|
6971
|
+
const pageId = effectivePageIds[pIdx];
|
|
6972
|
+
const mediaBox = page.getMediaBox();
|
|
6973
|
+
const contentsBytes = decodeContentsEntry(doc, page.node.Contents());
|
|
6974
|
+
const resourcesDict = page.node.Resources();
|
|
6975
|
+
const rawOps = parsePdfContentStreamTextOps(doc, contentsBytes, resourcesDict, mediaBox);
|
|
6976
|
+
const pageSpans = rawOps.map((op, sIdx) => ({
|
|
6977
|
+
id: `native-${pageId}-${sIdx + 1}`,
|
|
6978
|
+
pageId,
|
|
6979
|
+
pageIndex: pIdx,
|
|
6980
|
+
text: op.text,
|
|
6981
|
+
left: op.left,
|
|
6982
|
+
top: op.top,
|
|
6983
|
+
width: op.width,
|
|
6984
|
+
height: op.height,
|
|
6985
|
+
fontSize: op.fontSize,
|
|
6986
|
+
suppressed: false
|
|
6987
|
+
}));
|
|
6988
|
+
if (pageSpans.length === 0 && contentsBytes.byteLength > 0) {
|
|
6989
|
+
anyPageEmpty = true;
|
|
6990
|
+
}
|
|
6991
|
+
spansByPage[pageId] = pageSpans;
|
|
6992
|
+
}
|
|
6993
|
+
if (anyPageEmpty) {
|
|
6994
|
+
const pdfjsResult = await tryExtractViaPdfjsFallback(pdfBytes, effectivePageIds);
|
|
6995
|
+
if (pdfjsResult) {
|
|
6996
|
+
for (const pageId of effectivePageIds) {
|
|
6997
|
+
if ((spansByPage[pageId]?.length ?? 0) === 0 && (pdfjsResult[pageId]?.length ?? 0) > 0) {
|
|
6998
|
+
spansByPage[pageId] = pdfjsResult[pageId];
|
|
6520
6999
|
}
|
|
6521
7000
|
}
|
|
6522
7001
|
}
|
|
6523
7002
|
}
|
|
6524
|
-
|
|
6525
|
-
if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
|
|
6526
|
-
globalThis.crypto.getRandomValues(seedBytes);
|
|
6527
|
-
} else {
|
|
6528
|
-
const fallbackText = `univer-pdf-${Date.now()}-${Math.random()}-${pdfDoc.getPageCount()}`;
|
|
6529
|
-
const enc = new TextEncoder().encode(fallbackText);
|
|
6530
|
-
seedBytes.set(enc.subarray(0, Math.min(32, enc.byteLength)));
|
|
6531
|
-
}
|
|
6532
|
-
const fileId = md5Bytes(seedBytes);
|
|
6533
|
-
const idHex = bytesToHex(fileId);
|
|
6534
|
-
pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
|
|
6535
|
-
PDFHexString.of(idHex),
|
|
6536
|
-
PDFHexString.of(idHex)
|
|
6537
|
-
]);
|
|
6538
|
-
return fileId;
|
|
7003
|
+
return spansByPage;
|
|
6539
7004
|
}
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
|
|
6543
|
-
const
|
|
6544
|
-
const
|
|
6545
|
-
|
|
6546
|
-
|
|
6547
|
-
|
|
6548
|
-
|
|
6549
|
-
const
|
|
6550
|
-
|
|
6551
|
-
const
|
|
6552
|
-
|
|
6553
|
-
|
|
6554
|
-
|
|
6555
|
-
fileId,
|
|
6556
|
-
revision,
|
|
6557
|
-
keyLength
|
|
7005
|
+
function rectsIntersect(a, b) {
|
|
7006
|
+
const ax2 = a.left + a.width;
|
|
7007
|
+
const ay2 = a.top + a.height;
|
|
7008
|
+
const bx2 = b.left + b.width;
|
|
7009
|
+
const by2 = b.top + b.height;
|
|
7010
|
+
return !(ax2 <= b.left || a.left >= bx2 || ay2 <= b.top || a.top >= by2);
|
|
7011
|
+
}
|
|
7012
|
+
function stripPdfPageNativeTextInRects(doc, page, stripRects) {
|
|
7013
|
+
if (!stripRects.length) return 0;
|
|
7014
|
+
const contentsBytes = decodeContentsEntry(doc, page.node.Contents());
|
|
7015
|
+
if (contentsBytes.byteLength === 0) return 0;
|
|
7016
|
+
const mediaBox = page.getMediaBox();
|
|
7017
|
+
const ops = parsePdfContentStreamTextOps(doc, contentsBytes, page.node.Resources(), mediaBox, [1, 0, 0, 1, 0, 0], true);
|
|
7018
|
+
const matchingOps = ops.filter(
|
|
7019
|
+
(op) => op.streamStartOffset !== void 0 && op.streamEndOffset !== void 0 && stripRects.some((r) => rectsIntersect(op, r))
|
|
6558
7020
|
);
|
|
6559
|
-
|
|
6560
|
-
const
|
|
6561
|
-
for (const
|
|
6562
|
-
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
|
|
6566
|
-
if (obj instanceof PDFRawStream2) {
|
|
6567
|
-
transformPdfObjectStringsWithRc4(obj.dict, objKey);
|
|
6568
|
-
const encryptedStream = rc4Bytes(objKey, obj.contents);
|
|
6569
|
-
obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(encryptedStream.byteLength));
|
|
6570
|
-
pdfDoc.context.assign(ref, PDFRawStream2.of(obj.dict, encryptedStream));
|
|
6571
|
-
} else if (obj instanceof PDFStream2) {
|
|
6572
|
-
transformPdfObjectStringsWithRc4(obj.dict, objKey);
|
|
6573
|
-
const encodedContents = obj.getContents();
|
|
6574
|
-
const encryptedStream = rc4Bytes(objKey, encodedContents);
|
|
6575
|
-
obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(encryptedStream.byteLength));
|
|
6576
|
-
pdfDoc.context.assign(ref, PDFRawStream2.of(obj.dict, encryptedStream));
|
|
6577
|
-
} else {
|
|
6578
|
-
const next = transformPdfObjectStringsWithRc4(obj, objKey);
|
|
6579
|
-
if (next !== obj) {
|
|
6580
|
-
pdfDoc.context.assign(ref, next);
|
|
7021
|
+
if (matchingOps.length === 0) return 0;
|
|
7022
|
+
const sanitized = contentsBytes.slice();
|
|
7023
|
+
for (const op of matchingOps) {
|
|
7024
|
+
for (let i = op.streamStartOffset; i < op.streamEndOffset; i++) {
|
|
7025
|
+
if (sanitized[i] !== 10 && sanitized[i] !== 13) {
|
|
7026
|
+
sanitized[i] = 32;
|
|
6581
7027
|
}
|
|
6582
7028
|
}
|
|
6583
7029
|
}
|
|
6584
|
-
const
|
|
6585
|
-
|
|
6586
|
-
|
|
6587
|
-
|
|
6588
|
-
Length: PDFNumber2.of(keyLength),
|
|
6589
|
-
P: PDFNumber2.of(pSigned),
|
|
6590
|
-
O: PDFHexString.of(bytesToHex(oBytes)),
|
|
6591
|
-
U: PDFHexString.of(bytesToHex(uBytes))
|
|
6592
|
-
});
|
|
6593
|
-
const encryptRef = pdfDoc.context.register(encryptDict);
|
|
6594
|
-
pdfDoc.context.trailerInfo.Encrypt = encryptRef;
|
|
6595
|
-
}
|
|
6596
|
-
async function encryptPdfBytes(pdfBytes, security) {
|
|
6597
|
-
if (!security || security.enabled === false) {
|
|
6598
|
-
return pdfBytes.slice();
|
|
6599
|
-
}
|
|
6600
|
-
const cleanBytes = inspectPdfEncryption(pdfBytes).encrypted ? await decryptPdfBytes(pdfBytes, security.ownerPassword || security.userPassword || "") : pdfBytes;
|
|
6601
|
-
const pdfDoc = await PDFDocument2.load(cleanBytes, { updateMetadata: false });
|
|
6602
|
-
await applyPdfSecurityToDocument(pdfDoc, security);
|
|
6603
|
-
return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false });
|
|
7030
|
+
const newStream = doc.context.flateStream(sanitized);
|
|
7031
|
+
const newRef = doc.context.register(newStream);
|
|
7032
|
+
page.node.set(PDFName2.of("Contents"), newRef);
|
|
7033
|
+
return matchingOps.length;
|
|
6604
7034
|
}
|
|
6605
|
-
function
|
|
6606
|
-
|
|
6607
|
-
|
|
6608
|
-
for (let i = 0; i < bytes.byteLength; i += chunk) {
|
|
6609
|
-
out += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
7035
|
+
async function mergePdfBytes(pdfList) {
|
|
7036
|
+
if (!Array.isArray(pdfList) || pdfList.length === 0) {
|
|
7037
|
+
throw new Error("[UniverPdfs] mergePdfBytes requires at least one PDF Uint8Array.");
|
|
6610
7038
|
}
|
|
6611
|
-
|
|
6612
|
-
|
|
6613
|
-
|
|
6614
|
-
|
|
6615
|
-
|
|
6616
|
-
|
|
6617
|
-
|
|
6618
|
-
|
|
6619
|
-
for (let i = openIdx; i < text.length; i++) {
|
|
6620
|
-
const ch = text.charCodeAt(i);
|
|
6621
|
-
if (inLiteral) {
|
|
6622
|
-
if (ch === 92) {
|
|
6623
|
-
i++;
|
|
6624
|
-
continue;
|
|
6625
|
-
}
|
|
6626
|
-
if (ch === 40) literalDepth++;
|
|
6627
|
-
else if (ch === 41) {
|
|
6628
|
-
literalDepth--;
|
|
6629
|
-
if (literalDepth <= 0) {
|
|
6630
|
-
inLiteral = false;
|
|
6631
|
-
}
|
|
7039
|
+
const mergedDoc = await PDFDocument2.create();
|
|
7040
|
+
for (const rawBytes of pdfList) {
|
|
7041
|
+
const srcDoc = await PDFDocument2.load(rawBytes, { ignoreEncryption: true });
|
|
7042
|
+
const indices = srcDoc.getPageIndices();
|
|
7043
|
+
if (indices.length > 0) {
|
|
7044
|
+
const copiedPages = await mergedDoc.copyPages(srcDoc, indices);
|
|
7045
|
+
for (const page of copiedPages) {
|
|
7046
|
+
mergedDoc.addPage(page);
|
|
6632
7047
|
}
|
|
6633
|
-
continue;
|
|
6634
|
-
}
|
|
6635
|
-
if (ch === 40) {
|
|
6636
|
-
inLiteral = true;
|
|
6637
|
-
literalDepth = 1;
|
|
6638
|
-
continue;
|
|
6639
7048
|
}
|
|
6640
|
-
|
|
6641
|
-
|
|
6642
|
-
|
|
6643
|
-
|
|
6644
|
-
|
|
7049
|
+
}
|
|
7050
|
+
return await mergedDoc.save();
|
|
7051
|
+
}
|
|
7052
|
+
async function splitPdfBytes(pdfBytes, ranges) {
|
|
7053
|
+
if (!Array.isArray(ranges) || ranges.length === 0) {
|
|
7054
|
+
return [];
|
|
7055
|
+
}
|
|
7056
|
+
const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
7057
|
+
const totalPages = srcDoc.getPageCount();
|
|
7058
|
+
const outputs = [];
|
|
7059
|
+
for (const range of ranges) {
|
|
7060
|
+
const start = Math.floor(range.startPage);
|
|
7061
|
+
const end = Math.floor(range.endPage);
|
|
7062
|
+
if (start < 1 || end < start || start > totalPages) {
|
|
7063
|
+
throw new Error(
|
|
7064
|
+
`[UniverPdfs] Invalid 1-based page range [${range.startPage}..${range.endPage}] for document with ${totalPages} page(s).`
|
|
7065
|
+
);
|
|
6645
7066
|
}
|
|
6646
|
-
|
|
6647
|
-
|
|
6648
|
-
|
|
6649
|
-
|
|
7067
|
+
const clampedEnd = Math.min(totalPages, end);
|
|
7068
|
+
const indices = [];
|
|
7069
|
+
for (let p = start; p <= clampedEnd; p++) {
|
|
7070
|
+
indices.push(p - 1);
|
|
6650
7071
|
}
|
|
6651
|
-
|
|
6652
|
-
|
|
6653
|
-
|
|
6654
|
-
|
|
6655
|
-
return text.slice(openIdx, i + 1);
|
|
6656
|
-
}
|
|
7072
|
+
const subDoc = await PDFDocument2.create();
|
|
7073
|
+
const copiedPages = await subDoc.copyPages(srcDoc, indices);
|
|
7074
|
+
for (const page of copiedPages) {
|
|
7075
|
+
subDoc.addPage(page);
|
|
6657
7076
|
}
|
|
7077
|
+
outputs.push(await subDoc.save());
|
|
6658
7078
|
}
|
|
6659
|
-
return
|
|
7079
|
+
return outputs;
|
|
6660
7080
|
}
|
|
6661
|
-
function
|
|
6662
|
-
|
|
6663
|
-
const
|
|
6664
|
-
if (!
|
|
6665
|
-
|
|
6666
|
-
while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
|
|
6667
|
-
if (pos >= dictText.length) return null;
|
|
6668
|
-
if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
|
|
6669
|
-
const close = dictText.indexOf(">", pos + 1);
|
|
6670
|
-
if (close < 0) return null;
|
|
6671
|
-
return hexToBytes(dictText.slice(pos + 1, close));
|
|
7081
|
+
function parsePdfPageRange(rangeExpr, totalPages) {
|
|
7082
|
+
if (totalPages <= 0) return [];
|
|
7083
|
+
const trimmed = (rangeExpr ?? "").trim();
|
|
7084
|
+
if (!trimmed || trimmed.toLowerCase() === "all" || trimmed === "*") {
|
|
7085
|
+
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
|
6672
7086
|
}
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
6676
|
-
|
|
6677
|
-
|
|
6678
|
-
if (ch === 92) {
|
|
6679
|
-
i += 2;
|
|
6680
|
-
continue;
|
|
6681
|
-
}
|
|
6682
|
-
if (ch === 40) depth++;
|
|
6683
|
-
else if (ch === 41) depth--;
|
|
6684
|
-
i++;
|
|
7087
|
+
const out = [];
|
|
7088
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7089
|
+
const addPage = (p) => {
|
|
7090
|
+
if (p < 1 || p > totalPages) {
|
|
7091
|
+
throw new Error(`[UniverPdfs] Page number ${p} is out of bounds (1..${totalPages}).`);
|
|
6685
7092
|
}
|
|
6686
|
-
if (
|
|
6687
|
-
|
|
7093
|
+
if (!seen.has(p)) {
|
|
7094
|
+
seen.add(p);
|
|
7095
|
+
out.push(p);
|
|
6688
7096
|
}
|
|
6689
|
-
}
|
|
6690
|
-
|
|
6691
|
-
|
|
6692
|
-
|
|
6693
|
-
|
|
6694
|
-
|
|
6695
|
-
|
|
6696
|
-
|
|
6697
|
-
|
|
6698
|
-
if (pos >= dictText.length) return null;
|
|
6699
|
-
if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
|
|
6700
|
-
const close = dictText.indexOf(">", pos + 1);
|
|
6701
|
-
if (close >= 0) return hexToBytes(dictText.slice(pos + 1, close));
|
|
6702
|
-
} else if (dictText[pos] === "(") {
|
|
6703
|
-
let depth = 1;
|
|
6704
|
-
let i = pos + 1;
|
|
6705
|
-
while (i < dictText.length && depth > 0) {
|
|
6706
|
-
const ch = dictText.charCodeAt(i);
|
|
6707
|
-
if (ch === 92) {
|
|
6708
|
-
i += 2;
|
|
6709
|
-
continue;
|
|
7097
|
+
};
|
|
7098
|
+
const parts = trimmed.split(",").map((s) => s.trim()).filter(Boolean);
|
|
7099
|
+
for (const part of parts) {
|
|
7100
|
+
const rangeMatch = /^(\d+)\s*-\s*(\d*)$/.exec(part);
|
|
7101
|
+
if (rangeMatch) {
|
|
7102
|
+
const start = parseInt(rangeMatch[1], 10);
|
|
7103
|
+
const end = rangeMatch[2] ? parseInt(rangeMatch[2], 10) : totalPages;
|
|
7104
|
+
if (start < 1 || end < start || end > totalPages) {
|
|
7105
|
+
throw new Error(`[UniverPdfs] Invalid page range "${part}" for ${totalPages}-page document.`);
|
|
6710
7106
|
}
|
|
6711
|
-
|
|
6712
|
-
|
|
6713
|
-
|
|
7107
|
+
for (let p = start; p <= end; p++) {
|
|
7108
|
+
addPage(p);
|
|
7109
|
+
}
|
|
7110
|
+
continue;
|
|
6714
7111
|
}
|
|
6715
|
-
if (
|
|
6716
|
-
|
|
7112
|
+
if (/^\d+$/.test(part)) {
|
|
7113
|
+
addPage(parseInt(part, 10));
|
|
7114
|
+
continue;
|
|
6717
7115
|
}
|
|
7116
|
+
throw new Error(`[UniverPdfs] Invalid page range token "${part}".`);
|
|
6718
7117
|
}
|
|
6719
|
-
return
|
|
7118
|
+
return out;
|
|
6720
7119
|
}
|
|
6721
|
-
function
|
|
6722
|
-
if (
|
|
6723
|
-
|
|
6724
|
-
|
|
6725
|
-
|
|
6726
|
-
|
|
6727
|
-
|
|
6728
|
-
|
|
6729
|
-
|
|
6730
|
-
|
|
6731
|
-
|
|
6732
|
-
|
|
6733
|
-
|
|
6734
|
-
|
|
6735
|
-
break;
|
|
6736
|
-
}
|
|
6737
|
-
if (candidate && !containerDict) {
|
|
6738
|
-
containerDict = candidate;
|
|
6739
|
-
}
|
|
7120
|
+
function resolveOneBasedPages(pages, totalPages) {
|
|
7121
|
+
if (typeof pages === "string") {
|
|
7122
|
+
return parsePdfPageRange(pages, totalPages);
|
|
7123
|
+
}
|
|
7124
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7125
|
+
const out = [];
|
|
7126
|
+
for (const raw of pages) {
|
|
7127
|
+
const p = Math.floor(raw);
|
|
7128
|
+
if (p < 1 || p > totalPages) {
|
|
7129
|
+
throw new Error(`[UniverPdfs] Page number ${raw} is out of bounds (1..${totalPages}).`);
|
|
7130
|
+
}
|
|
7131
|
+
if (!seen.has(p)) {
|
|
7132
|
+
seen.add(p);
|
|
7133
|
+
out.push(p);
|
|
6740
7134
|
}
|
|
6741
|
-
searchEnd = trailerIdx;
|
|
6742
7135
|
}
|
|
6743
|
-
|
|
6744
|
-
|
|
6745
|
-
|
|
6746
|
-
|
|
7136
|
+
return out;
|
|
7137
|
+
}
|
|
7138
|
+
async function removePdfPagesBytes(pdfBytes, pagesToRemove) {
|
|
7139
|
+
const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
7140
|
+
const totalPages = srcDoc.getPageCount();
|
|
7141
|
+
const removeSet = new Set(resolveOneBasedPages(pagesToRemove, totalPages));
|
|
7142
|
+
const keepIndices = [];
|
|
7143
|
+
for (let p = 1; p <= totalPages; p++) {
|
|
7144
|
+
if (!removeSet.has(p)) {
|
|
7145
|
+
keepIndices.push(p - 1);
|
|
6747
7146
|
}
|
|
6748
7147
|
}
|
|
6749
|
-
if (
|
|
6750
|
-
|
|
7148
|
+
if (keepIndices.length === 0) {
|
|
7149
|
+
throw new Error("[UniverPdfs] Cannot remove all pages from a PDF document.");
|
|
6751
7150
|
}
|
|
6752
|
-
|
|
6753
|
-
const
|
|
6754
|
-
|
|
6755
|
-
|
|
6756
|
-
|
|
6757
|
-
|
|
6758
|
-
|
|
6759
|
-
|
|
6760
|
-
|
|
6761
|
-
|
|
6762
|
-
|
|
6763
|
-
|
|
6764
|
-
|
|
7151
|
+
const outDoc = await PDFDocument2.create();
|
|
7152
|
+
const copied = await outDoc.copyPages(srcDoc, keepIndices);
|
|
7153
|
+
for (const page of copied) {
|
|
7154
|
+
outDoc.addPage(page);
|
|
7155
|
+
}
|
|
7156
|
+
return await outDoc.save();
|
|
7157
|
+
}
|
|
7158
|
+
async function insertPdfPagesBytes(basePdfBytes, insertPdfBytes, atPageIndex, sourcePages) {
|
|
7159
|
+
const baseDoc = await PDFDocument2.load(basePdfBytes, { ignoreEncryption: true });
|
|
7160
|
+
const insertDoc = await PDFDocument2.load(insertPdfBytes, { ignoreEncryption: true });
|
|
7161
|
+
const baseCount = baseDoc.getPageCount();
|
|
7162
|
+
const insertTotal = insertDoc.getPageCount();
|
|
7163
|
+
const targetIdx = atPageIndex === void 0 ? baseCount : Math.max(0, Math.min(baseCount, Math.floor(atPageIndex)));
|
|
7164
|
+
const srcOneBased = sourcePages ? resolveOneBasedPages(sourcePages, insertTotal) : Array.from({ length: insertTotal }, (_, i) => i + 1);
|
|
7165
|
+
const outDoc = await PDFDocument2.create();
|
|
7166
|
+
const beforeIndices = Array.from({ length: targetIdx }, (_, i) => i);
|
|
7167
|
+
const afterIndices = Array.from({ length: baseCount - targetIdx }, (_, i) => targetIdx + i);
|
|
7168
|
+
if (beforeIndices.length > 0) {
|
|
7169
|
+
for (const pg of await outDoc.copyPages(baseDoc, beforeIndices)) {
|
|
7170
|
+
outDoc.addPage(pg);
|
|
6765
7171
|
}
|
|
6766
|
-
} else if (/\/Encrypt\s*<</.test(containerDict)) {
|
|
6767
|
-
const inlineIdx = containerDict.search(/\/Encrypt\s*<</);
|
|
6768
|
-
encryptDictText = extractBalancedPdfDict(containerDict, inlineIdx);
|
|
6769
7172
|
}
|
|
6770
|
-
if (
|
|
6771
|
-
|
|
6772
|
-
|
|
6773
|
-
const rMatch = /\/R\s+(-?\d+)/.exec(encryptDictText);
|
|
6774
|
-
const lenMatch = /\/Length\s+(\d+)/.exec(encryptDictText);
|
|
6775
|
-
const pMatch = /\/P\s+(-?\d+)/.exec(encryptDictText);
|
|
6776
|
-
const filter = filterMatch ? filterMatch[1] : "Standard";
|
|
6777
|
-
const version = vMatch ? parseInt(vMatch[1], 10) : 1;
|
|
6778
|
-
const revision = rMatch ? parseInt(rMatch[1], 10) : version >= 2 ? 3 : 2;
|
|
6779
|
-
const keyLength = lenMatch ? parseInt(lenMatch[1], 10) : version >= 2 ? 128 : 40;
|
|
6780
|
-
const pSigned = pMatch ? parseInt(pMatch[1], 10) | 0 : -4;
|
|
6781
|
-
const oBytes = parsePdfStringTokenAfterKey(encryptDictText, "O") ?? new Uint8Array(0);
|
|
6782
|
-
const uBytes = parsePdfStringTokenAfterKey(encryptDictText, "U") ?? new Uint8Array(0);
|
|
6783
|
-
let fileId = parseFirstPdfArrayStringBytes(containerDict, "ID");
|
|
6784
|
-
if (!fileId) {
|
|
6785
|
-
const idRefMatch = /\/ID\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
|
|
6786
|
-
if (idRefMatch) {
|
|
6787
|
-
const idObjRe = new RegExp(`(?:^|[\\r\\n\\s])${idRefMatch[1]}\\s+${idRefMatch[2]}\\s+obj\\b([\\s\\S]{0,512}?)endobj`);
|
|
6788
|
-
const idObjM = idObjRe.exec(rawText);
|
|
6789
|
-
if (idObjM) {
|
|
6790
|
-
fileId = parseFirstPdfArrayStringBytes(`/ID ${idObjM[1]}`, "ID");
|
|
6791
|
-
}
|
|
7173
|
+
if (srcOneBased.length > 0) {
|
|
7174
|
+
for (const pg of await outDoc.copyPages(insertDoc, srcOneBased.map((p) => p - 1))) {
|
|
7175
|
+
outDoc.addPage(pg);
|
|
6792
7176
|
}
|
|
6793
7177
|
}
|
|
6794
|
-
|
|
6795
|
-
|
|
6796
|
-
|
|
6797
|
-
revision,
|
|
6798
|
-
keyLength,
|
|
6799
|
-
pSigned,
|
|
6800
|
-
oBytes,
|
|
6801
|
-
uBytes,
|
|
6802
|
-
fileId: fileId ?? new Uint8Array(0)
|
|
6803
|
-
};
|
|
6804
|
-
}
|
|
6805
|
-
function extractEncryptMetadataFromDoc(doc) {
|
|
6806
|
-
const encEntry = doc.context.trailerInfo.Encrypt;
|
|
6807
|
-
if (!encEntry) return null;
|
|
6808
|
-
const encDict = encEntry instanceof PDFDict2 ? encEntry : doc.context.lookupMaybe(encEntry, PDFDict2);
|
|
6809
|
-
if (!encDict) return null;
|
|
6810
|
-
const filterObj = encDict.get(PDFName2.of("Filter"));
|
|
6811
|
-
const filter = filterObj instanceof PDFName2 ? filterObj.decodeText() : "Standard";
|
|
6812
|
-
const vObj = encDict.get(PDFName2.of("V"));
|
|
6813
|
-
const version = vObj instanceof PDFNumber2 ? vObj.asNumber() : 1;
|
|
6814
|
-
const rObj = encDict.get(PDFName2.of("R"));
|
|
6815
|
-
const revision = rObj instanceof PDFNumber2 ? rObj.asNumber() : version >= 2 ? 3 : 2;
|
|
6816
|
-
const lenObj = encDict.get(PDFName2.of("Length"));
|
|
6817
|
-
const keyLength = lenObj instanceof PDFNumber2 ? lenObj.asNumber() : version >= 2 ? 128 : 40;
|
|
6818
|
-
const pObj = encDict.get(PDFName2.of("P"));
|
|
6819
|
-
const pSigned = pObj instanceof PDFNumber2 ? pObj.asNumber() | 0 : -4;
|
|
6820
|
-
const oObj = encDict.get(PDFName2.of("O"));
|
|
6821
|
-
const oBytes = oObj instanceof PDFHexString || oObj instanceof PDFString ? extractPdfStringRawBytes(oObj) : new Uint8Array(0);
|
|
6822
|
-
const uObj = encDict.get(PDFName2.of("U"));
|
|
6823
|
-
const uBytes = uObj instanceof PDFHexString || uObj instanceof PDFString ? extractPdfStringRawBytes(uObj) : new Uint8Array(0);
|
|
6824
|
-
let fileId = new Uint8Array(0);
|
|
6825
|
-
const idEntry = doc.context.trailerInfo.ID;
|
|
6826
|
-
const idArr = idEntry instanceof PDFArray2 ? idEntry : doc.context.lookupMaybe(idEntry, PDFArray2);
|
|
6827
|
-
if (idArr && idArr.size() > 0) {
|
|
6828
|
-
const first = idArr.get(0);
|
|
6829
|
-
if (first instanceof PDFHexString || first instanceof PDFString) {
|
|
6830
|
-
fileId = extractPdfStringRawBytes(first);
|
|
7178
|
+
if (afterIndices.length > 0) {
|
|
7179
|
+
for (const pg of await outDoc.copyPages(baseDoc, afterIndices)) {
|
|
7180
|
+
outDoc.addPage(pg);
|
|
6831
7181
|
}
|
|
6832
7182
|
}
|
|
6833
|
-
return
|
|
6834
|
-
filter,
|
|
6835
|
-
version,
|
|
6836
|
-
revision,
|
|
6837
|
-
keyLength,
|
|
6838
|
-
pSigned,
|
|
6839
|
-
oBytes,
|
|
6840
|
-
uBytes,
|
|
6841
|
-
fileId
|
|
6842
|
-
};
|
|
7183
|
+
return await outDoc.save();
|
|
6843
7184
|
}
|
|
6844
|
-
function
|
|
6845
|
-
const
|
|
6846
|
-
|
|
6847
|
-
|
|
6848
|
-
|
|
6849
|
-
|
|
6850
|
-
|
|
6851
|
-
|
|
7185
|
+
async function rotatePdfPagesBytes(pdfBytes, angleDeg, pages, options) {
|
|
7186
|
+
const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
7187
|
+
const totalPages = doc.getPageCount();
|
|
7188
|
+
const targets = pages ? resolveOneBasedPages(pages, totalPages) : Array.from({ length: totalPages }, (_, i) => i + 1);
|
|
7189
|
+
const isRelative = options?.relative !== false;
|
|
7190
|
+
for (const pNum of targets) {
|
|
7191
|
+
const page = doc.getPage(pNum - 1);
|
|
7192
|
+
const curAngle = page.getRotation().angle || 0;
|
|
7193
|
+
const nextAngle = isRelative ? ((curAngle + angleDeg) % 360 + 360) % 360 : (angleDeg % 360 + 360) % 360;
|
|
7194
|
+
page.setRotation(degrees(nextAngle));
|
|
6852
7195
|
}
|
|
6853
|
-
|
|
6854
|
-
|
|
6855
|
-
|
|
6856
|
-
|
|
6857
|
-
|
|
6858
|
-
|
|
6859
|
-
|
|
6860
|
-
|
|
6861
|
-
|
|
6862
|
-
|
|
7196
|
+
return await doc.save();
|
|
7197
|
+
}
|
|
7198
|
+
async function movePdfPageBytes(pdfBytes, fromPage, toPage) {
|
|
7199
|
+
const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
7200
|
+
const totalPages = srcDoc.getPageCount();
|
|
7201
|
+
const fromIdx = Math.floor(fromPage) - 1;
|
|
7202
|
+
const toIdx = Math.floor(toPage) - 1;
|
|
7203
|
+
if (fromIdx < 0 || fromIdx >= totalPages || toIdx < 0 || toIdx >= totalPages) {
|
|
7204
|
+
throw new Error(
|
|
7205
|
+
`[UniverPdfs] movePdfPageBytes indices (${fromPage} -> ${toPage}) out of bounds (1..${totalPages}).`
|
|
6863
7206
|
);
|
|
6864
|
-
requiresOpenPassword = emptyKey === null;
|
|
6865
7207
|
}
|
|
6866
|
-
|
|
6867
|
-
|
|
6868
|
-
|
|
6869
|
-
|
|
6870
|
-
|
|
6871
|
-
|
|
6872
|
-
|
|
6873
|
-
|
|
6874
|
-
|
|
6875
|
-
}
|
|
7208
|
+
if (fromIdx === toIdx) {
|
|
7209
|
+
return await srcDoc.save();
|
|
7210
|
+
}
|
|
7211
|
+
const order = Array.from({ length: totalPages }, (_, i) => i);
|
|
7212
|
+
const [moved] = order.splice(fromIdx, 1);
|
|
7213
|
+
order.splice(toIdx, 0, moved);
|
|
7214
|
+
const outDoc = await PDFDocument2.create();
|
|
7215
|
+
for (const pg of await outDoc.copyPages(srcDoc, order)) {
|
|
7216
|
+
outDoc.addPage(pg);
|
|
7217
|
+
}
|
|
7218
|
+
return await outDoc.save();
|
|
7219
|
+
}
|
|
7220
|
+
async function organizePdfBytes(pdfBytes, planOrOptions) {
|
|
7221
|
+
if (!Array.isArray(planOrOptions) && planOrOptions.actions?.length) {
|
|
7222
|
+
let working = pdfBytes;
|
|
7223
|
+
for (const act of planOrOptions.actions) {
|
|
7224
|
+
if (act.type === "remove") {
|
|
7225
|
+
working = await removePdfPagesBytes(working, act.pages);
|
|
7226
|
+
} else if (act.type === "rotate") {
|
|
7227
|
+
working = await rotatePdfPagesBytes(working, act.angle, act.pages, { relative: act.relative });
|
|
7228
|
+
} else if (act.type === "move") {
|
|
7229
|
+
working = await movePdfPageBytes(working, act.fromPage, act.toPage);
|
|
7230
|
+
} else if (act.type === "duplicate") {
|
|
7231
|
+
const doc = await PDFDocument2.load(working, { ignoreEncryption: true });
|
|
7232
|
+
const total = doc.getPageCount();
|
|
7233
|
+
const p = Math.floor(act.pageNumber);
|
|
7234
|
+
if (p < 1 || p > total) {
|
|
7235
|
+
throw new Error(`[UniverPdfs] Cannot duplicate page ${act.pageNumber} (1..${total}).`);
|
|
7236
|
+
}
|
|
7237
|
+
const plan = [];
|
|
7238
|
+
for (let i = 1; i <= total; i++) {
|
|
7239
|
+
if (i === p && act.insertAfter === false) plan.push(p);
|
|
7240
|
+
plan.push(i);
|
|
7241
|
+
if (i === p && act.insertAfter !== false) plan.push(p);
|
|
7242
|
+
}
|
|
7243
|
+
working = await organizePdfBytes(working, plan);
|
|
7244
|
+
}
|
|
7245
|
+
}
|
|
7246
|
+
if (!planOrOptions.pages) {
|
|
7247
|
+
return working;
|
|
7248
|
+
}
|
|
7249
|
+
return organizePdfBytes(working, planOrOptions.pages);
|
|
7250
|
+
}
|
|
7251
|
+
const pageSpecs = Array.isArray(planOrOptions) ? planOrOptions : planOrOptions.pages ?? [];
|
|
7252
|
+
if (pageSpecs.length === 0) {
|
|
7253
|
+
throw new Error("[UniverPdfs] organizePdfBytes requires at least one output page specification.");
|
|
7254
|
+
}
|
|
7255
|
+
const srcDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
|
|
7256
|
+
const totalPages = srcDoc.getPageCount();
|
|
7257
|
+
const outDoc = await PDFDocument2.create();
|
|
7258
|
+
for (const spec of pageSpecs) {
|
|
7259
|
+
const pNum = typeof spec === "number" ? Math.floor(spec) : Math.floor(spec.pageNumber);
|
|
7260
|
+
if (pNum < 1 || pNum > totalPages) {
|
|
7261
|
+
throw new Error(`[UniverPdfs] organizePdfBytes pageNumber ${pNum} out of bounds (1..${totalPages}).`);
|
|
7262
|
+
}
|
|
7263
|
+
const [copiedPage] = await outDoc.copyPages(srcDoc, [pNum - 1]);
|
|
7264
|
+
if (typeof spec === "object") {
|
|
7265
|
+
if (spec.rotation !== void 0) {
|
|
7266
|
+
const absAngle = (spec.rotation % 360 + 360) % 360;
|
|
7267
|
+
copiedPage.setRotation(degrees(absAngle));
|
|
7268
|
+
} else if (spec.addRotation !== void 0) {
|
|
7269
|
+
const curAngle = copiedPage.getRotation().angle || 0;
|
|
7270
|
+
const nextAngle = ((curAngle + spec.addRotation) % 360 + 360) % 360;
|
|
7271
|
+
copiedPage.setRotation(degrees(nextAngle));
|
|
7272
|
+
}
|
|
7273
|
+
}
|
|
7274
|
+
outDoc.addPage(copiedPage);
|
|
7275
|
+
}
|
|
7276
|
+
return await outDoc.save();
|
|
6876
7277
|
}
|
|
6877
|
-
|
|
6878
|
-
|
|
6879
|
-
const
|
|
6880
|
-
|
|
6881
|
-
|
|
6882
|
-
|
|
6883
|
-
|
|
6884
|
-
|
|
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
|
+
}
|
|
6885
7292
|
}
|
|
6886
|
-
|
|
6887
|
-
|
|
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}.`);
|
|
6888
7300
|
}
|
|
6889
|
-
|
|
6890
|
-
|
|
6891
|
-
|
|
6892
|
-
`Unsupported PDF encryption handler (Filter=/${meta.filter}, V=${meta.version}, R=${meta.revision}).`
|
|
6893
|
-
);
|
|
7301
|
+
const chunks = [];
|
|
7302
|
+
for (let i = 0; i < indices.length; i += step) {
|
|
7303
|
+
chunks.push(indices.slice(i, i + step));
|
|
6894
7304
|
}
|
|
6895
|
-
|
|
6896
|
-
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
|
|
6900
|
-
|
|
6901
|
-
|
|
6902
|
-
|
|
6903
|
-
|
|
6904
|
-
|
|
6905
|
-
|
|
6906
|
-
|
|
6907
|
-
if (requiresOpenPassword && candidatePw.length === 0) {
|
|
6908
|
-
throw new PdfSecurityError(
|
|
6909
|
-
"PDF_PASSWORD_REQUIRED",
|
|
6910
|
-
"Encrypted PDF document requires an open password."
|
|
6911
|
-
);
|
|
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);
|
|
6912
7317
|
}
|
|
6913
|
-
|
|
6914
|
-
if (
|
|
6915
|
-
|
|
6916
|
-
}
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
|
|
6920
|
-
|
|
6921
|
-
|
|
6922
|
-
|
|
6923
|
-
|
|
6924
|
-
|
|
6925
|
-
|
|
6926
|
-
|
|
6927
|
-
|
|
6928
|
-
|
|
6929
|
-
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
|
|
6934
|
-
|
|
6935
|
-
|
|
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);
|
|
6936
7389
|
}
|
|
6937
7390
|
}
|
|
6938
|
-
|
|
6939
|
-
|
|
6940
|
-
|
|
6941
|
-
|
|
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
|
|
6942
7409
|
);
|
|
7410
|
+
return groups.map((pageIndices) => ({
|
|
7411
|
+
label: formatPdfPageIndicesLabel(pageIndices),
|
|
7412
|
+
pageIndices
|
|
7413
|
+
}));
|
|
6943
7414
|
}
|
|
6944
|
-
const
|
|
6945
|
-
const
|
|
6946
|
-
|
|
6947
|
-
if (
|
|
6948
|
-
|
|
6949
|
-
|
|
6950
|
-
if (
|
|
6951
|
-
|
|
6952
|
-
|
|
6953
|
-
|
|
6954
|
-
if (
|
|
6955
|
-
|
|
6956
|
-
|
|
6957
|
-
|
|
6958
|
-
|
|
6959
|
-
} else if (
|
|
6960
|
-
|
|
6961
|
-
const
|
|
6962
|
-
|
|
6963
|
-
|
|
6964
|
-
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
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
|
+
});
|
|
6968
7446
|
}
|
|
6969
7447
|
}
|
|
6970
7448
|
}
|
|
6971
|
-
|
|
6972
|
-
|
|
6973
|
-
|
|
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
|
+
}
|
|
6974
7466
|
}
|
|
6975
|
-
return
|
|
7467
|
+
return out;
|
|
6976
7468
|
}
|
|
6977
|
-
|
|
6978
|
-
const
|
|
6979
|
-
|
|
6980
|
-
|
|
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
|
+
});
|
|
6981
7568
|
}
|
|
6982
|
-
return
|
|
7569
|
+
return outputs;
|
|
6983
7570
|
}
|
|
6984
7571
|
|
|
6985
7572
|
// src/exporter/pdf-svg-vector.ts
|
|
@@ -11263,9 +11850,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
|
|
|
11263
11850
|
pdfPage.setRotation(degrees2(pageMeta.rotation));
|
|
11264
11851
|
}
|
|
11265
11852
|
if (pageMeta.cropBox) {
|
|
11266
|
-
const cb = pageMeta.cropBox;
|
|
11267
|
-
|
|
11268
|
-
|
|
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
|
+
}
|
|
11269
11858
|
}
|
|
11270
11859
|
if (isCopiedBasePage && suppressedNativeRects.length > 0) {
|
|
11271
11860
|
for (const sRect of suppressedNativeRects) {
|
|
@@ -11565,60 +12154,123 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
|
|
|
11565
12154
|
{ colorType: elColorType }
|
|
11566
12155
|
);
|
|
11567
12156
|
} else if (el.type === "stamp" /* STAMP */) {
|
|
11568
|
-
|
|
11569
|
-
|
|
11570
|
-
|
|
11571
|
-
|
|
11572
|
-
|
|
11573
|
-
|
|
12157
|
+
if (el.svgContent) {
|
|
12158
|
+
drawVectorSvgOnPdfPage(
|
|
12159
|
+
pdfPage,
|
|
12160
|
+
pageHeight,
|
|
12161
|
+
left,
|
|
12162
|
+
top,
|
|
11574
12163
|
width,
|
|
11575
12164
|
height,
|
|
11576
|
-
|
|
11577
|
-
|
|
11578
|
-
|
|
11579
|
-
|
|
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
|
+
}
|
|
11580
12215
|
} else {
|
|
11581
|
-
|
|
11582
|
-
|
|
11583
|
-
|
|
11584
|
-
|
|
11585
|
-
|
|
11586
|
-
|
|
11587
|
-
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
|
|
11598
|
-
|
|
11599
|
-
|
|
11600
|
-
|
|
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}
|
|
11601
12250
|
\u2605 ${el.secondaryText}` : el.primaryText;
|
|
11602
|
-
|
|
11603
|
-
|
|
11604
|
-
|
|
11605
|
-
|
|
11606
|
-
|
|
11607
|
-
|
|
11608
|
-
|
|
11609
|
-
|
|
11610
|
-
|
|
11611
|
-
|
|
11612
|
-
|
|
11613
|
-
|
|
11614
|
-
|
|
11615
|
-
|
|
11616
|
-
|
|
11617
|
-
|
|
11618
|
-
|
|
11619
|
-
|
|
11620
|
-
|
|
11621
|
-
|
|
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
|
+
}
|
|
11622
12274
|
} else if (el.type === "ink" /* INK */) {
|
|
11623
12275
|
const stroke2 = parseHexColor(el.strokeColor) ?? { r: 0.94, g: 0.27, b: 0.27, a: 1 };
|
|
11624
12276
|
const strokeCol = toPdfLibColor(stroke2, elColorType);
|
|
@@ -11860,6 +12512,32 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
|
|
|
11860
12512
|
svgEl.opacity ?? 1,
|
|
11861
12513
|
elColorType
|
|
11862
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
|
+
}
|
|
11863
12541
|
} else if (el.type === "circleMark" /* CIRCLE_MARK */) {
|
|
11864
12542
|
const cmEl = el;
|
|
11865
12543
|
const cmKey = cmEl.formFieldName || cmEl.fieldKey || cmEl.bindingField;
|
|
@@ -12658,11 +13336,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
|
|
|
12658
13336
|
});
|
|
12659
13337
|
}
|
|
12660
13338
|
const pdfSubtype = annotType === "highlight" ? "Highlight" : annotType === "underline" ? "Underline" : annotType === "strikeout" ? "StrikeOut" : annotType === "squiggly" ? "Squiggly" : "Text";
|
|
13339
|
+
const effectiveStatus = annotEl.reviewStatus ?? annotEl.status;
|
|
12661
13340
|
const replyLines = (annotEl.replies ?? []).map((r) => `[${r.author}] ${r.content}`);
|
|
12662
13341
|
const threadSummary = [
|
|
12663
|
-
|
|
13342
|
+
effectiveStatus ? `[${effectiveStatus.toUpperCase()}] ${annotEl.comment ?? ""}`.trim() : annotEl.comment ?? "",
|
|
12664
13343
|
...replyLines
|
|
12665
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;
|
|
12666
13354
|
const annotDictEntries = {
|
|
12667
13355
|
Type: "Annot",
|
|
12668
13356
|
Subtype: pdfSubtype,
|
|
@@ -12670,7 +13358,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
|
|
|
12670
13358
|
C: [col.r, col.g, col.b],
|
|
12671
13359
|
CA: op,
|
|
12672
13360
|
T: PDFHexString2.fromText(annotEl.author || "Reviewer"),
|
|
12673
|
-
Contents: PDFHexString2.fromText(threadSummary)
|
|
13361
|
+
Contents: PDFHexString2.fromText(threadSummary),
|
|
13362
|
+
...pdfReviewState ? {
|
|
13363
|
+
StateModel: PDFString2.of("Review"),
|
|
13364
|
+
State: PDFString2.of(pdfReviewState)
|
|
13365
|
+
} : {}
|
|
12674
13366
|
};
|
|
12675
13367
|
if (pdfSubtype !== "Text") {
|
|
12676
13368
|
annotDictEntries.QuadPoints = [
|
|
@@ -13187,7 +13879,7 @@ function extractPdfFormValues(snapshot) {
|
|
|
13187
13879
|
return out;
|
|
13188
13880
|
}
|
|
13189
13881
|
function fillPdfFormValues(snapshot, values) {
|
|
13190
|
-
const next =
|
|
13882
|
+
const next = Tools3.deepClone(snapshot);
|
|
13191
13883
|
for (const pageId of next.document.pageOrder) {
|
|
13192
13884
|
const map = next.editState.elementsByPage[pageId] ?? {};
|
|
13193
13885
|
for (const el of Object.values(map)) {
|
|
@@ -17229,6 +17921,7 @@ export {
|
|
|
17229
17921
|
PdfTableCellVerticalAlign,
|
|
17230
17922
|
PDF_TABLE_THEME_PRESETS,
|
|
17231
17923
|
PDF_PAGE_PRESETS,
|
|
17924
|
+
resolvePdfCropBoxPt,
|
|
17232
17925
|
PdfElementType,
|
|
17233
17926
|
PdfImageSourceType,
|
|
17234
17927
|
PdfTableBorderStyle,
|
|
@@ -17270,6 +17963,13 @@ export {
|
|
|
17270
17963
|
fromPdfmeTemplate,
|
|
17271
17964
|
exportToPdfmeTemplate,
|
|
17272
17965
|
importFromPdfmeTemplate,
|
|
17966
|
+
PDF_STANDARD_STAMP_PRESETS,
|
|
17967
|
+
PDF_STANDARD_STAMP_PRESET_MAP,
|
|
17968
|
+
getPdfStandardStampPreset,
|
|
17969
|
+
buildPdfApprovalStampSvg,
|
|
17970
|
+
extractSvgTextDescriptors,
|
|
17971
|
+
createPdfApprovalStampSvgElement,
|
|
17972
|
+
createPdfApprovalStampElement,
|
|
17273
17973
|
svgToDataUri,
|
|
17274
17974
|
parseGs1ApplicationIdentifiers,
|
|
17275
17975
|
formatGs1HumanReadable,
|
|
@@ -17304,18 +18004,6 @@ export {
|
|
|
17304
18004
|
encodeBarcodeByFormat,
|
|
17305
18005
|
renderBarcodeSvgByFormat,
|
|
17306
18006
|
renderBarcodeSvgDataUrlByFormat,
|
|
17307
|
-
parsePdfContentStreamTextOps,
|
|
17308
|
-
extractNativeTextSpansFromPdfBytes,
|
|
17309
|
-
rectsIntersect,
|
|
17310
|
-
stripPdfPageNativeTextInRects,
|
|
17311
|
-
mergePdfBytes,
|
|
17312
|
-
splitPdfBytes,
|
|
17313
|
-
parsePdfPageRange,
|
|
17314
|
-
removePdfPagesBytes,
|
|
17315
|
-
insertPdfPagesBytes,
|
|
17316
|
-
rotatePdfPagesBytes,
|
|
17317
|
-
movePdfPageBytes,
|
|
17318
|
-
organizePdfBytes,
|
|
17319
18007
|
PdfSecurityError,
|
|
17320
18008
|
PDF_PASSWORD_PADDING,
|
|
17321
18009
|
md5Bytes,
|
|
@@ -17335,6 +18023,22 @@ export {
|
|
|
17335
18023
|
inspectPdfEncryption,
|
|
17336
18024
|
decryptPdfBytes,
|
|
17337
18025
|
verifyAndDecryptPdfBytes,
|
|
18026
|
+
parsePdfContentStreamTextOps,
|
|
18027
|
+
extractNativeTextSpansFromPdfBytes,
|
|
18028
|
+
rectsIntersect,
|
|
18029
|
+
stripPdfPageNativeTextInRects,
|
|
18030
|
+
mergePdfBytes,
|
|
18031
|
+
splitPdfBytes,
|
|
18032
|
+
parsePdfPageRange,
|
|
18033
|
+
removePdfPagesBytes,
|
|
18034
|
+
insertPdfPagesBytes,
|
|
18035
|
+
rotatePdfPagesBytes,
|
|
18036
|
+
movePdfPageBytes,
|
|
18037
|
+
organizePdfBytes,
|
|
18038
|
+
formatPdfPageIndicesLabel,
|
|
18039
|
+
parsePdfPageRangeSpec,
|
|
18040
|
+
splitPdfUnitByRanges,
|
|
18041
|
+
splitPdfBytesByRanges,
|
|
17338
18042
|
parseObjectPositionRatios,
|
|
17339
18043
|
computeImageFitPlacement,
|
|
17340
18044
|
computeElementCenterTransformMatrix,
|
|
@@ -17416,4 +18120,4 @@ export {
|
|
|
17416
18120
|
renderJsxToPdfmeTemplate,
|
|
17417
18121
|
exportJsxToPdfBytes
|
|
17418
18122
|
};
|
|
17419
|
-
//# sourceMappingURL=chunk-
|
|
18123
|
+
//# sourceMappingURL=chunk-PQUNQAVL.js.map
|