pdfnative 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -32
- package/dist/index.cjs +1027 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +512 -9
- package/dist/index.d.ts +512 -9
- package/dist/index.js +1021 -53
- package/dist/index.js.map +1 -1
- package/dist/tools/build-emoji-font.js +1139 -0
- package/dist/worker/index.cjs +92 -11
- package/dist/worker/index.cjs.map +1 -1
- package/dist/worker/index.js +92 -11
- package/dist/worker/index.js.map +1 -1
- package/package.json +17 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
-
var __esm = (fn2, res) => function __init() {
|
|
4
|
-
|
|
3
|
+
var __esm = (fn2, res, err) => function __init() {
|
|
4
|
+
if (err) throw err[0];
|
|
5
|
+
try {
|
|
6
|
+
return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res;
|
|
7
|
+
} catch (e) {
|
|
8
|
+
throw err = [e], e;
|
|
9
|
+
}
|
|
5
10
|
};
|
|
6
11
|
var __export = (target, all) => {
|
|
7
12
|
for (var name in all)
|
|
@@ -5979,15 +5984,86 @@ function radialShadingDict(p, m) {
|
|
|
5979
5984
|
const s = (sx + sy) / 2 || 1;
|
|
5980
5985
|
return `<< /ShadingType 3 /ColorSpace /DeviceRGB /Coords [${n(x0)} ${n(y0)} ${n(p.r0 * s)} ${n(x1)} ${n(y1)} ${n(p.r1 * s)}] /Function ${buildGradientFunction(p.stops)} /Extend ${extendFlags(p.extend)} >>`;
|
|
5981
5986
|
}
|
|
5987
|
+
function colorAtOffset(stops, t) {
|
|
5988
|
+
if (stops.length === 0) return [0, 0, 0, 255];
|
|
5989
|
+
const sorted = stops.slice().sort((a, b) => a.offset - b.offset);
|
|
5990
|
+
if (t <= sorted[0].offset) return sorted[0].color;
|
|
5991
|
+
const last = sorted[sorted.length - 1];
|
|
5992
|
+
if (t >= last.offset) return last.color;
|
|
5993
|
+
for (let i = 0; i < sorted.length - 1; i++) {
|
|
5994
|
+
const a = sorted[i], b = sorted[i + 1];
|
|
5995
|
+
if (t >= a.offset && t <= b.offset) {
|
|
5996
|
+
const span = b.offset - a.offset || 1;
|
|
5997
|
+
const f = (t - a.offset) / span;
|
|
5998
|
+
return [
|
|
5999
|
+
Math.round(a.color[0] + (b.color[0] - a.color[0]) * f),
|
|
6000
|
+
Math.round(a.color[1] + (b.color[1] - a.color[1]) * f),
|
|
6001
|
+
Math.round(a.color[2] + (b.color[2] - a.color[2]) * f),
|
|
6002
|
+
Math.round(a.color[3] + (b.color[3] - a.color[3]) * f)
|
|
6003
|
+
];
|
|
6004
|
+
}
|
|
6005
|
+
}
|
|
6006
|
+
return last.color;
|
|
6007
|
+
}
|
|
6008
|
+
function emitSweep(p, cx, cy, maxR, body, gsFor, blendMode) {
|
|
6009
|
+
const start = p.startAngle;
|
|
6010
|
+
const end = p.endAngle;
|
|
6011
|
+
const span = end - start;
|
|
6012
|
+
if (Math.abs(span) < 0.01) {
|
|
6013
|
+
const c = colorAtOffset(p.stops, 0);
|
|
6014
|
+
const gs = gsFor(c[3] / 255, blendMode);
|
|
6015
|
+
if (gs) body.push(`/${gs} gs`);
|
|
6016
|
+
body.push(`${ch(c[0])} ${ch(c[1])} ${ch(c[2])} rg`);
|
|
6017
|
+
body.push(`${n(cx - maxR)} ${n(cy - maxR)} ${n(2 * maxR)} ${n(2 * maxR)} re`);
|
|
6018
|
+
body.push("f");
|
|
6019
|
+
return;
|
|
6020
|
+
}
|
|
6021
|
+
const steps = Math.max(12, Math.min(180, Math.ceil(Math.abs(span) / 3)));
|
|
6022
|
+
const r = maxR * 1.5;
|
|
6023
|
+
const rad = Math.PI / 180;
|
|
6024
|
+
for (let i = 0; i < steps; i++) {
|
|
6025
|
+
const a0 = start + span * i / steps;
|
|
6026
|
+
const a1 = start + span * (i + 1) / steps;
|
|
6027
|
+
const tMid = (i + 0.5) / steps;
|
|
6028
|
+
const c = colorAtOffset(p.stops, tMid);
|
|
6029
|
+
const gs = gsFor(c[3] / 255, blendMode);
|
|
6030
|
+
body.push("q");
|
|
6031
|
+
if (gs) body.push(`/${gs} gs`);
|
|
6032
|
+
body.push(`${ch(c[0])} ${ch(c[1])} ${ch(c[2])} rg`);
|
|
6033
|
+
const x0 = cx + r * Math.cos(a0 * rad), y0 = cy + r * Math.sin(a0 * rad);
|
|
6034
|
+
const x1 = cx + r * Math.cos(a1 * rad), y1 = cy + r * Math.sin(a1 * rad);
|
|
6035
|
+
body.push(`${n(cx)} ${n(cy)} m ${n(x0)} ${n(y0)} l ${n(x1)} ${n(y1)} l h`);
|
|
6036
|
+
body.push("f");
|
|
6037
|
+
body.push("Q");
|
|
6038
|
+
}
|
|
6039
|
+
}
|
|
5982
6040
|
function renderColorGlyph(glyph, outlines, unitsPerEm) {
|
|
5983
6041
|
const body = [];
|
|
5984
6042
|
const shadings = [];
|
|
5985
6043
|
const extGStates = [];
|
|
5986
|
-
const
|
|
6044
|
+
const gsMap = /* @__PURE__ */ new Map();
|
|
5987
6045
|
let shadingIdx = 0;
|
|
6046
|
+
const gsFor = (alpha, bm) => {
|
|
6047
|
+
const a = Math.max(0, Math.min(1, alpha));
|
|
6048
|
+
const needAlpha = a < 0.999;
|
|
6049
|
+
const needBm = bm !== void 0 && bm !== "Normal";
|
|
6050
|
+
if (!needAlpha && !needBm) return "";
|
|
6051
|
+
const key = `${needAlpha ? a.toFixed(3) : "1"}|${needBm ? bm : ""}`;
|
|
6052
|
+
let name = gsMap.get(key);
|
|
6053
|
+
if (!name) {
|
|
6054
|
+
name = `Gs${gsMap.size}`;
|
|
6055
|
+
gsMap.set(key, name);
|
|
6056
|
+
const parts = [];
|
|
6057
|
+
if (needAlpha) parts.push(`/ca ${n(a)}`, `/CA ${n(a)}`);
|
|
6058
|
+
if (needBm) parts.push(`/BM /${bm}`);
|
|
6059
|
+
extGStates.push({ name, dict: `<< ${parts.join(" ")} >>` });
|
|
6060
|
+
}
|
|
6061
|
+
return name;
|
|
6062
|
+
};
|
|
5988
6063
|
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
5989
6064
|
for (const layer of glyph.layers) {
|
|
5990
6065
|
const m = layer.transform ?? ID;
|
|
6066
|
+
const bm = layer.blendMode;
|
|
5991
6067
|
const contours = outlines(layer.glyphId);
|
|
5992
6068
|
if (contours.length === 0) continue;
|
|
5993
6069
|
const path = contoursToPath(contours, m);
|
|
@@ -6002,26 +6078,36 @@ function renderColorGlyph(glyph, outlines, unitsPerEm) {
|
|
|
6002
6078
|
}
|
|
6003
6079
|
if (layer.paint.kind === "solid") {
|
|
6004
6080
|
const c = layer.paint.color;
|
|
6005
|
-
const alpha = c[3] / 255;
|
|
6006
6081
|
body.push("q");
|
|
6007
|
-
|
|
6008
|
-
|
|
6009
|
-
if (!gs) {
|
|
6010
|
-
gs = `GsA${alphaMap.size}`;
|
|
6011
|
-
alphaMap.set(c[3], gs);
|
|
6012
|
-
extGStates.push({ name: gs, dict: `<< /ca ${n(alpha)} /CA ${n(alpha)} >>` });
|
|
6013
|
-
}
|
|
6014
|
-
body.push(`/${gs} gs`);
|
|
6015
|
-
}
|
|
6082
|
+
const gs = gsFor(c[3] / 255, bm);
|
|
6083
|
+
if (gs) body.push(`/${gs} gs`);
|
|
6016
6084
|
body.push(`${ch(c[0])} ${ch(c[1])} ${ch(c[2])} rg`);
|
|
6017
6085
|
body.push(path);
|
|
6018
6086
|
body.push("f");
|
|
6019
6087
|
body.push("Q");
|
|
6088
|
+
} else if (layer.paint.kind === "sweep") {
|
|
6089
|
+
const [cx, cy] = tx(m, layer.paint.center[0], layer.paint.center[1]);
|
|
6090
|
+
let r2 = 0;
|
|
6091
|
+
for (const contour of contours) {
|
|
6092
|
+
for (const pt of contour) {
|
|
6093
|
+
const [px, py] = tx(m, pt.x, pt.y);
|
|
6094
|
+
const d = (px - cx) * (px - cx) + (py - cy) * (py - cy);
|
|
6095
|
+
if (d > r2) r2 = d;
|
|
6096
|
+
}
|
|
6097
|
+
}
|
|
6098
|
+
const maxR = Math.sqrt(r2) || 1;
|
|
6099
|
+
body.push("q");
|
|
6100
|
+
body.push(path);
|
|
6101
|
+
body.push("W n");
|
|
6102
|
+
emitSweep(layer.paint, cx, cy, maxR, body, gsFor, bm);
|
|
6103
|
+
body.push("Q");
|
|
6020
6104
|
} else {
|
|
6021
6105
|
const name = `Sh${shadingIdx++}`;
|
|
6022
6106
|
const dict = layer.paint.kind === "linear" ? linearShadingDict(layer.paint, m) : radialShadingDict(layer.paint, m);
|
|
6023
6107
|
shadings.push({ name, dict });
|
|
6024
6108
|
body.push("q");
|
|
6109
|
+
const gs = gsFor(1, bm);
|
|
6110
|
+
if (gs) body.push(`/${gs} gs`);
|
|
6025
6111
|
body.push(path);
|
|
6026
6112
|
body.push("W n");
|
|
6027
6113
|
body.push(`/${name} sh`);
|
|
@@ -8529,6 +8615,180 @@ function buildPDFBytes(params, layoutOptions) {
|
|
|
8529
8615
|
return toBytes(buildPDF(params, layoutOptions));
|
|
8530
8616
|
}
|
|
8531
8617
|
|
|
8618
|
+
// src/core/pdf-outline.ts
|
|
8619
|
+
function buildOutlineObjects(items, startObjNum, pageObjNumFor, defaultY, fmtNum3, pageCount) {
|
|
8620
|
+
const rootObjNum = startObjNum;
|
|
8621
|
+
const nodes = [];
|
|
8622
|
+
let nextObj = startObjNum + 1;
|
|
8623
|
+
function alloc(list, parentObjNum, depth) {
|
|
8624
|
+
let first = 0;
|
|
8625
|
+
let last = 0;
|
|
8626
|
+
let prev = 0;
|
|
8627
|
+
let visibleCount = 0;
|
|
8628
|
+
const siblingNodes = [];
|
|
8629
|
+
for (const item of list) {
|
|
8630
|
+
const objNum = nextObj++;
|
|
8631
|
+
const open = item.open !== false;
|
|
8632
|
+
const node = {
|
|
8633
|
+
item,
|
|
8634
|
+
objNum,
|
|
8635
|
+
parentObjNum,
|
|
8636
|
+
depth,
|
|
8637
|
+
firstChildObjNum: 0,
|
|
8638
|
+
lastChildObjNum: 0,
|
|
8639
|
+
prevObjNum: prev,
|
|
8640
|
+
nextObjNum: 0,
|
|
8641
|
+
openDescendantCount: 0,
|
|
8642
|
+
open
|
|
8643
|
+
};
|
|
8644
|
+
if (prev !== 0) {
|
|
8645
|
+
const prevNode = siblingNodes[siblingNodes.length - 1];
|
|
8646
|
+
prevNode.nextObjNum = objNum;
|
|
8647
|
+
}
|
|
8648
|
+
nodes.push(node);
|
|
8649
|
+
siblingNodes.push(node);
|
|
8650
|
+
if (first === 0) first = objNum;
|
|
8651
|
+
last = objNum;
|
|
8652
|
+
prev = objNum;
|
|
8653
|
+
visibleCount++;
|
|
8654
|
+
const children = item.children;
|
|
8655
|
+
if (children && children.length > 0) {
|
|
8656
|
+
const sub = alloc(children, objNum, depth + 1);
|
|
8657
|
+
node.firstChildObjNum = sub.first;
|
|
8658
|
+
node.lastChildObjNum = sub.last;
|
|
8659
|
+
node.openDescendantCount = sub.visibleCount;
|
|
8660
|
+
if (open) visibleCount += sub.visibleCount;
|
|
8661
|
+
}
|
|
8662
|
+
}
|
|
8663
|
+
return { first, last, visibleCount };
|
|
8664
|
+
}
|
|
8665
|
+
const top = alloc(items, rootObjNum, 0);
|
|
8666
|
+
const objects = [];
|
|
8667
|
+
objects.push([
|
|
8668
|
+
rootObjNum,
|
|
8669
|
+
`<< /Type /Outlines /First ${top.first} 0 R /Last ${top.last} 0 R /Count ${top.visibleCount} >>`
|
|
8670
|
+
]);
|
|
8671
|
+
for (const node of nodes) {
|
|
8672
|
+
const it = node.item;
|
|
8673
|
+
const pageIdx = Math.max(0, Math.min(pageCount - 1, it.pageIndex | 0));
|
|
8674
|
+
const pageObj = pageObjNumFor(pageIdx);
|
|
8675
|
+
const y = it.y ?? defaultY;
|
|
8676
|
+
const parts = [
|
|
8677
|
+
`/Title ${encodePdfTextString(it.title)}`,
|
|
8678
|
+
`/Parent ${node.parentObjNum} 0 R`
|
|
8679
|
+
];
|
|
8680
|
+
if (node.prevObjNum !== 0) parts.push(`/Prev ${node.prevObjNum} 0 R`);
|
|
8681
|
+
if (node.nextObjNum !== 0) parts.push(`/Next ${node.nextObjNum} 0 R`);
|
|
8682
|
+
if (node.firstChildObjNum !== 0) {
|
|
8683
|
+
parts.push(`/First ${node.firstChildObjNum} 0 R`);
|
|
8684
|
+
parts.push(`/Last ${node.lastChildObjNum} 0 R`);
|
|
8685
|
+
const count = node.open ? node.openDescendantCount : -node.openDescendantCount;
|
|
8686
|
+
parts.push(`/Count ${count}`);
|
|
8687
|
+
}
|
|
8688
|
+
parts.push(`/Dest [${pageObj} 0 R /XYZ 0 ${fmtNum3(y)} null]`);
|
|
8689
|
+
const flags = (it.bold ? 2 : 0) | (it.italic ? 1 : 0);
|
|
8690
|
+
if (flags !== 0) parts.push(`/F ${flags}`);
|
|
8691
|
+
if (it.color) parts.push(`/C [${it.color}]`);
|
|
8692
|
+
objects.push([node.objNum, `<< ${parts.join(" ")} >>`]);
|
|
8693
|
+
}
|
|
8694
|
+
return { objects, rootObjNum, totalObjects: nodes.length + 1 };
|
|
8695
|
+
}
|
|
8696
|
+
|
|
8697
|
+
// src/core/pdf-page-labels.ts
|
|
8698
|
+
var STYLE_OP = {
|
|
8699
|
+
decimal: "D",
|
|
8700
|
+
roman: "r",
|
|
8701
|
+
Roman: "R",
|
|
8702
|
+
alpha: "a",
|
|
8703
|
+
Alpha: "A"
|
|
8704
|
+
};
|
|
8705
|
+
function escapePdfLiteral(s) {
|
|
8706
|
+
return s.replace(/[\\()]/g, (c) => "\\" + c);
|
|
8707
|
+
}
|
|
8708
|
+
function buildPageLabelsDict(ranges, pageCount) {
|
|
8709
|
+
if (ranges.length === 0) {
|
|
8710
|
+
throw new Error("pageLabels must contain at least one range");
|
|
8711
|
+
}
|
|
8712
|
+
const sorted = [...ranges].sort((a, b) => a.startPage - b.startPage);
|
|
8713
|
+
let prev = -1;
|
|
8714
|
+
const nums = [];
|
|
8715
|
+
for (const r of sorted) {
|
|
8716
|
+
const idx = r.startPage | 0;
|
|
8717
|
+
if (idx < 0 || idx >= pageCount) {
|
|
8718
|
+
throw new Error(`pageLabels range startPage ${idx} out of bounds (0-${pageCount - 1})`);
|
|
8719
|
+
}
|
|
8720
|
+
if (idx <= prev) {
|
|
8721
|
+
throw new Error(`pageLabels ranges must have strictly increasing, unique startPage values (got ${idx} after ${prev})`);
|
|
8722
|
+
}
|
|
8723
|
+
prev = idx;
|
|
8724
|
+
const entryParts = [];
|
|
8725
|
+
const style = r.style ?? "decimal";
|
|
8726
|
+
if (style !== "none") {
|
|
8727
|
+
entryParts.push(`/S /${STYLE_OP[style]}`);
|
|
8728
|
+
}
|
|
8729
|
+
if (r.prefix !== void 0 && r.prefix !== "") {
|
|
8730
|
+
entryParts.push(`/P (${escapePdfLiteral(r.prefix)})`);
|
|
8731
|
+
}
|
|
8732
|
+
if (r.start !== void 0 && r.start !== 1) {
|
|
8733
|
+
if (!Number.isInteger(r.start) || r.start < 1) {
|
|
8734
|
+
throw new Error(`pageLabels range start must be a positive integer (got ${r.start})`);
|
|
8735
|
+
}
|
|
8736
|
+
entryParts.push(`/St ${r.start}`);
|
|
8737
|
+
}
|
|
8738
|
+
nums.push(`${idx} << ${entryParts.join(" ")} >>`);
|
|
8739
|
+
}
|
|
8740
|
+
return `<< /Nums [${nums.join(" ")}] >>`;
|
|
8741
|
+
}
|
|
8742
|
+
|
|
8743
|
+
// src/core/pdf-viewer-prefs.ts
|
|
8744
|
+
var PAGE_LAYOUT = {
|
|
8745
|
+
singlePage: "SinglePage",
|
|
8746
|
+
oneColumn: "OneColumn",
|
|
8747
|
+
twoColumnLeft: "TwoColumnLeft",
|
|
8748
|
+
twoColumnRight: "TwoColumnRight",
|
|
8749
|
+
twoPageLeft: "TwoPageLeft",
|
|
8750
|
+
twoPageRight: "TwoPageRight"
|
|
8751
|
+
};
|
|
8752
|
+
var PAGE_MODE = {
|
|
8753
|
+
useNone: "UseNone",
|
|
8754
|
+
useOutlines: "UseOutlines",
|
|
8755
|
+
useThumbs: "UseThumbs",
|
|
8756
|
+
fullScreen: "FullScreen",
|
|
8757
|
+
useOC: "UseOC",
|
|
8758
|
+
useAttachments: "UseAttachments"
|
|
8759
|
+
};
|
|
8760
|
+
var NON_FS_PAGE_MODE = {
|
|
8761
|
+
useNone: "UseNone",
|
|
8762
|
+
useOutlines: "UseOutlines",
|
|
8763
|
+
useThumbs: "UseThumbs",
|
|
8764
|
+
useOC: "UseOC"
|
|
8765
|
+
};
|
|
8766
|
+
function buildViewerPreferences(prefs) {
|
|
8767
|
+
const pageLayout = prefs.pageLayout ? PAGE_LAYOUT[prefs.pageLayout] : void 0;
|
|
8768
|
+
const pageMode = prefs.pageMode ? PAGE_MODE[prefs.pageMode] : void 0;
|
|
8769
|
+
const entries = [];
|
|
8770
|
+
const bool = (key, v) => {
|
|
8771
|
+
if (v !== void 0) entries.push(`/${key} ${v ? "true" : "false"}`);
|
|
8772
|
+
};
|
|
8773
|
+
bool("HideToolbar", prefs.hideToolbar);
|
|
8774
|
+
bool("HideMenubar", prefs.hideMenubar);
|
|
8775
|
+
bool("HideWindowUI", prefs.hideWindowUI);
|
|
8776
|
+
bool("FitWindow", prefs.fitWindow);
|
|
8777
|
+
bool("CenterWindow", prefs.centerWindow);
|
|
8778
|
+
bool("DisplayDocTitle", prefs.displayDocTitle);
|
|
8779
|
+
if (prefs.nonFullScreenPageMode) {
|
|
8780
|
+
entries.push(`/NonFullScreenPageMode /${NON_FS_PAGE_MODE[prefs.nonFullScreenPageMode]}`);
|
|
8781
|
+
}
|
|
8782
|
+
if (prefs.direction) {
|
|
8783
|
+
entries.push(`/Direction /${prefs.direction === "r2l" ? "R2L" : "L2R"}`);
|
|
8784
|
+
}
|
|
8785
|
+
if (prefs.printScaling) {
|
|
8786
|
+
entries.push(`/PrintScaling /${prefs.printScaling === "none" ? "None" : "AppDefault"}`);
|
|
8787
|
+
}
|
|
8788
|
+
const dict = entries.length > 0 ? ` /ViewerPreferences << ${entries.join(" ")} >>` : "";
|
|
8789
|
+
return { pageLayout, pageMode, dict };
|
|
8790
|
+
}
|
|
8791
|
+
|
|
8532
8792
|
// src/core/pdf-document.ts
|
|
8533
8793
|
init_pdf_encrypt();
|
|
8534
8794
|
|
|
@@ -11020,23 +11280,36 @@ function renderList(block, y, enc, mgL, cw, tagCtx, documentChildren) {
|
|
|
11020
11280
|
const sz = block.fontSize ?? DEFAULT_LIST_SIZE;
|
|
11021
11281
|
const lineH = sz * DEFAULT_LINE_HEIGHT;
|
|
11022
11282
|
const color = "0.216 0.255 0.318";
|
|
11023
|
-
const availW = cw - LIST_INDENT - BULLET_MARK_WIDTH;
|
|
11024
11283
|
ops.push(`${color} rg`);
|
|
11025
|
-
const
|
|
11026
|
-
|
|
11027
|
-
|
|
11028
|
-
|
|
11029
|
-
|
|
11284
|
+
const root = renderListLevel(block.items, block.style, 0, y, sz, lineH, enc, mgL, cw, tagCtx);
|
|
11285
|
+
ops.push(...root.ops);
|
|
11286
|
+
if (tagCtx?.tagged && root.struct && root.struct.children.length > 0) {
|
|
11287
|
+
documentChildren.push(root.struct);
|
|
11288
|
+
}
|
|
11289
|
+
return { ops, y: root.y };
|
|
11290
|
+
}
|
|
11291
|
+
function renderListLevel(items, style, depth, y, sz, lineH, enc, mgL, cw, tagCtx) {
|
|
11292
|
+
const ops = [];
|
|
11293
|
+
const indent = LIST_INDENT * (depth + 1);
|
|
11294
|
+
const markerX = mgL + indent;
|
|
11295
|
+
const xOffset = markerX + BULLET_MARK_WIDTH;
|
|
11296
|
+
const availW = cw - indent - BULLET_MARK_WIDTH;
|
|
11297
|
+
const levelChildren = [];
|
|
11298
|
+
for (let idx = 0; idx < items.length; idx++) {
|
|
11299
|
+
const entry = items[idx];
|
|
11300
|
+
const text = typeof entry === "string" ? entry : entry.text;
|
|
11301
|
+
const children = typeof entry === "string" ? void 0 : entry.items;
|
|
11302
|
+
const marker = style === "bullet" ? "\u2022" : `${idx + 1}.`;
|
|
11303
|
+
const lines = wrapText(text, availW, sz, enc);
|
|
11030
11304
|
const liChildren = [];
|
|
11031
11305
|
if (tagCtx?.tagged) {
|
|
11032
11306
|
const mcid = tagCtx.mcidAlloc.next(tagCtx.pageObjNum);
|
|
11033
11307
|
liChildren.push({ mcid, pageObjNum: tagCtx.pageObjNum });
|
|
11034
|
-
ops.push(txtTagged(marker,
|
|
11308
|
+
ops.push(txtTagged(marker, markerX, y - sz, enc.f1, sz, enc, mcid));
|
|
11035
11309
|
} else {
|
|
11036
|
-
ops.push(txt(marker,
|
|
11310
|
+
ops.push(txt(marker, markerX, y - sz, enc.f1, sz, enc));
|
|
11037
11311
|
}
|
|
11038
11312
|
for (let li = 0; li < lines.length; li++) {
|
|
11039
|
-
const xOffset = mgL + LIST_INDENT + BULLET_MARK_WIDTH;
|
|
11040
11313
|
if (li === 0) {
|
|
11041
11314
|
if (tagCtx?.tagged) {
|
|
11042
11315
|
const mcid = tagCtx.mcidAlloc.next(tagCtx.pageObjNum);
|
|
@@ -11057,14 +11330,20 @@ function renderList(block, y, enc, mgL, cw, tagCtx, documentChildren) {
|
|
|
11057
11330
|
}
|
|
11058
11331
|
}
|
|
11059
11332
|
y -= lineH + LIST_ITEM_SPACING;
|
|
11333
|
+
if (children && children.length > 0) {
|
|
11334
|
+
const sub = renderListLevel(children, style, depth + 1, y, sz, lineH, enc, mgL, cw, tagCtx);
|
|
11335
|
+
ops.push(...sub.ops);
|
|
11336
|
+
y = sub.y;
|
|
11337
|
+
if (tagCtx?.tagged && sub.struct && sub.struct.children.length > 0) {
|
|
11338
|
+
liChildren.push(sub.struct);
|
|
11339
|
+
}
|
|
11340
|
+
}
|
|
11060
11341
|
if (tagCtx?.tagged && liChildren.length > 0) {
|
|
11061
|
-
|
|
11342
|
+
levelChildren.push({ type: "LI", children: liChildren });
|
|
11062
11343
|
}
|
|
11063
11344
|
}
|
|
11064
|
-
|
|
11065
|
-
|
|
11066
|
-
}
|
|
11067
|
-
return { ops, y };
|
|
11345
|
+
const struct = tagCtx?.tagged ? { type: "L", children: levelChildren } : void 0;
|
|
11346
|
+
return { ops, y, struct };
|
|
11068
11347
|
}
|
|
11069
11348
|
var DEFAULT_ZEBRA_COLOR = "0.969 0.973 0.984";
|
|
11070
11349
|
var CAPTION_FONT_SIZE = 9;
|
|
@@ -11152,6 +11431,30 @@ function renderTable(block, y, enc, mgL, mgR, pgW, cw, tagCtx, documentChildren,
|
|
|
11152
11431
|
const clip = block.clipCells !== false;
|
|
11153
11432
|
const zebraColor = resolveZebraColor(block.zebra);
|
|
11154
11433
|
const wrapMode = block.wrap ?? "auto";
|
|
11434
|
+
const borders = block.cellBorders;
|
|
11435
|
+
const borderSides = borders ? {
|
|
11436
|
+
top: borders.all === true || borders.top === true,
|
|
11437
|
+
right: borders.all === true || borders.right === true,
|
|
11438
|
+
bottom: borders.all === true || borders.bottom === true,
|
|
11439
|
+
left: borders.all === true || borders.left === true
|
|
11440
|
+
} : null;
|
|
11441
|
+
const borderColor = borders?.color ? parseColor(borders.color) : "0.8 0.8 0.8";
|
|
11442
|
+
const borderWidth = borders?.width ?? 0.5;
|
|
11443
|
+
const borderDash = borders?.style === "dashed" ? "[3] 0 d" : borders?.style === "dotted" ? `[${fmtNum(borderWidth)} ${fmtNum(borderWidth * 2)}] 0 d` : null;
|
|
11444
|
+
const cellBorderOps = (cellX, cellW, top, h) => {
|
|
11445
|
+
if (!borderSides || !borderSides.top && !borderSides.right && !borderSides.bottom && !borderSides.left) {
|
|
11446
|
+
return [];
|
|
11447
|
+
}
|
|
11448
|
+
const o = [];
|
|
11449
|
+
o.push(`${fmtNum(borderWidth)} w ${borderColor} RG${borderDash ? " " + borderDash : ""}`);
|
|
11450
|
+
const x0 = cellX, x1 = cellX + cellW, y0 = top - h, y1 = top;
|
|
11451
|
+
if (borderSides.top) o.push(`${fmtNum(x0)} ${fmtNum(y1)} m ${fmtNum(x1)} ${fmtNum(y1)} l S`);
|
|
11452
|
+
if (borderSides.bottom) o.push(`${fmtNum(x0)} ${fmtNum(y0)} m ${fmtNum(x1)} ${fmtNum(y0)} l S`);
|
|
11453
|
+
if (borderSides.left) o.push(`${fmtNum(x0)} ${fmtNum(y0)} m ${fmtNum(x0)} ${fmtNum(y1)} l S`);
|
|
11454
|
+
if (borderSides.right) o.push(`${fmtNum(x1)} ${fmtNum(y0)} m ${fmtNum(x1)} ${fmtNum(y1)} l S`);
|
|
11455
|
+
if (borderDash) o.push("[] 0 d");
|
|
11456
|
+
return o;
|
|
11457
|
+
};
|
|
11155
11458
|
const clipCell = (op, i, top, h) => clip ? `q ${fmtNum(cx[i])} ${fmtNum(top - h)} ${fmtNum(cwi[i])} ${fmtNum(h)} re W n
|
|
11156
11459
|
${op}
|
|
11157
11460
|
Q` : op;
|
|
@@ -11160,9 +11463,21 @@ Q` : op;
|
|
|
11160
11463
|
const out = [];
|
|
11161
11464
|
const lineH = sz * TABLE_LINE_HEIGHT;
|
|
11162
11465
|
const padBottom = isHeader ? HEADER_PAD_BOTTOM : CELL_PAD_BOTTOM;
|
|
11466
|
+
const vAlign = col.vAlign ?? block.cellVAlign;
|
|
11163
11467
|
for (let li = 0; li < lines.length; li++) {
|
|
11164
11468
|
const t = lines.length === 1 && wrapMode === "never" ? truncate(lines[li], isHeader && col.mxH !== void 0 ? col.mxH : col.mx) : lines[li];
|
|
11165
|
-
|
|
11469
|
+
let baselineY;
|
|
11470
|
+
if (vAlign) {
|
|
11471
|
+
const blockH = lines.length * lineH;
|
|
11472
|
+
let offset;
|
|
11473
|
+
if (vAlign === "top") offset = pad;
|
|
11474
|
+
else if (vAlign === "bottom") offset = rowH - blockH - pad;
|
|
11475
|
+
else offset = (rowH - blockH) / 2;
|
|
11476
|
+
if (offset < pad) offset = pad;
|
|
11477
|
+
baselineY = rowTop - offset - li * lineH - sz + sz * 0.2;
|
|
11478
|
+
} else {
|
|
11479
|
+
baselineY = lines.length === 1 ? rowTop - rowH + padBottom : rowTop - pad - sz + sz * 0.2 - li * lineH;
|
|
11480
|
+
}
|
|
11166
11481
|
let op;
|
|
11167
11482
|
if (mcRefsOut !== null && tagCtx?.tagged) {
|
|
11168
11483
|
const mcid = tagCtx.mcidAlloc.next(tagCtx.pageObjNum);
|
|
@@ -11217,6 +11532,7 @@ Q` : op;
|
|
|
11217
11532
|
for (let i = 0; i < block.headers.length && i < columns.length; i++) {
|
|
11218
11533
|
const cellRefs = tagCtx?.tagged ? [] : null;
|
|
11219
11534
|
ops.push(...emitCell(headerLines[i] ?? [""], i, y, headerHeight, enc.f2, fs.th, cellRefs, true));
|
|
11535
|
+
ops.push(...cellBorderOps(cx[i], cwi[i], y, headerHeight));
|
|
11220
11536
|
if (cellRefs && cellRefs.length > 0) {
|
|
11221
11537
|
thChildren.push({ type: "TH", children: cellRefs });
|
|
11222
11538
|
}
|
|
@@ -11244,6 +11560,7 @@ Q` : op;
|
|
|
11244
11560
|
ops.push(`${color} rg`);
|
|
11245
11561
|
const cellRefs = tagCtx?.tagged ? [] : null;
|
|
11246
11562
|
ops.push(...emitCell(cells[i] ?? [""], i, y, rowH, font, fs.td, cellRefs, false));
|
|
11563
|
+
ops.push(...cellBorderOps(cx[i], cwi[i], y, rowH));
|
|
11247
11564
|
if (cellRefs && cellRefs.length > 0) {
|
|
11248
11565
|
tdChildren.push({ type: "TD", children: cellRefs });
|
|
11249
11566
|
}
|
|
@@ -11615,13 +11932,20 @@ function estimateBlockHeight(block, enc, cw, headings) {
|
|
|
11615
11932
|
case "list": {
|
|
11616
11933
|
const sz = block.fontSize ?? DEFAULT_LIST_SIZE;
|
|
11617
11934
|
const lineH = sz * DEFAULT_LINE_HEIGHT;
|
|
11618
|
-
const
|
|
11619
|
-
|
|
11620
|
-
|
|
11621
|
-
|
|
11622
|
-
|
|
11623
|
-
|
|
11624
|
-
|
|
11935
|
+
const measureLevel = (items, depth) => {
|
|
11936
|
+
const availW = cw - LIST_INDENT * (depth + 1) - BULLET_MARK_WIDTH;
|
|
11937
|
+
let acc = 0;
|
|
11938
|
+
for (const entry of items) {
|
|
11939
|
+
const text = typeof entry === "string" ? entry : entry.text;
|
|
11940
|
+
const lines = wrapText(text, availW, sz, enc);
|
|
11941
|
+
acc += lineH + (lines.length - 1) * lineH + LIST_ITEM_SPACING;
|
|
11942
|
+
if (typeof entry !== "string" && entry.items && entry.items.length > 0) {
|
|
11943
|
+
acc += measureLevel(entry.items, depth + 1);
|
|
11944
|
+
}
|
|
11945
|
+
}
|
|
11946
|
+
return acc;
|
|
11947
|
+
};
|
|
11948
|
+
return measureLevel(block.items, 0);
|
|
11625
11949
|
}
|
|
11626
11950
|
case "table": {
|
|
11627
11951
|
return TH_H + block.rows.length * ROW_H + 6;
|
|
@@ -12479,6 +12803,41 @@ function assembleDocumentParts(params, layoutOptions) {
|
|
|
12479
12803
|
totalObjs += efResult.totalObjects;
|
|
12480
12804
|
}
|
|
12481
12805
|
}
|
|
12806
|
+
let pageLabelsStr = "";
|
|
12807
|
+
if (params.pageLabels && params.pageLabels.length > 0) {
|
|
12808
|
+
pageLabelsStr = ` /PageLabels ${buildPageLabelsDict(params.pageLabels, totalPages)}`;
|
|
12809
|
+
}
|
|
12810
|
+
const viewerPrefs = layout?.viewerPreferences ? buildViewerPreferences(layout.viewerPreferences) : void 0;
|
|
12811
|
+
let viewerPrefsStr = viewerPrefs?.dict ?? "";
|
|
12812
|
+
if (viewerPrefs?.pageLayout) {
|
|
12813
|
+
viewerPrefsStr = ` /PageLayout /${viewerPrefs.pageLayout}${viewerPrefsStr}`;
|
|
12814
|
+
}
|
|
12815
|
+
let outlineCatalogStr = "";
|
|
12816
|
+
if (params.outline) {
|
|
12817
|
+
const items = params.outline === "auto" ? autoOutlineFromHeadings(headingDests) : params.outline.map(mapOutlineItem);
|
|
12818
|
+
if (items.length > 0) {
|
|
12819
|
+
const outlineStart = totalObjs + 1;
|
|
12820
|
+
const built = buildOutlineObjects(
|
|
12821
|
+
items,
|
|
12822
|
+
outlineStart,
|
|
12823
|
+
(pageIndex) => pageObjStart + pageIndex * 2,
|
|
12824
|
+
pgH - mg.t,
|
|
12825
|
+
fmtNum,
|
|
12826
|
+
totalPages
|
|
12827
|
+
);
|
|
12828
|
+
for (const [objNum, content] of built.objects) {
|
|
12829
|
+
emitObj(objNum, content);
|
|
12830
|
+
}
|
|
12831
|
+
totalObjs = outlineStart + built.totalObjects - 1;
|
|
12832
|
+
outlineCatalogStr = ` /Outlines ${built.rootObjNum} 0 R`;
|
|
12833
|
+
if (!viewerPrefs?.pageMode) {
|
|
12834
|
+
outlineCatalogStr += " /PageMode /UseOutlines";
|
|
12835
|
+
}
|
|
12836
|
+
}
|
|
12837
|
+
}
|
|
12838
|
+
if (viewerPrefs?.pageMode) {
|
|
12839
|
+
viewerPrefsStr = ` /PageMode /${viewerPrefs.pageMode}${viewerPrefsStr}`;
|
|
12840
|
+
}
|
|
12482
12841
|
let destsStr = "";
|
|
12483
12842
|
if (hasToc && headingDests.length > 0) {
|
|
12484
12843
|
const destEntries = headingDests.map((h) => {
|
|
@@ -12508,7 +12867,7 @@ function assembleDocumentParts(params, layoutOptions) {
|
|
|
12508
12867
|
acroFormStr = ` ${buildAcroFormDict(fieldObjNums, formFontObjNum)}`;
|
|
12509
12868
|
}
|
|
12510
12869
|
if (tagged) {
|
|
12511
|
-
let catalogContent = `<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot ${structTreeRootObjNum} 0 R /Metadata ${xmpObjNum} 0 R /OutputIntents [${outputIntentObjNum} 0 R]${destsStr}${acroFormStr}`;
|
|
12870
|
+
let catalogContent = `<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot ${structTreeRootObjNum} 0 R /Metadata ${xmpObjNum} 0 R /OutputIntents [${outputIntentObjNum} 0 R]${destsStr}${acroFormStr}${outlineCatalogStr}${pageLabelsStr}${viewerPrefsStr}`;
|
|
12512
12871
|
if (afArrayStr) {
|
|
12513
12872
|
catalogContent += ` /AF [${afArrayStr}] ${embeddedFilesNamesDict}`;
|
|
12514
12873
|
}
|
|
@@ -12530,8 +12889,8 @@ endobj
|
|
|
12530
12889
|
}
|
|
12531
12890
|
}
|
|
12532
12891
|
}
|
|
12533
|
-
} else if (destsStr || acroFormStr) {
|
|
12534
|
-
const catalogContent = `<< /Type /Catalog /Pages 2 0 R${destsStr}${acroFormStr} >>`;
|
|
12892
|
+
} else if (destsStr || acroFormStr || outlineCatalogStr || pageLabelsStr || viewerPrefsStr) {
|
|
12893
|
+
const catalogContent = `<< /Type /Catalog /Pages 2 0 R${destsStr}${acroFormStr}${outlineCatalogStr}${pageLabelsStr}${viewerPrefsStr} >>`;
|
|
12535
12894
|
const oldCatalog = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\n";
|
|
12536
12895
|
const newCatalog = `1 0 obj
|
|
12537
12896
|
${catalogContent}
|
|
@@ -12557,6 +12916,40 @@ endobj
|
|
|
12557
12916
|
function buildDocumentPDFBytes(params, layoutOptions) {
|
|
12558
12917
|
return toBytes(buildDocumentPDF(params, layoutOptions));
|
|
12559
12918
|
}
|
|
12919
|
+
function mapOutlineItem(item) {
|
|
12920
|
+
return {
|
|
12921
|
+
title: item.title,
|
|
12922
|
+
pageIndex: item.pageIndex,
|
|
12923
|
+
y: item.y,
|
|
12924
|
+
bold: item.bold,
|
|
12925
|
+
italic: item.italic,
|
|
12926
|
+
open: item.open,
|
|
12927
|
+
color: item.color !== void 0 ? parseColor(item.color) : void 0,
|
|
12928
|
+
children: item.children ? item.children.map(mapOutlineItem) : void 0
|
|
12929
|
+
};
|
|
12930
|
+
}
|
|
12931
|
+
function autoOutlineFromHeadings(headings) {
|
|
12932
|
+
const root = [];
|
|
12933
|
+
const stack = [];
|
|
12934
|
+
for (const h of headings) {
|
|
12935
|
+
const node = {
|
|
12936
|
+
title: h.text,
|
|
12937
|
+
pageIndex: h.pageIndex,
|
|
12938
|
+
y: h.y,
|
|
12939
|
+
children: []
|
|
12940
|
+
};
|
|
12941
|
+
while (stack.length > 0 && stack[stack.length - 1].level >= h.level) {
|
|
12942
|
+
stack.pop();
|
|
12943
|
+
}
|
|
12944
|
+
if (stack.length === 0) {
|
|
12945
|
+
root.push(node);
|
|
12946
|
+
} else {
|
|
12947
|
+
stack[stack.length - 1].children.push(node);
|
|
12948
|
+
}
|
|
12949
|
+
stack.push({ level: h.level, children: node.children });
|
|
12950
|
+
}
|
|
12951
|
+
return root;
|
|
12952
|
+
}
|
|
12560
12953
|
|
|
12561
12954
|
// src/core/pdf-signature.ts
|
|
12562
12955
|
init_sha();
|
|
@@ -12566,6 +12959,17 @@ init_asn1();
|
|
|
12566
12959
|
init_sha();
|
|
12567
12960
|
init_rsa();
|
|
12568
12961
|
init_ecdsa();
|
|
12962
|
+
|
|
12963
|
+
// src/crypto/crypto-provider.ts
|
|
12964
|
+
var _cryptoProvider = null;
|
|
12965
|
+
function setCryptoProvider(provider) {
|
|
12966
|
+
_cryptoProvider = provider;
|
|
12967
|
+
}
|
|
12968
|
+
function getCryptoProvider() {
|
|
12969
|
+
return _cryptoProvider;
|
|
12970
|
+
}
|
|
12971
|
+
|
|
12972
|
+
// src/crypto/cms.ts
|
|
12569
12973
|
var OID_SIGNED_DATA = new Uint8Array([42, 134, 72, 134, 247, 13, 1, 7, 2]);
|
|
12570
12974
|
var OID_DATA = new Uint8Array([42, 134, 72, 134, 247, 13, 1, 7, 1]);
|
|
12571
12975
|
var OID_SHA256 = new Uint8Array([96, 134, 72, 1, 101, 3, 4, 2, 1]);
|
|
@@ -12625,18 +13029,26 @@ function buildSignerInfo(options) {
|
|
|
12625
13029
|
const signedAttrsContent = concatUint8Arrays(attrContentType, attrMessageDigest, attrSigningTime);
|
|
12626
13030
|
const signedAttrsImplicit = derWrap(160, signedAttrsContent);
|
|
12627
13031
|
const signedAttrsForSig = derSet(attrContentType, attrMessageDigest, attrSigningTime);
|
|
12628
|
-
const
|
|
13032
|
+
const provider = options.provider ?? getCryptoProvider();
|
|
12629
13033
|
let sigAlgId;
|
|
12630
13034
|
let signatureValue;
|
|
12631
13035
|
if (algorithm === "rsa-sha256") {
|
|
12632
|
-
if (!options.rsaKey) throw new Error("RSA private key required for rsa-sha256");
|
|
12633
13036
|
sigAlgId = derSequence(derOid(OID_SHA256_RSA), derNull());
|
|
12634
|
-
|
|
13037
|
+
if (provider) {
|
|
13038
|
+
signatureValue = provider.sign(signedAttrsForSig, algorithm);
|
|
13039
|
+
} else {
|
|
13040
|
+
if (!options.rsaKey) throw new Error("RSA private key (or a crypto provider) required for rsa-sha256");
|
|
13041
|
+
signatureValue = rsaSignHash(sha256(signedAttrsForSig), options.rsaKey);
|
|
13042
|
+
}
|
|
12635
13043
|
} else if (algorithm === "ecdsa-sha256") {
|
|
12636
|
-
if (!options.ecKey) throw new Error("ECDSA private key required for ecdsa-sha256");
|
|
12637
13044
|
sigAlgId = derSequence(derOid(OID_ECDSA_SHA256));
|
|
12638
|
-
|
|
12639
|
-
|
|
13045
|
+
if (provider) {
|
|
13046
|
+
signatureValue = provider.sign(signedAttrsForSig, algorithm);
|
|
13047
|
+
} else {
|
|
13048
|
+
if (!options.ecKey) throw new Error("ECDSA private key (or a crypto provider) required for ecdsa-sha256");
|
|
13049
|
+
const { r, s } = ecdsaSignHash(sha256(signedAttrsForSig), options.ecKey);
|
|
13050
|
+
signatureValue = encodeDerSignature(r, s);
|
|
13051
|
+
}
|
|
12640
13052
|
} else {
|
|
12641
13053
|
throw new Error(`Unsupported algorithm: ${algorithm}`);
|
|
12642
13054
|
}
|
|
@@ -12715,7 +13127,8 @@ function signPdfBytes(pdfBytes, options) {
|
|
|
12715
13127
|
rsaKey: options.rsaKey,
|
|
12716
13128
|
ecKey: options.ecKey,
|
|
12717
13129
|
algorithm,
|
|
12718
|
-
signingTime: options.signingTime
|
|
13130
|
+
signingTime: options.signingTime,
|
|
13131
|
+
provider: options.provider
|
|
12719
13132
|
};
|
|
12720
13133
|
const cms = buildCmsSignedData(cmsOptions);
|
|
12721
13134
|
if (cms.length * 2 > hexLen) {
|
|
@@ -14532,6 +14945,68 @@ async function streamByteLength(stream) {
|
|
|
14532
14945
|
}
|
|
14533
14946
|
return total;
|
|
14534
14947
|
}
|
|
14948
|
+
async function streamToFile(stream, filePath, opts) {
|
|
14949
|
+
let fs;
|
|
14950
|
+
try {
|
|
14951
|
+
fs = await import('fs');
|
|
14952
|
+
} catch {
|
|
14953
|
+
throw new Error("streamToFile requires a Node.js environment (node:fs is unavailable)");
|
|
14954
|
+
}
|
|
14955
|
+
const signal = opts?.signal;
|
|
14956
|
+
if (signal?.aborted) throw new Error("streamToFile aborted before start");
|
|
14957
|
+
const ws = fs.createWriteStream(filePath);
|
|
14958
|
+
let bytesWritten = 0;
|
|
14959
|
+
const onAbort = () => {
|
|
14960
|
+
ws.destroy(new Error("streamToFile aborted"));
|
|
14961
|
+
};
|
|
14962
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
14963
|
+
try {
|
|
14964
|
+
await new Promise((resolve, reject) => {
|
|
14965
|
+
ws.on("error", reject);
|
|
14966
|
+
ws.on("open", () => resolve());
|
|
14967
|
+
});
|
|
14968
|
+
for await (const chunk of stream) {
|
|
14969
|
+
if (signal?.aborted) throw new Error("streamToFile aborted");
|
|
14970
|
+
bytesWritten += chunk.length;
|
|
14971
|
+
const ok = ws.write(chunk);
|
|
14972
|
+
if (!ok) {
|
|
14973
|
+
await new Promise((resolve, reject) => {
|
|
14974
|
+
const onErr = (e) => {
|
|
14975
|
+
ws.off("drain", onDrain);
|
|
14976
|
+
reject(e);
|
|
14977
|
+
};
|
|
14978
|
+
const onDrain = () => {
|
|
14979
|
+
ws.off("error", onErr);
|
|
14980
|
+
resolve();
|
|
14981
|
+
};
|
|
14982
|
+
ws.once("drain", onDrain);
|
|
14983
|
+
ws.once("error", onErr);
|
|
14984
|
+
});
|
|
14985
|
+
}
|
|
14986
|
+
}
|
|
14987
|
+
if (signal?.aborted) throw new Error("streamToFile aborted");
|
|
14988
|
+
await new Promise((resolve, reject) => {
|
|
14989
|
+
ws.end((err) => err ? reject(err) : resolve());
|
|
14990
|
+
});
|
|
14991
|
+
} catch (err) {
|
|
14992
|
+
await new Promise((resolve) => {
|
|
14993
|
+
if (ws.closed) {
|
|
14994
|
+
resolve();
|
|
14995
|
+
return;
|
|
14996
|
+
}
|
|
14997
|
+
ws.once("close", () => resolve());
|
|
14998
|
+
ws.destroy();
|
|
14999
|
+
});
|
|
15000
|
+
try {
|
|
15001
|
+
fs.rmSync(filePath, { force: true });
|
|
15002
|
+
} catch {
|
|
15003
|
+
}
|
|
15004
|
+
throw err;
|
|
15005
|
+
} finally {
|
|
15006
|
+
signal?.removeEventListener("abort", onAbort);
|
|
15007
|
+
}
|
|
15008
|
+
return { bytesWritten, path: filePath };
|
|
15009
|
+
}
|
|
14535
15010
|
var DEFAULT_CHUNK_SIZE = 65536;
|
|
14536
15011
|
var MIN_CHUNK_SIZE = 1024;
|
|
14537
15012
|
var MAX_CHUNK_SIZE = 16777216;
|
|
@@ -14747,6 +15222,123 @@ async function initCrypto() {
|
|
|
14747
15222
|
initEcdsaAsn12(asn1);
|
|
14748
15223
|
}
|
|
14749
15224
|
|
|
15225
|
+
// src/fonts/font-validator.ts
|
|
15226
|
+
var SFNT_MAGIC = /* @__PURE__ */ new Set([
|
|
15227
|
+
65536,
|
|
15228
|
+
// TrueType outlines
|
|
15229
|
+
1330926671,
|
|
15230
|
+
// 'OTTO' — CFF/OpenType outlines
|
|
15231
|
+
1953658213,
|
|
15232
|
+
// 'true' — legacy Apple TrueType
|
|
15233
|
+
1953784678
|
|
15234
|
+
// 'ttcf' — TrueType Collection
|
|
15235
|
+
]);
|
|
15236
|
+
function decodeBase64Prefix(b64, maxBytes) {
|
|
15237
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) return null;
|
|
15238
|
+
if (b64.length % 4 !== 0) return null;
|
|
15239
|
+
const g = globalThis;
|
|
15240
|
+
try {
|
|
15241
|
+
const atobFn = g["atob"];
|
|
15242
|
+
if (typeof atobFn === "function") {
|
|
15243
|
+
const need = Math.ceil(maxBytes / 3 * 4 / 4) * 4;
|
|
15244
|
+
const slice = b64.slice(0, Math.min(b64.length, need));
|
|
15245
|
+
const bin = atobFn(slice);
|
|
15246
|
+
const out = new Uint8Array(Math.min(bin.length, maxBytes));
|
|
15247
|
+
for (let i = 0; i < out.length; i++) out[i] = bin.charCodeAt(i) & 255;
|
|
15248
|
+
return out;
|
|
15249
|
+
}
|
|
15250
|
+
const bufCtor = g["Buffer"];
|
|
15251
|
+
if (bufCtor?.from) {
|
|
15252
|
+
return bufCtor.from(b64, "base64").subarray(0, maxBytes);
|
|
15253
|
+
}
|
|
15254
|
+
} catch {
|
|
15255
|
+
return null;
|
|
15256
|
+
}
|
|
15257
|
+
return null;
|
|
15258
|
+
}
|
|
15259
|
+
function validateFontData(data) {
|
|
15260
|
+
const errors = [];
|
|
15261
|
+
const warnings = [];
|
|
15262
|
+
if (data === null || typeof data !== "object") {
|
|
15263
|
+
return { valid: false, errors: ["font data must be a non-null object"], warnings };
|
|
15264
|
+
}
|
|
15265
|
+
const f = data;
|
|
15266
|
+
const m = f.metrics;
|
|
15267
|
+
if (!m || typeof m !== "object") {
|
|
15268
|
+
errors.push("missing or invalid `metrics` object");
|
|
15269
|
+
} else {
|
|
15270
|
+
const finiteFields = ["unitsPerEm", "numGlyphs", "ascent", "descent", "capHeight", "stemV"];
|
|
15271
|
+
const mRec = m;
|
|
15272
|
+
for (const k of finiteFields) {
|
|
15273
|
+
const v = mRec[k];
|
|
15274
|
+
if (typeof v !== "number" || !Number.isFinite(v)) {
|
|
15275
|
+
errors.push(`metrics.${String(k)} must be a finite number`);
|
|
15276
|
+
}
|
|
15277
|
+
}
|
|
15278
|
+
if (typeof m.unitsPerEm === "number" && m.unitsPerEm <= 0) {
|
|
15279
|
+
errors.push("metrics.unitsPerEm must be positive");
|
|
15280
|
+
}
|
|
15281
|
+
if (!Array.isArray(m.bbox) || m.bbox.length !== 4 || !m.bbox.every((n2) => typeof n2 === "number" && Number.isFinite(n2))) {
|
|
15282
|
+
errors.push("metrics.bbox must be a 4-number array [xMin yMin xMax yMax]");
|
|
15283
|
+
}
|
|
15284
|
+
}
|
|
15285
|
+
if (typeof f.fontName !== "string" || f.fontName.length === 0) {
|
|
15286
|
+
errors.push("`fontName` must be a non-empty string");
|
|
15287
|
+
}
|
|
15288
|
+
const cmap = f.cmap;
|
|
15289
|
+
let cmapEntries = 0;
|
|
15290
|
+
if (!cmap || typeof cmap !== "object") {
|
|
15291
|
+
errors.push("missing or invalid `cmap` (codepoint \u2192 glyph id map)");
|
|
15292
|
+
} else {
|
|
15293
|
+
cmapEntries = Object.keys(cmap).length;
|
|
15294
|
+
if (cmapEntries === 0) {
|
|
15295
|
+
errors.push("`cmap` is empty \u2014 the font maps no characters");
|
|
15296
|
+
}
|
|
15297
|
+
}
|
|
15298
|
+
const widths = f.widths;
|
|
15299
|
+
if (!widths || typeof widths !== "object") {
|
|
15300
|
+
errors.push("missing or invalid `widths` (glyph id \u2192 advance map)");
|
|
15301
|
+
}
|
|
15302
|
+
if (cmap && typeof cmap === "object" && widths && typeof widths === "object") {
|
|
15303
|
+
const numGlyphs = m && typeof m.numGlyphs === "number" ? m.numGlyphs : Infinity;
|
|
15304
|
+
let missingWidth = 0;
|
|
15305
|
+
let outOfRange = 0;
|
|
15306
|
+
for (const gid of Object.values(cmap)) {
|
|
15307
|
+
if (typeof gid !== "number" || !Number.isInteger(gid) || gid < 0) {
|
|
15308
|
+
outOfRange++;
|
|
15309
|
+
continue;
|
|
15310
|
+
}
|
|
15311
|
+
if (Number.isFinite(numGlyphs) && gid >= numGlyphs) outOfRange++;
|
|
15312
|
+
if (widths[gid] === void 0) missingWidth++;
|
|
15313
|
+
}
|
|
15314
|
+
if (outOfRange > 0) {
|
|
15315
|
+
errors.push(`${outOfRange} cmap entr${outOfRange === 1 ? "y maps" : "ies map"} to an out-of-range glyph id`);
|
|
15316
|
+
}
|
|
15317
|
+
if (missingWidth > 0) {
|
|
15318
|
+
warnings.push(`${missingWidth} cmap glyph id(s) have no explicit width (defaultWidth will be used)`);
|
|
15319
|
+
}
|
|
15320
|
+
}
|
|
15321
|
+
if (typeof f.pdfWidthArray !== "string" || f.pdfWidthArray.length === 0) {
|
|
15322
|
+
errors.push("`pdfWidthArray` must be a non-empty PDF /W array string");
|
|
15323
|
+
} else if (!/^\s*\d/.test(f.pdfWidthArray)) {
|
|
15324
|
+
warnings.push("`pdfWidthArray` does not begin with a glyph index \u2014 verify the /W array format");
|
|
15325
|
+
}
|
|
15326
|
+
if (typeof f.ttfBase64 !== "string" || f.ttfBase64.length === 0) {
|
|
15327
|
+
errors.push("`ttfBase64` must be a non-empty base64 string");
|
|
15328
|
+
} else {
|
|
15329
|
+
const head = decodeBase64Prefix(f.ttfBase64, 4);
|
|
15330
|
+
if (!head || head.length < 4) {
|
|
15331
|
+
errors.push("`ttfBase64` is not valid base64");
|
|
15332
|
+
} else {
|
|
15333
|
+
const magic = (head[0] << 24 | head[1] << 16 | head[2] << 8 | head[3]) >>> 0;
|
|
15334
|
+
if (!SFNT_MAGIC.has(magic)) {
|
|
15335
|
+
errors.push(`\`ttfBase64\` is not an SFNT font (unexpected magic 0x${magic.toString(16).padStart(8, "0")})`);
|
|
15336
|
+
}
|
|
15337
|
+
}
|
|
15338
|
+
}
|
|
15339
|
+
return { valid: errors.length === 0, errors, warnings };
|
|
15340
|
+
}
|
|
15341
|
+
|
|
14750
15342
|
// src/fonts/colr-parser.ts
|
|
14751
15343
|
var IDENTITY = [1, 0, 0, 1, 0, 0];
|
|
14752
15344
|
function compose(outer, inner) {
|
|
@@ -14863,6 +15455,22 @@ function resolveFill(ctx, offset, m) {
|
|
|
14863
15455
|
const s = avgScale(m);
|
|
14864
15456
|
return { kind: "radial", c0: apply(m, x0, y0), r0: r0 * s, c1: apply(m, x1, y1), r1: r1 * s, stops, extend };
|
|
14865
15457
|
}
|
|
15458
|
+
case 8: {
|
|
15459
|
+
const colorLineOffset = getUint24(view, offset + 1);
|
|
15460
|
+
const cx = view.getInt16(offset + 4), cy = view.getInt16(offset + 6);
|
|
15461
|
+
const startAngle = f2dot14(view, offset + 8) * 180;
|
|
15462
|
+
const endAngle = f2dot14(view, offset + 10) * 180;
|
|
15463
|
+
const { stops, extend } = readColorLine(ctx, offset + colorLineOffset);
|
|
15464
|
+
const rot = Math.atan2(m[1], m[0]) * 180 / Math.PI;
|
|
15465
|
+
return {
|
|
15466
|
+
kind: "sweep",
|
|
15467
|
+
center: apply(m, cx, cy),
|
|
15468
|
+
startAngle: startAngle + rot,
|
|
15469
|
+
endAngle: endAngle + rot,
|
|
15470
|
+
stops,
|
|
15471
|
+
extend
|
|
15472
|
+
};
|
|
15473
|
+
}
|
|
14866
15474
|
case 12: {
|
|
14867
15475
|
const subOffset = getUint24(view, offset + 1);
|
|
14868
15476
|
const transformOffset = getUint24(view, offset + 4);
|
|
@@ -14892,7 +15500,7 @@ function readAffine(view, pos) {
|
|
|
14892
15500
|
const dy = fixed(view, pos + 20);
|
|
14893
15501
|
return [xx, yx, xy, yy, dx, dy];
|
|
14894
15502
|
}
|
|
14895
|
-
function collectLayers(ctx, offset, m, out, depth) {
|
|
15503
|
+
function collectLayers(ctx, offset, m, out, depth, blendMode) {
|
|
14896
15504
|
if (depth > 16) throw new UnsupportedPaint("paint recursion too deep");
|
|
14897
15505
|
const { view } = ctx;
|
|
14898
15506
|
const format = view.getUint8(offset);
|
|
@@ -14904,7 +15512,7 @@ function collectLayers(ctx, offset, m, out, depth) {
|
|
|
14904
15512
|
for (let i = 0; i < numLayers; i++) {
|
|
14905
15513
|
const idx = firstLayerIndex + i;
|
|
14906
15514
|
const paintOffset = view.getUint32(ctx.layerListBase + 4 + idx * 4);
|
|
14907
|
-
collectLayers(ctx, ctx.layerListBase + paintOffset, m, out, depth + 1);
|
|
15515
|
+
collectLayers(ctx, ctx.layerListBase + paintOffset, m, out, depth + 1, blendMode);
|
|
14908
15516
|
}
|
|
14909
15517
|
return;
|
|
14910
15518
|
}
|
|
@@ -14912,39 +15520,91 @@ function collectLayers(ctx, offset, m, out, depth) {
|
|
|
14912
15520
|
const subOffset = getUint24(view, offset + 1);
|
|
14913
15521
|
const glyphId = view.getUint16(offset + 4);
|
|
14914
15522
|
const paint = resolveFill(ctx, offset + subOffset, IDENTITY);
|
|
14915
|
-
|
|
15523
|
+
const layer = m === IDENTITY ? { glyphId, paint } : { glyphId, paint, transform: m };
|
|
15524
|
+
out.push(blendMode ? { ...layer, blendMode } : layer);
|
|
14916
15525
|
return;
|
|
14917
15526
|
}
|
|
14918
15527
|
case 11: {
|
|
14919
15528
|
const glyphId = view.getUint16(offset + 1);
|
|
14920
15529
|
const paintOffset = baseGlyphPaintOffset(ctx, glyphId);
|
|
14921
15530
|
if (paintOffset === null) throw new UnsupportedPaint("PaintColrGlyph missing base");
|
|
14922
|
-
collectLayers(ctx, paintOffset, m, out, depth + 1);
|
|
15531
|
+
collectLayers(ctx, paintOffset, m, out, depth + 1, blendMode);
|
|
14923
15532
|
return;
|
|
14924
15533
|
}
|
|
14925
15534
|
case 12: {
|
|
14926
15535
|
const subOffset = getUint24(view, offset + 1);
|
|
14927
15536
|
const transformOffset = getUint24(view, offset + 4);
|
|
14928
15537
|
const t = readAffine(view, offset + transformOffset);
|
|
14929
|
-
collectLayers(ctx, offset + subOffset, compose(m, t), out, depth + 1);
|
|
15538
|
+
collectLayers(ctx, offset + subOffset, compose(m, t), out, depth + 1, blendMode);
|
|
14930
15539
|
return;
|
|
14931
15540
|
}
|
|
14932
15541
|
case 14: {
|
|
14933
15542
|
const subOffset = getUint24(view, offset + 1);
|
|
14934
15543
|
const dx = view.getInt16(offset + 4), dy = view.getInt16(offset + 6);
|
|
14935
|
-
collectLayers(ctx, offset + subOffset, compose(m, [1, 0, 0, 1, dx, dy]), out, depth + 1);
|
|
15544
|
+
collectLayers(ctx, offset + subOffset, compose(m, [1, 0, 0, 1, dx, dy]), out, depth + 1, blendMode);
|
|
14936
15545
|
return;
|
|
14937
15546
|
}
|
|
14938
15547
|
case 16: {
|
|
14939
15548
|
const subOffset = getUint24(view, offset + 1);
|
|
14940
15549
|
const sx = f2dot14(view, offset + 4), sy = f2dot14(view, offset + 6);
|
|
14941
|
-
collectLayers(ctx, offset + subOffset, compose(m, [sx, 0, 0, sy, 0, 0]), out, depth + 1);
|
|
15550
|
+
collectLayers(ctx, offset + subOffset, compose(m, [sx, 0, 0, sy, 0, 0]), out, depth + 1, blendMode);
|
|
15551
|
+
return;
|
|
15552
|
+
}
|
|
15553
|
+
case 32: {
|
|
15554
|
+
const sourceOffset = getUint24(view, offset + 1);
|
|
15555
|
+
const mode = view.getUint8(offset + 4);
|
|
15556
|
+
const backdropOffset = getUint24(view, offset + 5);
|
|
15557
|
+
const bm = compositeModeToBlendMode(mode);
|
|
15558
|
+
if (bm === null) throw new UnsupportedPaint(`composite mode ${mode}`);
|
|
15559
|
+
collectLayers(ctx, offset + backdropOffset, m, out, depth + 1, blendMode);
|
|
15560
|
+
collectLayers(ctx, offset + sourceOffset, m, out, depth + 1, bm === "Normal" ? blendMode : bm);
|
|
14942
15561
|
return;
|
|
14943
15562
|
}
|
|
14944
15563
|
default:
|
|
14945
15564
|
throw new UnsupportedPaint(`structural paint format ${format}`);
|
|
14946
15565
|
}
|
|
14947
15566
|
}
|
|
15567
|
+
function compositeModeToBlendMode(mode) {
|
|
15568
|
+
switch (mode) {
|
|
15569
|
+
case 3:
|
|
15570
|
+
return "Normal";
|
|
15571
|
+
// SRC_OVER
|
|
15572
|
+
case 13:
|
|
15573
|
+
return "Screen";
|
|
15574
|
+
case 14:
|
|
15575
|
+
return "Overlay";
|
|
15576
|
+
case 15:
|
|
15577
|
+
return "Darken";
|
|
15578
|
+
case 16:
|
|
15579
|
+
return "Lighten";
|
|
15580
|
+
case 17:
|
|
15581
|
+
return "ColorDodge";
|
|
15582
|
+
case 18:
|
|
15583
|
+
return "ColorBurn";
|
|
15584
|
+
case 19:
|
|
15585
|
+
return "HardLight";
|
|
15586
|
+
case 20:
|
|
15587
|
+
return "SoftLight";
|
|
15588
|
+
case 21:
|
|
15589
|
+
return "Difference";
|
|
15590
|
+
case 22:
|
|
15591
|
+
return "Exclusion";
|
|
15592
|
+
case 23:
|
|
15593
|
+
return "Multiply";
|
|
15594
|
+
case 24:
|
|
15595
|
+
return "Hue";
|
|
15596
|
+
case 25:
|
|
15597
|
+
return "Saturation";
|
|
15598
|
+
case 26:
|
|
15599
|
+
return "Color";
|
|
15600
|
+
case 27:
|
|
15601
|
+
return "Luminosity";
|
|
15602
|
+
// 0 CLEAR, 1 SRC, 2 DEST, 4 DEST_OVER, 5 SRC_IN, 6 DEST_IN, 7 SRC_OUT,
|
|
15603
|
+
// 8 DEST_OUT, 9 SRC_ATOP, 10 DEST_ATOP, 11 XOR, 12 PLUS → unsupported.
|
|
15604
|
+
default:
|
|
15605
|
+
return null;
|
|
15606
|
+
}
|
|
15607
|
+
}
|
|
14948
15608
|
function baseGlyphPaintOffset(ctx, glyphId) {
|
|
14949
15609
|
const { view, colrBase } = ctx;
|
|
14950
15610
|
const baseGlyphListOffset = view.getUint32(colrBase + 14);
|
|
@@ -15020,6 +15680,314 @@ function parseColrCpal(bytes) {
|
|
|
15020
15680
|
return Object.keys(result).length ? result : null;
|
|
15021
15681
|
}
|
|
15022
15682
|
|
|
15683
|
+
// src/parser/pdf-pagetree.ts
|
|
15684
|
+
init_pdf_encrypt();
|
|
15685
|
+
var MAX_MERGE_SOURCES = 50;
|
|
15686
|
+
var DEFAULT_MEDIA_BOX = "[0 0 612 792]";
|
|
15687
|
+
var INHERITABLE_KEYS = ["MediaBox", "CropBox", "Rotate"];
|
|
15688
|
+
var MAX_COPY_DEPTH = 2e3;
|
|
15689
|
+
var DEFAULT_MAX_OUTPUT_SIZE = 256 * 1024 * 1024;
|
|
15690
|
+
function resolveMaxOutputSize(value) {
|
|
15691
|
+
if (value === void 0) return DEFAULT_MAX_OUTPUT_SIZE;
|
|
15692
|
+
if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
|
|
15693
|
+
throw new Error(
|
|
15694
|
+
`maxOutputSize must be a positive number or Infinity (got ${String(value)})`
|
|
15695
|
+
);
|
|
15696
|
+
}
|
|
15697
|
+
return value;
|
|
15698
|
+
}
|
|
15699
|
+
function mergePdfs(sources, opts) {
|
|
15700
|
+
if (sources.length === 0) throw new Error("mergePdfs requires at least one source PDF");
|
|
15701
|
+
if (sources.length > MAX_MERGE_SOURCES) {
|
|
15702
|
+
throw new Error(`mergePdfs supports at most ${MAX_MERGE_SOURCES} sources (got ${sources.length})`);
|
|
15703
|
+
}
|
|
15704
|
+
resolveMaxOutputSize(opts?.maxOutputSize);
|
|
15705
|
+
const specs = [];
|
|
15706
|
+
for (const src of sources) {
|
|
15707
|
+
const reader = openPdf(src);
|
|
15708
|
+
assertNotEncrypted(reader);
|
|
15709
|
+
const count = reader.pageCount;
|
|
15710
|
+
for (let i = 0; i < count; i++) specs.push({ reader, pageIndex: i });
|
|
15711
|
+
}
|
|
15712
|
+
return assemble(specs, opts ?? {});
|
|
15713
|
+
}
|
|
15714
|
+
function extractPages(src, pageIndices, opts) {
|
|
15715
|
+
if (pageIndices.length === 0) throw new Error("extractPages requires at least one page index");
|
|
15716
|
+
resolveMaxOutputSize(opts?.maxOutputSize);
|
|
15717
|
+
const reader = openPdf(src);
|
|
15718
|
+
assertNotEncrypted(reader);
|
|
15719
|
+
const count = reader.pageCount;
|
|
15720
|
+
const specs = [];
|
|
15721
|
+
for (const idx of pageIndices) {
|
|
15722
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= count) {
|
|
15723
|
+
throw new Error(`extractPages page index ${idx} out of range (0-${count - 1})`);
|
|
15724
|
+
}
|
|
15725
|
+
specs.push({ reader, pageIndex: idx });
|
|
15726
|
+
}
|
|
15727
|
+
return assemble(specs, opts ?? {});
|
|
15728
|
+
}
|
|
15729
|
+
function splitPdf(src, ranges, opts) {
|
|
15730
|
+
if (ranges.length === 0) throw new Error("splitPdf requires at least one range");
|
|
15731
|
+
resolveMaxOutputSize(opts?.maxOutputSize);
|
|
15732
|
+
const reader = openPdf(src);
|
|
15733
|
+
assertNotEncrypted(reader);
|
|
15734
|
+
const count = reader.pageCount;
|
|
15735
|
+
const out = [];
|
|
15736
|
+
for (const range of ranges) {
|
|
15737
|
+
const start = range.start | 0;
|
|
15738
|
+
const end = (range.end ?? range.start) | 0;
|
|
15739
|
+
if (start < 0 || end < start || end >= count) {
|
|
15740
|
+
throw new Error(`splitPdf range [${start}, ${end}] invalid for ${count}-page document`);
|
|
15741
|
+
}
|
|
15742
|
+
const specs = [];
|
|
15743
|
+
for (let i = start; i <= end; i++) specs.push({ reader, pageIndex: i });
|
|
15744
|
+
out.push(assemble(specs, opts ?? {}));
|
|
15745
|
+
}
|
|
15746
|
+
return out;
|
|
15747
|
+
}
|
|
15748
|
+
function assertNotEncrypted(reader) {
|
|
15749
|
+
if (reader.trailer.get("Encrypt") !== void 0) {
|
|
15750
|
+
throw new Error("Encrypted PDFs are not supported by the page-tree API (decrypt first)");
|
|
15751
|
+
}
|
|
15752
|
+
}
|
|
15753
|
+
function resolveInherited(reader, page, key) {
|
|
15754
|
+
let node = page;
|
|
15755
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15756
|
+
while (node && !seen.has(node)) {
|
|
15757
|
+
seen.add(node);
|
|
15758
|
+
const v = node.get(key);
|
|
15759
|
+
if (v !== void 0) return v;
|
|
15760
|
+
const parent = node.get("Parent");
|
|
15761
|
+
if (parent === void 0) break;
|
|
15762
|
+
const resolved = reader.resolveValue(parent);
|
|
15763
|
+
node = isDict(resolved) ? resolved : void 0;
|
|
15764
|
+
}
|
|
15765
|
+
return void 0;
|
|
15766
|
+
}
|
|
15767
|
+
function assemble(specs, opts) {
|
|
15768
|
+
const ctx = {
|
|
15769
|
+
nextNum: 3,
|
|
15770
|
+
bodies: /* @__PURE__ */ new Map(),
|
|
15771
|
+
memo: /* @__PURE__ */ new Map(),
|
|
15772
|
+
maxOutputSize: resolveMaxOutputSize(opts.maxOutputSize),
|
|
15773
|
+
totalBytes: 0
|
|
15774
|
+
};
|
|
15775
|
+
const pageNums = [];
|
|
15776
|
+
for (const spec of specs) {
|
|
15777
|
+
pageNums.push(copyPage(ctx, spec, opts));
|
|
15778
|
+
}
|
|
15779
|
+
const kids = pageNums.map((n2) => `${n2} 0 R`).join(" ");
|
|
15780
|
+
setBody(ctx, 2, `<< /Type /Pages /Kids [${kids}] /Count ${pageNums.length} >>`);
|
|
15781
|
+
setBody(ctx, 1, "<< /Type /Catalog /Pages 2 0 R >>");
|
|
15782
|
+
return serializeDocument(ctx);
|
|
15783
|
+
}
|
|
15784
|
+
function accountBytes(ctx, n2) {
|
|
15785
|
+
ctx.totalBytes += n2;
|
|
15786
|
+
if (ctx.totalBytes > ctx.maxOutputSize) {
|
|
15787
|
+
throw new Error(
|
|
15788
|
+
`page-tree output exceeded the ${ctx.maxOutputSize}-byte maxOutputSize limit (raise MergeOptions.maxOutputSize or pass Infinity to disable)`
|
|
15789
|
+
);
|
|
15790
|
+
}
|
|
15791
|
+
}
|
|
15792
|
+
function setBody(ctx, num, body) {
|
|
15793
|
+
accountBytes(ctx, body.length);
|
|
15794
|
+
ctx.bodies.set(num, body);
|
|
15795
|
+
}
|
|
15796
|
+
function memoFor(ctx, reader) {
|
|
15797
|
+
let m = ctx.memo.get(reader);
|
|
15798
|
+
if (!m) {
|
|
15799
|
+
m = /* @__PURE__ */ new Map();
|
|
15800
|
+
ctx.memo.set(reader, m);
|
|
15801
|
+
}
|
|
15802
|
+
return m;
|
|
15803
|
+
}
|
|
15804
|
+
function copyPage(ctx, spec, opts) {
|
|
15805
|
+
const { reader, pageIndex } = spec;
|
|
15806
|
+
const page = reader.getPage(pageIndex);
|
|
15807
|
+
const pageNum = ctx.nextNum++;
|
|
15808
|
+
const parts = ["/Type /Page", "/Parent 2 0 R"];
|
|
15809
|
+
for (const key of INHERITABLE_KEYS) {
|
|
15810
|
+
const v = resolveInherited(reader, page, key);
|
|
15811
|
+
if (v !== void 0) {
|
|
15812
|
+
parts.push(`/${key} ${serializeValue2(rewrite(ctx, reader, v))}`);
|
|
15813
|
+
} else if (key === "MediaBox") {
|
|
15814
|
+
parts.push(`/MediaBox ${DEFAULT_MEDIA_BOX}`);
|
|
15815
|
+
}
|
|
15816
|
+
}
|
|
15817
|
+
const res = resolveInherited(reader, page, "Resources");
|
|
15818
|
+
parts.push(`/Resources ${res !== void 0 ? serializeValue2(rewrite(ctx, reader, res)) : "<< >>"}`);
|
|
15819
|
+
const contents = page.get("Contents");
|
|
15820
|
+
if (contents !== void 0) {
|
|
15821
|
+
parts.push(`/Contents ${serializeValue2(rewrite(ctx, reader, contents))}`);
|
|
15822
|
+
}
|
|
15823
|
+
if (!opts.dropAnnotations) {
|
|
15824
|
+
const annots = filterAnnotations(ctx, reader, page);
|
|
15825
|
+
if (annots) parts.push(`/Annots ${annots}`);
|
|
15826
|
+
}
|
|
15827
|
+
setBody(ctx, pageNum, `<< ${parts.join(" ")} >>`);
|
|
15828
|
+
return pageNum;
|
|
15829
|
+
}
|
|
15830
|
+
function filterAnnotations(ctx, reader, page) {
|
|
15831
|
+
const annotsVal = page.get("Annots");
|
|
15832
|
+
if (annotsVal === void 0) return void 0;
|
|
15833
|
+
const arr = reader.resolveValue(annotsVal);
|
|
15834
|
+
if (!isArray(arr)) return void 0;
|
|
15835
|
+
const kept = [];
|
|
15836
|
+
for (const a of arr) {
|
|
15837
|
+
const ad = reader.resolveValue(a);
|
|
15838
|
+
if (!isDict(ad)) continue;
|
|
15839
|
+
if (dictGetName(ad, "Subtype") !== "Link") continue;
|
|
15840
|
+
const action = reader.resolveValue(ad.get("A") ?? null);
|
|
15841
|
+
if (!isDict(action) || dictGetName(action, "S") !== "URI") continue;
|
|
15842
|
+
const clean = /* @__PURE__ */ new Map();
|
|
15843
|
+
for (const [k, v] of ad) {
|
|
15844
|
+
if (k === "P" || k === "Parent") continue;
|
|
15845
|
+
clean.set(k, rewrite(ctx, reader, v));
|
|
15846
|
+
}
|
|
15847
|
+
kept.push(serializeValue2(clean));
|
|
15848
|
+
}
|
|
15849
|
+
return kept.length > 0 ? `[${kept.join(" ")}]` : void 0;
|
|
15850
|
+
}
|
|
15851
|
+
function copyObject(ctx, reader, srcNum, srcGen, depth = 0) {
|
|
15852
|
+
const memo = memoFor(ctx, reader);
|
|
15853
|
+
const existing = memo.get(srcNum);
|
|
15854
|
+
if (existing !== void 0) return existing;
|
|
15855
|
+
const newNum = ctx.nextNum++;
|
|
15856
|
+
memo.set(srcNum, newNum);
|
|
15857
|
+
const resolved = reader.resolve({ type: "ref", num: srcNum, gen: srcGen });
|
|
15858
|
+
if (isStream(resolved)) {
|
|
15859
|
+
ctx.bodies.set(newNum, serializeStreamBody(ctx, reader, resolved, depth));
|
|
15860
|
+
} else {
|
|
15861
|
+
const body = serializeValue2(rewrite(ctx, reader, resolved, depth));
|
|
15862
|
+
setBody(ctx, newNum, body);
|
|
15863
|
+
}
|
|
15864
|
+
return newNum;
|
|
15865
|
+
}
|
|
15866
|
+
function rewrite(ctx, reader, val, depth = 0) {
|
|
15867
|
+
if (depth > MAX_COPY_DEPTH) {
|
|
15868
|
+
throw new Error(
|
|
15869
|
+
`page-tree copy exceeded maximum object nesting depth (${MAX_COPY_DEPTH}) \u2014 malformed or adversarial PDF`
|
|
15870
|
+
);
|
|
15871
|
+
}
|
|
15872
|
+
if (isRef(val)) {
|
|
15873
|
+
const entry = reader.xref.entries.get(val.num);
|
|
15874
|
+
if (!entry || entry.type === 0) return null;
|
|
15875
|
+
const newNum = copyObject(ctx, reader, val.num, val.gen, depth + 1);
|
|
15876
|
+
return { type: "ref", num: newNum, gen: 0 };
|
|
15877
|
+
}
|
|
15878
|
+
if (isArray(val)) return val.map((v) => rewrite(ctx, reader, v, depth + 1));
|
|
15879
|
+
if (isStream(val)) {
|
|
15880
|
+
return val;
|
|
15881
|
+
}
|
|
15882
|
+
if (isDict(val)) {
|
|
15883
|
+
const out = /* @__PURE__ */ new Map();
|
|
15884
|
+
for (const [k, v] of val) out.set(k, rewrite(ctx, reader, v, depth + 1));
|
|
15885
|
+
return out;
|
|
15886
|
+
}
|
|
15887
|
+
return val;
|
|
15888
|
+
}
|
|
15889
|
+
function serializeStreamBody(ctx, reader, stream, depth = 0) {
|
|
15890
|
+
accountBytes(ctx, stream.data.length);
|
|
15891
|
+
const dict = /* @__PURE__ */ new Map();
|
|
15892
|
+
for (const [k, v] of stream.dict) {
|
|
15893
|
+
if (k === "Length") continue;
|
|
15894
|
+
dict.set(k, rewrite(ctx, reader, v, depth + 1));
|
|
15895
|
+
}
|
|
15896
|
+
dict.set("Length", stream.data.length);
|
|
15897
|
+
let body = serializeDict2(dict);
|
|
15898
|
+
body += "\nstream\n";
|
|
15899
|
+
body += bytesToLatin1(stream.data);
|
|
15900
|
+
body += "\nendstream";
|
|
15901
|
+
accountBytes(ctx, body.length - stream.data.length);
|
|
15902
|
+
return body;
|
|
15903
|
+
}
|
|
15904
|
+
function serializeValue2(val) {
|
|
15905
|
+
if (val === null) return "null";
|
|
15906
|
+
if (typeof val === "boolean") return val ? "true" : "false";
|
|
15907
|
+
if (typeof val === "number") {
|
|
15908
|
+
if (Number.isInteger(val)) return String(val);
|
|
15909
|
+
return val.toFixed(4).replace(/\.?0+$/, "");
|
|
15910
|
+
}
|
|
15911
|
+
if (typeof val === "string") return `(${escapePdfStr2(val)})`;
|
|
15912
|
+
if (isName(val)) return `/${val.value}`;
|
|
15913
|
+
if (isRef(val)) return `${val.num} ${val.gen} R`;
|
|
15914
|
+
if (isArray(val)) return "[" + val.map(serializeValue2).join(" ") + "]";
|
|
15915
|
+
if (isStream(val)) return serializeDict2(val.dict);
|
|
15916
|
+
if (isDict(val)) return serializeDict2(val);
|
|
15917
|
+
return "null";
|
|
15918
|
+
}
|
|
15919
|
+
function serializeDict2(dict) {
|
|
15920
|
+
let s = "<<";
|
|
15921
|
+
for (const [key, val] of dict) s += ` /${key} ${serializeValue2(val)}`;
|
|
15922
|
+
s += " >>";
|
|
15923
|
+
return s;
|
|
15924
|
+
}
|
|
15925
|
+
function escapePdfStr2(s) {
|
|
15926
|
+
return s.replace(/[\\()]/g, (c) => "\\" + c);
|
|
15927
|
+
}
|
|
15928
|
+
function bytesToLatin1(bytes) {
|
|
15929
|
+
let s = "";
|
|
15930
|
+
const CHUNK = 32768;
|
|
15931
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
15932
|
+
s += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
15933
|
+
}
|
|
15934
|
+
return s;
|
|
15935
|
+
}
|
|
15936
|
+
function serializeDocument(ctx) {
|
|
15937
|
+
const maxNum = ctx.nextNum - 1;
|
|
15938
|
+
const parts = [];
|
|
15939
|
+
const offsets = new Array(maxNum + 1).fill(0);
|
|
15940
|
+
let offset = 0;
|
|
15941
|
+
function push(s) {
|
|
15942
|
+
parts.push(s);
|
|
15943
|
+
offset += s.length;
|
|
15944
|
+
}
|
|
15945
|
+
push("%PDF-1.7\n");
|
|
15946
|
+
push("%\xE2\xE3\xCF\xD3\n");
|
|
15947
|
+
for (let num = 1; num <= maxNum; num++) {
|
|
15948
|
+
const body = ctx.bodies.get(num);
|
|
15949
|
+
if (body === void 0) continue;
|
|
15950
|
+
offsets[num] = offset;
|
|
15951
|
+
push(`${num} 0 obj
|
|
15952
|
+
${body}
|
|
15953
|
+
endobj
|
|
15954
|
+
`);
|
|
15955
|
+
}
|
|
15956
|
+
const xrefOffset = offset;
|
|
15957
|
+
const size = maxNum + 1;
|
|
15958
|
+
let xref = `xref
|
|
15959
|
+
0 ${size}
|
|
15960
|
+
0000000000 65535 f
|
|
15961
|
+
`;
|
|
15962
|
+
for (let num = 1; num <= maxNum; num++) {
|
|
15963
|
+
xref += `${String(offsets[num]).padStart(10, "0")} 00000 n
|
|
15964
|
+
`;
|
|
15965
|
+
}
|
|
15966
|
+
push(xref);
|
|
15967
|
+
const id = bytesToHex(md5(latin1ToBytes(parts.join(""))));
|
|
15968
|
+
push(`trailer
|
|
15969
|
+
<< /Size ${size} /Root 1 0 R /ID [<${id}> <${id}>] >>
|
|
15970
|
+
`);
|
|
15971
|
+
push(`startxref
|
|
15972
|
+
${xrefOffset}
|
|
15973
|
+
%%EOF
|
|
15974
|
+
`);
|
|
15975
|
+
const full = parts.join("");
|
|
15976
|
+
const out = new Uint8Array(full.length);
|
|
15977
|
+
for (let i = 0; i < full.length; i++) out[i] = full.charCodeAt(i) & 255;
|
|
15978
|
+
return out;
|
|
15979
|
+
}
|
|
15980
|
+
function latin1ToBytes(s) {
|
|
15981
|
+
const out = new Uint8Array(s.length);
|
|
15982
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 255;
|
|
15983
|
+
return out;
|
|
15984
|
+
}
|
|
15985
|
+
function bytesToHex(bytes) {
|
|
15986
|
+
let s = "";
|
|
15987
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
15988
|
+
return s;
|
|
15989
|
+
}
|
|
15990
|
+
|
|
15023
15991
|
// src/parser/pdf-ua-validator.ts
|
|
15024
15992
|
function pageContentText(reader, page) {
|
|
15025
15993
|
const contents = page.get("Contents");
|
|
@@ -15177,6 +16145,6 @@ async function createPDF(pdfParams, options) {
|
|
|
15177
16145
|
return generatePDFMainThread(pdfParams, options?.layoutOptions);
|
|
15178
16146
|
}
|
|
15179
16147
|
|
|
15180
|
-
export { BAL_H, DEFAULT_COLORS, DEFAULT_COLUMNS, DEFAULT_CW, DEFAULT_FONT_SIZES, DEFAULT_MARGINS, DEFAULT_MAX_BLOCKS, DEFAULT_MAX_INFLATE_OUTPUT, FT_H, HEADER_H, INFO_LN, KNOWN_DECODE_FILTERS, MAX_PARSE_DEPTH, MAX_XREF_CHAIN, PAGE_SIZES, PDF_A_CONFORMANCE_TARGETS, PG_H, PG_W, ROW_H, TH_H, TITLE_LN, WORKER_THRESHOLD, WORKER_TIMEOUT_MS, addSignaturePlaceholder, applyDecodeFilter, buildAcroFormDict, buildAppearanceStreamDict, buildCmsSignedData, buildDocumentPDF, buildDocumentPDFBytes, buildDocumentPDFStream, buildDocumentPDFStreamPageByPage, buildDocumentPDFStreamTrue, buildEmbeddedFiles, buildFormWidget, buildImageOperators, buildImageXObject, buildInternalLinkAnnotation, buildLinkAnnotation, buildPDF, buildPDFBytes, buildPDFStream, buildPDFStreamPageByPage, buildPDFStreamTrue, buildRadioGroupParent, buildSMaskXObject, buildSigDict, buildWatermarkState, chunkBinaryString, classifyClusters, classifyUseCategory, clearFontCache, computeColumnPositions, concatChunks, containsArabic, containsBengali, containsDevanagari, containsEthiopic, containsHebrew, containsKhmer, containsMyanmar, containsRTL, containsSinhala, containsTamil, containsTelugu, containsThai, containsTibetan, contoursToPath, createEncodingContext, createModifier, createPDF, createTokenizer, decodeASCII85, decodeASCIIHex, decodeEcPublicKey, decodeLZW, decodeRunLength, defaultFieldHeight, derBitString, derDecode, derInteger, derOctetString, derOid, derSequence, detectCharLang, detectFallbackLangs, detectImageFormat, dictGet, dictGetArray, dictGetDict, dictGetName, dictGetNum, dictGetRef, downloadBlob, ean13CheckDigit, ecPublicKeyFromPrivate, ecdsaSign, ecdsaVerify, encodeCode128, encodeEcPublicKey, encodePDF417, encodePdfTextString, estimateCmsSize, estimateContentsSize, extractGlyphContours, findStartxref, generateDataMatrix, generatePDFInWorker, generatePDFMainThread, generateQR, getMaxInflateOutputSize, getRegisteredLangs, getTrailerRef, getTrailerValue, hasFontLoader, helveticaBoldWidth, helveticaWidth, hmacSha256, inflateSync, initCrypto, initNodeCompression, initNodeDecompression as initNodeDecompression_parser, isArmenianCodepoint, isArray, isBengaliCodepoint, isCyrillicCodepoint, isDevanagariCodepoint, isDict, isEthiopicCodepoint, isGeorgianCodepoint, isKhmerCodepoint, isLinkAnnotation, isMyanmarCodepoint, isName, isRef, isSelfSigned, isSinhalaCodepoint, isStream, isTamilCodepoint, isTeluguCodepoint, isTibetanCodepoint, isValidPdfRgb, loadFontData, nameValue, needsUnicodeFont, normalizeBidiEmbeddings, normalizeColors, openPdf, parseCertificate, parseColor, parseColrCpal, parseCpal, parseGlyfFont, parseImage, parseIndirectObject, parseJPEG, parsePNG, parseRsaPrivateKey, parseRsaPublicKey, parseSvgPath, parseValue, parseXrefTable, pdfString, registerFont, registerFonts, renderBarcode, renderCode128, renderColorGlyph, renderDataMatrix, renderEAN13, renderPDF417, renderQR, renderSvg, resetFontRegistry, resolveBidiRuns, resolveLayout, resolvePdfAConfig, resolveTemplate, rsaSign, rsaSignHash, rsaVerify, rsaVerifyHash, setDeflateImpl, setInflateImpl, setMaxInflateOutputSize, sha384, sha512, shapeArabicText, shapeBengaliText, shapeDevanagariText, shapeKhmerText, shapeMyanmarText, shapeSinhalaText, shapeTamilText, shapeTeluguText, shapeThaiText, shapeTibetanText, signPdfBytes, slugify, splitTextByFont, streamByteLength, stripBidiControls, toBytes, toWinAnsi, truncate, truncateToWidth, validateAttachments, validateDocumentStreamable, validatePdfUA, validateTableStreamable, validateURL, validateWatermark, verifyCertSignature, wrapText };
|
|
16148
|
+
export { BAL_H, DEFAULT_COLORS, DEFAULT_COLUMNS, DEFAULT_CW, DEFAULT_FONT_SIZES, DEFAULT_MARGINS, DEFAULT_MAX_BLOCKS, DEFAULT_MAX_INFLATE_OUTPUT, FT_H, HEADER_H, INFO_LN, KNOWN_DECODE_FILTERS, MAX_PARSE_DEPTH, MAX_XREF_CHAIN, PAGE_SIZES, PDF_A_CONFORMANCE_TARGETS, PG_H, PG_W, ROW_H, TH_H, TITLE_LN, WORKER_THRESHOLD, WORKER_TIMEOUT_MS, addSignaturePlaceholder, applyDecodeFilter, buildAcroFormDict, buildAppearanceStreamDict, buildCmsSignedData, buildDocumentPDF, buildDocumentPDFBytes, buildDocumentPDFStream, buildDocumentPDFStreamPageByPage, buildDocumentPDFStreamTrue, buildEmbeddedFiles, buildFormWidget, buildImageOperators, buildImageXObject, buildInternalLinkAnnotation, buildLinkAnnotation, buildPDF, buildPDFBytes, buildPDFStream, buildPDFStreamPageByPage, buildPDFStreamTrue, buildRadioGroupParent, buildSMaskXObject, buildSigDict, buildWatermarkState, chunkBinaryString, classifyClusters, classifyUseCategory, clearFontCache, computeColumnPositions, concatChunks, containsArabic, containsBengali, containsDevanagari, containsEthiopic, containsHebrew, containsKhmer, containsMyanmar, containsRTL, containsSinhala, containsTamil, containsTelugu, containsThai, containsTibetan, contoursToPath, createEncodingContext, createModifier, createPDF, createTokenizer, decodeASCII85, decodeASCIIHex, decodeEcPublicKey, decodeLZW, decodeRunLength, defaultFieldHeight, derBitString, derDecode, derInteger, derOctetString, derOid, derSequence, detectCharLang, detectFallbackLangs, detectImageFormat, dictGet, dictGetArray, dictGetDict, dictGetName, dictGetNum, dictGetRef, downloadBlob, ean13CheckDigit, ecPublicKeyFromPrivate, ecdsaSign, ecdsaVerify, encodeCode128, encodeEcPublicKey, encodePDF417, encodePdfTextString, estimateCmsSize, estimateContentsSize, extractGlyphContours, extractPages, findStartxref, generateDataMatrix, generatePDFInWorker, generatePDFMainThread, generateQR, getCryptoProvider, getMaxInflateOutputSize, getRegisteredLangs, getTrailerRef, getTrailerValue, hasFontLoader, helveticaBoldWidth, helveticaWidth, hmacSha256, inflateSync, initCrypto, initNodeCompression, initNodeDecompression as initNodeDecompression_parser, isArmenianCodepoint, isArray, isBengaliCodepoint, isCyrillicCodepoint, isDevanagariCodepoint, isDict, isEthiopicCodepoint, isGeorgianCodepoint, isKhmerCodepoint, isLinkAnnotation, isMyanmarCodepoint, isName, isRef, isSelfSigned, isSinhalaCodepoint, isStream, isTamilCodepoint, isTeluguCodepoint, isTibetanCodepoint, isValidPdfRgb, loadFontData, mergePdfs, nameValue, needsUnicodeFont, normalizeBidiEmbeddings, normalizeColors, openPdf, parseCertificate, parseColor, parseColrCpal, parseCpal, parseGlyfFont, parseImage, parseIndirectObject, parseJPEG, parsePNG, parseRsaPrivateKey, parseRsaPublicKey, parseSvgPath, parseValue, parseXrefTable, pdfString, registerFont, registerFonts, renderBarcode, renderCode128, renderColorGlyph, renderDataMatrix, renderEAN13, renderPDF417, renderQR, renderSvg, resetFontRegistry, resolveBidiRuns, resolveLayout, resolvePdfAConfig, resolveTemplate, rsaSign, rsaSignHash, rsaVerify, rsaVerifyHash, setCryptoProvider, setDeflateImpl, setInflateImpl, setMaxInflateOutputSize, sha384, sha512, shapeArabicText, shapeBengaliText, shapeDevanagariText, shapeKhmerText, shapeMyanmarText, shapeSinhalaText, shapeTamilText, shapeTeluguText, shapeThaiText, shapeTibetanText, signPdfBytes, slugify, splitPdf, splitTextByFont, streamByteLength, streamToFile, stripBidiControls, toBytes, toWinAnsi, truncate, truncateToWidth, validateAttachments, validateDocumentStreamable, validateFontData, validatePdfUA, validateTableStreamable, validateURL, validateWatermark, verifyCertSignature, wrapText };
|
|
15181
16149
|
//# sourceMappingURL=index.js.map
|
|
15182
16150
|
//# sourceMappingURL=index.js.map
|