@openworkbook/pdf 0.1.1 → 0.2.1
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/dist/index.cjs +92 -35
- package/dist/index.d.cts +15 -3
- package/dist/index.d.ts +15 -3
- package/dist/index.js +86 -29
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -4413,6 +4413,9 @@ function runFont(r, f) {
|
|
|
4413
4413
|
return `${r.italic ? "italic " : ""}${r.bold ? "bold " : ""}${size.toFixed(2)}px "${r.family || f.family}"`;
|
|
4414
4414
|
}
|
|
4415
4415
|
|
|
4416
|
+
// src/export.ts
|
|
4417
|
+
var import_core10 = require("@openworkbook/core");
|
|
4418
|
+
|
|
4416
4419
|
// src/paint.ts
|
|
4417
4420
|
var import_core2 = require("@openworkbook/core");
|
|
4418
4421
|
var import_core3 = require("@openworkbook/core");
|
|
@@ -4765,8 +4768,8 @@ var SheetPainter = class {
|
|
|
4765
4768
|
const pic = (0, import_core2.cellImageAt)(s, r, c);
|
|
4766
4769
|
if (pic) {
|
|
4767
4770
|
if (this.o.draft) return;
|
|
4768
|
-
const img = this.o.image(pic.src);
|
|
4769
|
-
(0, import_core2.drawCellImage)(this.c2d, pic, img, { x, y, w, h }, { text: st.color || t.text, font: `${Math.round((st.fontSize || t.fontSize) * 4 / 3)}px "${t.fontFamily}"
|
|
4771
|
+
const pc = { kind: pic.formula ? "formula" : "cell", sheet: s.name, row: r, col: c, output: "pdf" }, img = this.o.image(pic.src);
|
|
4772
|
+
(0, import_core2.drawCellImage)(this.c2d, pic, img, { x, y, w, h }, { text: st.color || t.text, font: `${Math.round((st.fontSize || t.fontSize) * 4 / 3)}px "${t.fontFamily}"`, blocked: !img && this.o.painter.pictureBlocked(pic.src, pc) });
|
|
4770
4773
|
if (cell.link) this.link(cell.link, x, y, w, h, [r, c]);
|
|
4771
4774
|
return;
|
|
4772
4775
|
}
|
|
@@ -5061,8 +5064,8 @@ var SheetPainter = class {
|
|
|
5061
5064
|
return wd;
|
|
5062
5065
|
},
|
|
5063
5066
|
loadImage: (url) => {
|
|
5064
|
-
const img = this.o.image(url);
|
|
5065
|
-
return img ? { state: "ready", image: img, width: img.naturalWidth, height: img.naturalHeight } : { state: "error", width: 0, height: 0 };
|
|
5067
|
+
const pc = { kind: "cell-type", sheet: s.name, row: r, col: c, output: "pdf" }, img = this.o.image(url);
|
|
5068
|
+
return img ? { state: "ready", image: img, width: img.naturalWidth, height: img.naturalHeight } : { state: this.o.painter.pictureBlocked(url, pc) ? "blocked" : "error", width: 0, height: 0 };
|
|
5066
5069
|
}
|
|
5067
5070
|
};
|
|
5068
5071
|
}
|
|
@@ -5350,11 +5353,22 @@ function pdfPageBreaks(sheet, options = {}) {
|
|
|
5350
5353
|
}
|
|
5351
5354
|
function pdfPaintEnv(wb, options, warn) {
|
|
5352
5355
|
const images = /* @__PURE__ */ new Map();
|
|
5356
|
+
const gate = (0, import_core10.pictureGateFor)(wb, options);
|
|
5357
|
+
let blockedWarned = false;
|
|
5353
5358
|
const image = (src) => {
|
|
5354
5359
|
if (images.has(src)) return images.get(src);
|
|
5355
5360
|
let out = null;
|
|
5356
5361
|
try {
|
|
5357
|
-
const
|
|
5362
|
+
const given = options.images?.[src];
|
|
5363
|
+
if (!given && !dataUrlBytes(src) && gate.check(src, { kind: "other", output: "pdf" }).decision !== "allow") {
|
|
5364
|
+
if (!blockedWarned) {
|
|
5365
|
+
blockedWarned = true;
|
|
5366
|
+
warn("image-blocked", "Pictures from external addresses were not loaded because the picture policy blocks them (picturePolicy, allowedPictureOrigins, onLoadPicture); a placeholder is drawn instead.");
|
|
5367
|
+
}
|
|
5368
|
+
images.set(src, null);
|
|
5369
|
+
return null;
|
|
5370
|
+
}
|
|
5371
|
+
const bytes = given ?? dataUrlBytes(src)?.bytes;
|
|
5358
5372
|
if (!bytes) warn("image-not-loaded", `A picture at ${src.length > 80 ? src.slice(0, 77) + "..." : src} is not embedded: only data: URLs are read synchronously (use exportPdfAsync to download pictures, or pass their bytes in \`images\`).`);
|
|
5359
5373
|
else {
|
|
5360
5374
|
const kind = sniff(bytes);
|
|
@@ -5401,7 +5415,11 @@ function pdfPaintEnv(wb, options, warn) {
|
|
|
5401
5415
|
return out;
|
|
5402
5416
|
}
|
|
5403
5417
|
}
|
|
5404
|
-
return { defFont: (0, import_core9.getDefaultFont)(wb), warn, image, objectPainter: () =>
|
|
5418
|
+
return { defFont: (0, import_core9.getDefaultFont)(wb), warn, image, objectPainter: () => {
|
|
5419
|
+
const p = new PdfObjectPainter(wb);
|
|
5420
|
+
p.pictureGate = gate;
|
|
5421
|
+
return p;
|
|
5422
|
+
} };
|
|
5405
5423
|
}
|
|
5406
5424
|
function makeSheetPainter(env, sheet, ctx, rows, cols, setup, objects, position = 1, tags) {
|
|
5407
5425
|
const links = [];
|
|
@@ -6011,8 +6029,8 @@ var decodeURISafe = (s) => {
|
|
|
6011
6029
|
};
|
|
6012
6030
|
|
|
6013
6031
|
// src/file.ts
|
|
6014
|
-
var import_core10 = require("@openworkbook/core");
|
|
6015
6032
|
var import_core11 = require("@openworkbook/core");
|
|
6033
|
+
var import_core12 = require("@openworkbook/core");
|
|
6016
6034
|
var PDF_MIME = "application/pdf";
|
|
6017
6035
|
var toBlob = (b) => new Blob([b], { type: PDF_MIME });
|
|
6018
6036
|
var isBytes = (x) => x instanceof Uint8Array;
|
|
@@ -6085,42 +6103,79 @@ async function loadFonts(fonts) {
|
|
|
6085
6103
|
return out;
|
|
6086
6104
|
}
|
|
6087
6105
|
function asWb(src) {
|
|
6088
|
-
if (src instanceof
|
|
6089
|
-
if (src && typeof src === "object" && "workbook" in src && src.workbook instanceof
|
|
6090
|
-
return new
|
|
6106
|
+
if (src instanceof import_core12.Workbook) return src;
|
|
6107
|
+
if (src && typeof src === "object" && "workbook" in src && src.workbook instanceof import_core12.Workbook) return src.workbook;
|
|
6108
|
+
return new import_core12.Workbook(src);
|
|
6091
6109
|
}
|
|
6092
6110
|
function pictureSources(sheets) {
|
|
6093
|
-
const out = /* @__PURE__ */ new
|
|
6111
|
+
const out = /* @__PURE__ */ new Map();
|
|
6112
|
+
const add = (src, ctx) => {
|
|
6113
|
+
if (src && !out.has(src)) out.set(src, { ...ctx, output: "pdf" });
|
|
6114
|
+
};
|
|
6094
6115
|
for (const s of sheets) {
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
for (const
|
|
6099
|
-
for (const
|
|
6100
|
-
|
|
6101
|
-
if (src) out.add(src);
|
|
6102
|
-
}
|
|
6116
|
+
const sheet = s.name;
|
|
6117
|
+
for (const o of s.objects) if (o.kind === "image" && o.src) add(o.src, { kind: "object", sheet, objectId: o.id });
|
|
6118
|
+
if (s.backgroundImage && s.pageSetup.printBackground) add(s.backgroundImage, { kind: "background", sheet });
|
|
6119
|
+
for (const p of Object.values(s.pageSetup.headerFooterPictures ?? {})) if (p?.src) add(p.src, { kind: "header-footer", sheet });
|
|
6120
|
+
for (const src of (0, import_core11.cellStyleImageSources)(s)) add(src, { kind: "decoration", sheet });
|
|
6121
|
+
for (const o of s.objects) if (o.kind === "shape" && o.sparkline && /SPARK\.IMAGE/i.test(o.sparkline)) add((0, import_core11.sparkImageSource)((0, import_core11.sparkViewOf)(s, o.sparkline)), { kind: "sparkline", sheet, objectId: o.id });
|
|
6103
6122
|
for (const rule of s.condFormats) if (rule.type === "sparkline" && /SPARK\.IMAGE/i.test(rule.formula)) {
|
|
6104
|
-
for (const g of (0,
|
|
6105
|
-
const src = (0, import_core10.sparkImageSource)((0, import_core10.sparkRuleView)(s, rule.formula, rule.range, r, c));
|
|
6106
|
-
if (src) out.add(src);
|
|
6107
|
-
}
|
|
6123
|
+
for (const g of (0, import_core11.ruleRanges)(rule)) for (let r = g.r1; r <= Math.min(g.r2, s.maxRow); r++) for (let c = g.c1; c <= Math.min(g.c2, s.maxCol); c++) add((0, import_core11.sparkImageSource)((0, import_core11.sparkRuleView)(s, rule.formula, rule.range, r, c)), { kind: "sparkline", sheet, row: r, col: c });
|
|
6108
6124
|
}
|
|
6109
6125
|
for (let r = 0; r <= s.maxRow; r++) for (let c = 0; c <= s.maxCol; c++) {
|
|
6110
6126
|
const cell = s.getCell(r, c);
|
|
6111
6127
|
if (!cell) continue;
|
|
6112
6128
|
if (cell.img || cell.f && /IMAGE\s*\(/i.test(cell.f)) {
|
|
6113
|
-
const pic = (0,
|
|
6114
|
-
if (pic?.src)
|
|
6129
|
+
const pic = (0, import_core11.cellImageAt)(s, r, c);
|
|
6130
|
+
if (pic?.src) add(pic.src, { kind: pic.formula ? "formula" : "cell", sheet, row: r, col: c });
|
|
6115
6131
|
}
|
|
6116
|
-
if (cell.f && /SPARK\.IMAGE\s*\(/i.test(cell.f)) {
|
|
6117
|
-
|
|
6118
|
-
if (src) out.add(src);
|
|
6119
|
-
} else if (s.cellTypes.length && typeof cell.v === "string" && /^(https?:|data:image\/|blob:)/i.test(cell.v)) out.add(cell.v);
|
|
6132
|
+
if (cell.f && /SPARK\.IMAGE\s*\(/i.test(cell.f)) add((0, import_core11.sparkImageSource)((0, import_core11.cellSparkAt)(s, r, c)), { kind: "sparkline", sheet, row: r, col: c });
|
|
6133
|
+
else if (s.cellTypes.length && typeof cell.v === "string" && /^(https?:|data:image\/|blob:)/i.test(cell.v)) add(cell.v, { kind: "cell-type", sheet, row: r, col: c });
|
|
6120
6134
|
}
|
|
6121
6135
|
}
|
|
6122
6136
|
return out;
|
|
6123
6137
|
}
|
|
6138
|
+
async function loadPicture(url, gate, ctx) {
|
|
6139
|
+
const d = dataUrlBytes(url);
|
|
6140
|
+
if (d) return d.bytes;
|
|
6141
|
+
const browser = typeof globalThis.document !== "undefined";
|
|
6142
|
+
if (/^blob:/i.test(url)) {
|
|
6143
|
+
const r = await fetch(url);
|
|
6144
|
+
if (!r.ok) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6145
|
+
return new Uint8Array(await r.arrayBuffer());
|
|
6146
|
+
}
|
|
6147
|
+
if (!/^https?:/i.test(url) && !(/^\.{0,2}\//.test(url) && browser)) throw new Error("not a picture address");
|
|
6148
|
+
const base = browser ? globalThis.location?.href : void 0;
|
|
6149
|
+
let current = url;
|
|
6150
|
+
for (let hop = 0; hop <= MAX_PICTURE_REDIRECTS; hop++) {
|
|
6151
|
+
if (!browser) await assertPublicHost(current, gate.policy);
|
|
6152
|
+
const r = await fetch(current, { redirect: "manual", credentials: "omit" });
|
|
6153
|
+
if (r.type === "opaqueredirect") throw new Error("A picture address redirects; redirects cannot be checked here and are not followed.");
|
|
6154
|
+
if (r.status >= 300 && r.status < 400) {
|
|
6155
|
+
const loc = r.headers.get("location");
|
|
6156
|
+
if (!loc) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6157
|
+
const next = new URL(loc, new URL(current, base)).href;
|
|
6158
|
+
if (!await gate.allow(next, ctx)) throw new Error("A picture address redirects to an address the picture policy does not allow.");
|
|
6159
|
+
current = next;
|
|
6160
|
+
continue;
|
|
6161
|
+
}
|
|
6162
|
+
if (!r.ok) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6163
|
+
return new Uint8Array(await r.arrayBuffer());
|
|
6164
|
+
}
|
|
6165
|
+
throw new Error("Too many redirects for a picture.");
|
|
6166
|
+
}
|
|
6167
|
+
var MAX_PICTURE_REDIRECTS = 3;
|
|
6168
|
+
async function assertPublicHost(url, policy) {
|
|
6169
|
+
if (policy.allowPrivateNetwork) return;
|
|
6170
|
+
const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
|
|
6171
|
+
if ((0, import_core11.isPrivateNetworkAddress)(host) || /^localhost\.?$/i.test(host) || /\.localhost\.?$/i.test(host)) throw new Error("A picture address names a private network host.");
|
|
6172
|
+
if (/^[\d.]+$/.test(host) || host.includes(":")) return;
|
|
6173
|
+
const proc2 = globalThis.process;
|
|
6174
|
+
const dns = proc2?.getBuiltinModule?.("dns");
|
|
6175
|
+
if (!dns?.promises) throw new Error("A picture host cannot be checked (no DNS lookup); set picturePolicy.allowPrivateNetwork to download it anyway.");
|
|
6176
|
+
const all = await dns.promises.lookup(host, { all: true });
|
|
6177
|
+
if (all.some((a) => (0, import_core11.isPrivateNetworkAddress)(a.address))) throw new Error("A picture address resolves to a private network address.");
|
|
6178
|
+
}
|
|
6124
6179
|
async function toPng(bytes, kind) {
|
|
6125
6180
|
const g = globalThis;
|
|
6126
6181
|
if (!g.document || typeof Blob === "undefined") return null;
|
|
@@ -6155,16 +6210,18 @@ async function prepareAsyncOptions(wb, options) {
|
|
|
6155
6210
|
const images = { ...options.images || {} };
|
|
6156
6211
|
const which = options.sheets;
|
|
6157
6212
|
const sheets = !which || which === "active" ? [wb.activeSheet] : which === "all" ? wb.sheets.filter((s) => !s.hidden) : which.map((k) => typeof k === "number" ? wb.sheets[k] : wb.sheets.find((s) => s.name === k)).filter((s) => !!s);
|
|
6158
|
-
|
|
6213
|
+
const gate = (0, import_core11.pictureGateFor)(wb, options);
|
|
6214
|
+
await Promise.all([...pictureSources(sheets)].map(async ([src, ctx]) => {
|
|
6159
6215
|
if (images[src]) return;
|
|
6216
|
+
const d = dataUrlBytes(src);
|
|
6217
|
+
if (!d && !await gate.allow(src, ctx)) return;
|
|
6160
6218
|
const hit = pictureCache.get(src);
|
|
6161
6219
|
if (hit) {
|
|
6162
6220
|
images[src] = hit;
|
|
6163
6221
|
return;
|
|
6164
6222
|
}
|
|
6165
6223
|
try {
|
|
6166
|
-
const
|
|
6167
|
-
const bytes = d ? d.bytes : await load(src);
|
|
6224
|
+
const bytes = d ? d.bytes : await loadPicture(src, gate, ctx);
|
|
6168
6225
|
const kind = sniff(bytes);
|
|
6169
6226
|
const keep = (b) => {
|
|
6170
6227
|
images[src] = b;
|
|
@@ -6181,14 +6238,14 @@ async function prepareAsyncOptions(wb, options) {
|
|
|
6181
6238
|
} catch {
|
|
6182
6239
|
}
|
|
6183
6240
|
}));
|
|
6184
|
-
return { ...options, fonts, images };
|
|
6241
|
+
return { ...options, fonts, images, picturePolicy: gate.policy, allowedPictureOrigins: void 0, onLoadPicture: void 0 };
|
|
6185
6242
|
}
|
|
6186
6243
|
async function exportPdfAsync(source, options = {}) {
|
|
6187
6244
|
return (await exportPdfDetailedAsync(source, options)).bytes;
|
|
6188
6245
|
}
|
|
6189
6246
|
|
|
6190
6247
|
// src/layout.ts
|
|
6191
|
-
var
|
|
6248
|
+
var import_core13 = require("@openworkbook/core");
|
|
6192
6249
|
|
|
6193
6250
|
// src/screen.ts
|
|
6194
6251
|
var ScreenGradient = class {
|
|
@@ -6835,7 +6892,7 @@ function layoutPdf(source, options = {}) {
|
|
|
6835
6892
|
const fonts = new FontManager({ fonts: options.fonts, defaultFont: options.defaultFont, fallbackFonts: options.fallbackFonts, warn });
|
|
6836
6893
|
const res = new PdfResources(new PdfWriter(), fonts, warn);
|
|
6837
6894
|
const env = pdfPaintEnv(wb, options, warn);
|
|
6838
|
-
const when = (0,
|
|
6895
|
+
const when = (0, import_core13.printDateTime)(options.date ?? /* @__PURE__ */ new Date(), wb.culture);
|
|
6839
6896
|
const fileName = options.fileName ?? (options.title ? `${options.title}` : "Book1");
|
|
6840
6897
|
const plans = sheets.map((sheet) => {
|
|
6841
6898
|
curSheet = sheet.name;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Range, PageSetupPatch, PageBreaks, LinkPolicy, Workbook, WorkbookData, Worksheet, PageSetup } from '@openworkbook/core';
|
|
1
|
+
import { Range, PageSetupPatch, PageBreaks, LinkPolicy, PicturePolicy, LoadPictureHandler, Workbook, WorkbookData, Worksheet, PageSetup } from '@openworkbook/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Fonts of one PDF: which face draws which character, how wide every piece of text is, and the PDF font objects
|
|
@@ -115,7 +115,7 @@ interface PdfExportOptions {
|
|
|
115
115
|
filePath?: string;
|
|
116
116
|
/** The moment `&D` / `&T` print (default: now). */
|
|
117
117
|
date?: Date;
|
|
118
|
-
/** Picture bytes for sources that are not data: URLs (http(s) URLs, blob: URLs). `exportPdfAsync` fills this by downloading
|
|
118
|
+
/** Picture bytes for sources that are not data: URLs (http(s) URLs, blob: URLs), supplied by the application (used as given, whatever the picture policy says). `exportPdfAsync` fills this by downloading the pictures the picture policy allows. */
|
|
119
119
|
images?: Record<string, Uint8Array>;
|
|
120
120
|
/**
|
|
121
121
|
* Encrypt the file with AES-256 (PDF 2.0 security handler, revision 6): the password needed to open it. `''` (with
|
|
@@ -142,6 +142,18 @@ interface PdfExportOptions {
|
|
|
142
142
|
linkPolicy?: LinkPolicy;
|
|
143
143
|
/** Shorthand for `linkPolicy.allowedSchemes` (wins over it). */
|
|
144
144
|
allowedLinkSchemes?: string[];
|
|
145
|
+
/**
|
|
146
|
+
* [picture policy] Which pictures named by the workbook (IMAGE results, cell pictures, picture objects, cell
|
|
147
|
+
* decoration and header / footer pictures) may be loaded (see core's `PictureGate`). Default: embedded pictures
|
|
148
|
+
* (`data:`, `blob:`) and the bytes passed in `images`; remote ones only when this policy, `onLoadPicture` or the
|
|
149
|
+
* user ("Enable content", `workbook.externalContent`) allows them. A refused picture is drawn as a placeholder
|
|
150
|
+
* (`image-blocked` warning) and never downloaded by `exportPdfAsync`.
|
|
151
|
+
*/
|
|
152
|
+
picturePolicy?: PicturePolicy;
|
|
153
|
+
/** [picture policy] Shorthand for `picturePolicy.allowedOrigins` (wins over it). */
|
|
154
|
+
allowedPictureOrigins?: string[];
|
|
155
|
+
/** [picture policy] Asked before a picture the policy lists do not allow is loaded (`exportPdfAsync` awaits a promise; the synchronous export treats a pending answer as a refusal). */
|
|
156
|
+
onLoadPicture?: LoadPictureHandler;
|
|
145
157
|
/**
|
|
146
158
|
* [tagged pdf] Write a tagged (accessible) PDF: a structure tree with one Sect per sheet, one Table per print area
|
|
147
159
|
* (one TR per sheet row, TH / TD cells, continued across pages; repeated print titles are artifacts), Figures with
|
|
@@ -232,7 +244,7 @@ type AsyncPdfExportOptions = Omit<PdfExportOptions, 'fonts'> & {
|
|
|
232
244
|
fonts?: Record<string, AsyncFontSource>;
|
|
233
245
|
};
|
|
234
246
|
/**
|
|
235
|
-
* Asynchronous export: fonts may be given as URLs / file paths, pictures at http(s) / blob: URLs are downloaded,
|
|
247
|
+
* Asynchronous export: fonts may be given as URLs / file paths, pictures at http(s) / blob: URLs that the picture policy allows are downloaded (never before it allows them, never from a file path),
|
|
236
248
|
* and in a browser GIF / WebP / BMP pictures are converted to PNG through a canvas. Otherwise as `exportPdf`.
|
|
237
249
|
*/
|
|
238
250
|
declare function exportPdfDetailedAsync(source: PdfSource, options?: AsyncPdfExportOptions): Promise<PdfExportResult>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Range, PageSetupPatch, PageBreaks, LinkPolicy, Workbook, WorkbookData, Worksheet, PageSetup } from '@openworkbook/core';
|
|
1
|
+
import { Range, PageSetupPatch, PageBreaks, LinkPolicy, PicturePolicy, LoadPictureHandler, Workbook, WorkbookData, Worksheet, PageSetup } from '@openworkbook/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Fonts of one PDF: which face draws which character, how wide every piece of text is, and the PDF font objects
|
|
@@ -115,7 +115,7 @@ interface PdfExportOptions {
|
|
|
115
115
|
filePath?: string;
|
|
116
116
|
/** The moment `&D` / `&T` print (default: now). */
|
|
117
117
|
date?: Date;
|
|
118
|
-
/** Picture bytes for sources that are not data: URLs (http(s) URLs, blob: URLs). `exportPdfAsync` fills this by downloading
|
|
118
|
+
/** Picture bytes for sources that are not data: URLs (http(s) URLs, blob: URLs), supplied by the application (used as given, whatever the picture policy says). `exportPdfAsync` fills this by downloading the pictures the picture policy allows. */
|
|
119
119
|
images?: Record<string, Uint8Array>;
|
|
120
120
|
/**
|
|
121
121
|
* Encrypt the file with AES-256 (PDF 2.0 security handler, revision 6): the password needed to open it. `''` (with
|
|
@@ -142,6 +142,18 @@ interface PdfExportOptions {
|
|
|
142
142
|
linkPolicy?: LinkPolicy;
|
|
143
143
|
/** Shorthand for `linkPolicy.allowedSchemes` (wins over it). */
|
|
144
144
|
allowedLinkSchemes?: string[];
|
|
145
|
+
/**
|
|
146
|
+
* [picture policy] Which pictures named by the workbook (IMAGE results, cell pictures, picture objects, cell
|
|
147
|
+
* decoration and header / footer pictures) may be loaded (see core's `PictureGate`). Default: embedded pictures
|
|
148
|
+
* (`data:`, `blob:`) and the bytes passed in `images`; remote ones only when this policy, `onLoadPicture` or the
|
|
149
|
+
* user ("Enable content", `workbook.externalContent`) allows them. A refused picture is drawn as a placeholder
|
|
150
|
+
* (`image-blocked` warning) and never downloaded by `exportPdfAsync`.
|
|
151
|
+
*/
|
|
152
|
+
picturePolicy?: PicturePolicy;
|
|
153
|
+
/** [picture policy] Shorthand for `picturePolicy.allowedOrigins` (wins over it). */
|
|
154
|
+
allowedPictureOrigins?: string[];
|
|
155
|
+
/** [picture policy] Asked before a picture the policy lists do not allow is loaded (`exportPdfAsync` awaits a promise; the synchronous export treats a pending answer as a refusal). */
|
|
156
|
+
onLoadPicture?: LoadPictureHandler;
|
|
145
157
|
/**
|
|
146
158
|
* [tagged pdf] Write a tagged (accessible) PDF: a structure tree with one Sect per sheet, one Table per print area
|
|
147
159
|
* (one TR per sheet row, TH / TD cells, continued across pages; repeated print titles are artifacts), Figures with
|
|
@@ -232,7 +244,7 @@ type AsyncPdfExportOptions = Omit<PdfExportOptions, 'fonts'> & {
|
|
|
232
244
|
fonts?: Record<string, AsyncFontSource>;
|
|
233
245
|
};
|
|
234
246
|
/**
|
|
235
|
-
* Asynchronous export: fonts may be given as URLs / file paths, pictures at http(s) / blob: URLs are downloaded,
|
|
247
|
+
* Asynchronous export: fonts may be given as URLs / file paths, pictures at http(s) / blob: URLs that the picture policy allows are downloaded (never before it allows them, never from a file path),
|
|
236
248
|
* and in a browser GIF / WebP / BMP pictures are converted to PNG through a canvas. Otherwise as `exportPdf`.
|
|
237
249
|
*/
|
|
238
250
|
declare function exportPdfDetailedAsync(source: PdfSource, options?: AsyncPdfExportOptions): Promise<PdfExportResult>;
|
package/dist/index.js
CHANGED
|
@@ -4391,6 +4391,9 @@ function runFont(r, f) {
|
|
|
4391
4391
|
return `${r.italic ? "italic " : ""}${r.bold ? "bold " : ""}${size.toFixed(2)}px "${r.family || f.family}"`;
|
|
4392
4392
|
}
|
|
4393
4393
|
|
|
4394
|
+
// src/export.ts
|
|
4395
|
+
import { pictureGateFor } from "@openworkbook/core";
|
|
4396
|
+
|
|
4394
4397
|
// src/paint.ts
|
|
4395
4398
|
import {
|
|
4396
4399
|
RECORD_ICON_W,
|
|
@@ -4798,8 +4801,8 @@ var SheetPainter = class {
|
|
|
4798
4801
|
const pic = cellImageAt(s, r, c);
|
|
4799
4802
|
if (pic) {
|
|
4800
4803
|
if (this.o.draft) return;
|
|
4801
|
-
const img = this.o.image(pic.src);
|
|
4802
|
-
drawCellImage(this.c2d, pic, img, { x, y, w, h }, { text: st.color || t.text, font: `${Math.round((st.fontSize || t.fontSize) * 4 / 3)}px "${t.fontFamily}"
|
|
4804
|
+
const pc = { kind: pic.formula ? "formula" : "cell", sheet: s.name, row: r, col: c, output: "pdf" }, img = this.o.image(pic.src);
|
|
4805
|
+
drawCellImage(this.c2d, pic, img, { x, y, w, h }, { text: st.color || t.text, font: `${Math.round((st.fontSize || t.fontSize) * 4 / 3)}px "${t.fontFamily}"`, blocked: !img && this.o.painter.pictureBlocked(pic.src, pc) });
|
|
4803
4806
|
if (cell.link) this.link(cell.link, x, y, w, h, [r, c]);
|
|
4804
4807
|
return;
|
|
4805
4808
|
}
|
|
@@ -5094,8 +5097,8 @@ var SheetPainter = class {
|
|
|
5094
5097
|
return wd;
|
|
5095
5098
|
},
|
|
5096
5099
|
loadImage: (url) => {
|
|
5097
|
-
const img = this.o.image(url);
|
|
5098
|
-
return img ? { state: "ready", image: img, width: img.naturalWidth, height: img.naturalHeight } : { state: "error", width: 0, height: 0 };
|
|
5100
|
+
const pc = { kind: "cell-type", sheet: s.name, row: r, col: c, output: "pdf" }, img = this.o.image(url);
|
|
5101
|
+
return img ? { state: "ready", image: img, width: img.naturalWidth, height: img.naturalHeight } : { state: this.o.painter.pictureBlocked(url, pc) ? "blocked" : "error", width: 0, height: 0 };
|
|
5099
5102
|
}
|
|
5100
5103
|
};
|
|
5101
5104
|
}
|
|
@@ -5383,11 +5386,22 @@ function pdfPageBreaks(sheet, options = {}) {
|
|
|
5383
5386
|
}
|
|
5384
5387
|
function pdfPaintEnv(wb, options, warn) {
|
|
5385
5388
|
const images = /* @__PURE__ */ new Map();
|
|
5389
|
+
const gate = pictureGateFor(wb, options);
|
|
5390
|
+
let blockedWarned = false;
|
|
5386
5391
|
const image = (src) => {
|
|
5387
5392
|
if (images.has(src)) return images.get(src);
|
|
5388
5393
|
let out = null;
|
|
5389
5394
|
try {
|
|
5390
|
-
const
|
|
5395
|
+
const given = options.images?.[src];
|
|
5396
|
+
if (!given && !dataUrlBytes(src) && gate.check(src, { kind: "other", output: "pdf" }).decision !== "allow") {
|
|
5397
|
+
if (!blockedWarned) {
|
|
5398
|
+
blockedWarned = true;
|
|
5399
|
+
warn("image-blocked", "Pictures from external addresses were not loaded because the picture policy blocks them (picturePolicy, allowedPictureOrigins, onLoadPicture); a placeholder is drawn instead.");
|
|
5400
|
+
}
|
|
5401
|
+
images.set(src, null);
|
|
5402
|
+
return null;
|
|
5403
|
+
}
|
|
5404
|
+
const bytes = given ?? dataUrlBytes(src)?.bytes;
|
|
5391
5405
|
if (!bytes) warn("image-not-loaded", `A picture at ${src.length > 80 ? src.slice(0, 77) + "..." : src} is not embedded: only data: URLs are read synchronously (use exportPdfAsync to download pictures, or pass their bytes in \`images\`).`);
|
|
5392
5406
|
else {
|
|
5393
5407
|
const kind = sniff(bytes);
|
|
@@ -5434,7 +5448,11 @@ function pdfPaintEnv(wb, options, warn) {
|
|
|
5434
5448
|
return out;
|
|
5435
5449
|
}
|
|
5436
5450
|
}
|
|
5437
|
-
return { defFont: getDefaultFont(wb), warn, image, objectPainter: () =>
|
|
5451
|
+
return { defFont: getDefaultFont(wb), warn, image, objectPainter: () => {
|
|
5452
|
+
const p = new PdfObjectPainter(wb);
|
|
5453
|
+
p.pictureGate = gate;
|
|
5454
|
+
return p;
|
|
5455
|
+
} };
|
|
5438
5456
|
}
|
|
5439
5457
|
function makeSheetPainter(env, sheet, ctx, rows, cols, setup, objects, position = 1, tags) {
|
|
5440
5458
|
const links = [];
|
|
@@ -6044,7 +6062,7 @@ var decodeURISafe = (s) => {
|
|
|
6044
6062
|
};
|
|
6045
6063
|
|
|
6046
6064
|
// src/file.ts
|
|
6047
|
-
import { cellImageAt as cellImageAt2, cellStyleImageSources, cellSparkAt, ruleRanges, sparkImageSource, sparkRuleView, sparkViewOf } from "@openworkbook/core";
|
|
6065
|
+
import { isPrivateNetworkAddress, pictureGateFor as pictureGateFor2, cellImageAt as cellImageAt2, cellStyleImageSources, cellSparkAt, ruleRanges, sparkImageSource, sparkRuleView, sparkViewOf } from "@openworkbook/core";
|
|
6048
6066
|
import { Workbook as WB } from "@openworkbook/core";
|
|
6049
6067
|
var PDF_MIME = "application/pdf";
|
|
6050
6068
|
var toBlob = (b) => new Blob([b], { type: PDF_MIME });
|
|
@@ -6123,37 +6141,74 @@ function asWb(src) {
|
|
|
6123
6141
|
return new WB(src);
|
|
6124
6142
|
}
|
|
6125
6143
|
function pictureSources(sheets) {
|
|
6126
|
-
const out = /* @__PURE__ */ new
|
|
6144
|
+
const out = /* @__PURE__ */ new Map();
|
|
6145
|
+
const add = (src, ctx) => {
|
|
6146
|
+
if (src && !out.has(src)) out.set(src, { ...ctx, output: "pdf" });
|
|
6147
|
+
};
|
|
6127
6148
|
for (const s of sheets) {
|
|
6128
|
-
|
|
6129
|
-
|
|
6130
|
-
|
|
6131
|
-
for (const
|
|
6132
|
-
for (const
|
|
6133
|
-
|
|
6134
|
-
if (src) out.add(src);
|
|
6135
|
-
}
|
|
6149
|
+
const sheet = s.name;
|
|
6150
|
+
for (const o of s.objects) if (o.kind === "image" && o.src) add(o.src, { kind: "object", sheet, objectId: o.id });
|
|
6151
|
+
if (s.backgroundImage && s.pageSetup.printBackground) add(s.backgroundImage, { kind: "background", sheet });
|
|
6152
|
+
for (const p of Object.values(s.pageSetup.headerFooterPictures ?? {})) if (p?.src) add(p.src, { kind: "header-footer", sheet });
|
|
6153
|
+
for (const src of cellStyleImageSources(s)) add(src, { kind: "decoration", sheet });
|
|
6154
|
+
for (const o of s.objects) if (o.kind === "shape" && o.sparkline && /SPARK\.IMAGE/i.test(o.sparkline)) add(sparkImageSource(sparkViewOf(s, o.sparkline)), { kind: "sparkline", sheet, objectId: o.id });
|
|
6136
6155
|
for (const rule of s.condFormats) if (rule.type === "sparkline" && /SPARK\.IMAGE/i.test(rule.formula)) {
|
|
6137
|
-
for (const g of ruleRanges(rule)) for (let r = g.r1; r <= Math.min(g.r2, s.maxRow); r++) for (let c = g.c1; c <= Math.min(g.c2, s.maxCol); c++) {
|
|
6138
|
-
const src = sparkImageSource(sparkRuleView(s, rule.formula, rule.range, r, c));
|
|
6139
|
-
if (src) out.add(src);
|
|
6140
|
-
}
|
|
6156
|
+
for (const g of ruleRanges(rule)) for (let r = g.r1; r <= Math.min(g.r2, s.maxRow); r++) for (let c = g.c1; c <= Math.min(g.c2, s.maxCol); c++) add(sparkImageSource(sparkRuleView(s, rule.formula, rule.range, r, c)), { kind: "sparkline", sheet, row: r, col: c });
|
|
6141
6157
|
}
|
|
6142
6158
|
for (let r = 0; r <= s.maxRow; r++) for (let c = 0; c <= s.maxCol; c++) {
|
|
6143
6159
|
const cell = s.getCell(r, c);
|
|
6144
6160
|
if (!cell) continue;
|
|
6145
6161
|
if (cell.img || cell.f && /IMAGE\s*\(/i.test(cell.f)) {
|
|
6146
6162
|
const pic = cellImageAt2(s, r, c);
|
|
6147
|
-
if (pic?.src)
|
|
6163
|
+
if (pic?.src) add(pic.src, { kind: pic.formula ? "formula" : "cell", sheet, row: r, col: c });
|
|
6148
6164
|
}
|
|
6149
|
-
if (cell.f && /SPARK\.IMAGE\s*\(/i.test(cell.f)) {
|
|
6150
|
-
|
|
6151
|
-
if (src) out.add(src);
|
|
6152
|
-
} else if (s.cellTypes.length && typeof cell.v === "string" && /^(https?:|data:image\/|blob:)/i.test(cell.v)) out.add(cell.v);
|
|
6165
|
+
if (cell.f && /SPARK\.IMAGE\s*\(/i.test(cell.f)) add(sparkImageSource(cellSparkAt(s, r, c)), { kind: "sparkline", sheet, row: r, col: c });
|
|
6166
|
+
else if (s.cellTypes.length && typeof cell.v === "string" && /^(https?:|data:image\/|blob:)/i.test(cell.v)) add(cell.v, { kind: "cell-type", sheet, row: r, col: c });
|
|
6153
6167
|
}
|
|
6154
6168
|
}
|
|
6155
6169
|
return out;
|
|
6156
6170
|
}
|
|
6171
|
+
async function loadPicture(url, gate, ctx) {
|
|
6172
|
+
const d = dataUrlBytes(url);
|
|
6173
|
+
if (d) return d.bytes;
|
|
6174
|
+
const browser = typeof globalThis.document !== "undefined";
|
|
6175
|
+
if (/^blob:/i.test(url)) {
|
|
6176
|
+
const r = await fetch(url);
|
|
6177
|
+
if (!r.ok) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6178
|
+
return new Uint8Array(await r.arrayBuffer());
|
|
6179
|
+
}
|
|
6180
|
+
if (!/^https?:/i.test(url) && !(/^\.{0,2}\//.test(url) && browser)) throw new Error("not a picture address");
|
|
6181
|
+
const base = browser ? globalThis.location?.href : void 0;
|
|
6182
|
+
let current = url;
|
|
6183
|
+
for (let hop = 0; hop <= MAX_PICTURE_REDIRECTS; hop++) {
|
|
6184
|
+
if (!browser) await assertPublicHost(current, gate.policy);
|
|
6185
|
+
const r = await fetch(current, { redirect: "manual", credentials: "omit" });
|
|
6186
|
+
if (r.type === "opaqueredirect") throw new Error("A picture address redirects; redirects cannot be checked here and are not followed.");
|
|
6187
|
+
if (r.status >= 300 && r.status < 400) {
|
|
6188
|
+
const loc = r.headers.get("location");
|
|
6189
|
+
if (!loc) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6190
|
+
const next = new URL(loc, new URL(current, base)).href;
|
|
6191
|
+
if (!await gate.allow(next, ctx)) throw new Error("A picture address redirects to an address the picture policy does not allow.");
|
|
6192
|
+
current = next;
|
|
6193
|
+
continue;
|
|
6194
|
+
}
|
|
6195
|
+
if (!r.ok) throw new Error(`Could not load a picture: HTTP ${r.status}`);
|
|
6196
|
+
return new Uint8Array(await r.arrayBuffer());
|
|
6197
|
+
}
|
|
6198
|
+
throw new Error("Too many redirects for a picture.");
|
|
6199
|
+
}
|
|
6200
|
+
var MAX_PICTURE_REDIRECTS = 3;
|
|
6201
|
+
async function assertPublicHost(url, policy) {
|
|
6202
|
+
if (policy.allowPrivateNetwork) return;
|
|
6203
|
+
const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
|
|
6204
|
+
if (isPrivateNetworkAddress(host) || /^localhost\.?$/i.test(host) || /\.localhost\.?$/i.test(host)) throw new Error("A picture address names a private network host.");
|
|
6205
|
+
if (/^[\d.]+$/.test(host) || host.includes(":")) return;
|
|
6206
|
+
const proc2 = globalThis.process;
|
|
6207
|
+
const dns = proc2?.getBuiltinModule?.("dns");
|
|
6208
|
+
if (!dns?.promises) throw new Error("A picture host cannot be checked (no DNS lookup); set picturePolicy.allowPrivateNetwork to download it anyway.");
|
|
6209
|
+
const all = await dns.promises.lookup(host, { all: true });
|
|
6210
|
+
if (all.some((a) => isPrivateNetworkAddress(a.address))) throw new Error("A picture address resolves to a private network address.");
|
|
6211
|
+
}
|
|
6157
6212
|
async function toPng(bytes, kind) {
|
|
6158
6213
|
const g = globalThis;
|
|
6159
6214
|
if (!g.document || typeof Blob === "undefined") return null;
|
|
@@ -6188,16 +6243,18 @@ async function prepareAsyncOptions(wb, options) {
|
|
|
6188
6243
|
const images = { ...options.images || {} };
|
|
6189
6244
|
const which = options.sheets;
|
|
6190
6245
|
const sheets = !which || which === "active" ? [wb.activeSheet] : which === "all" ? wb.sheets.filter((s) => !s.hidden) : which.map((k) => typeof k === "number" ? wb.sheets[k] : wb.sheets.find((s) => s.name === k)).filter((s) => !!s);
|
|
6191
|
-
|
|
6246
|
+
const gate = pictureGateFor2(wb, options);
|
|
6247
|
+
await Promise.all([...pictureSources(sheets)].map(async ([src, ctx]) => {
|
|
6192
6248
|
if (images[src]) return;
|
|
6249
|
+
const d = dataUrlBytes(src);
|
|
6250
|
+
if (!d && !await gate.allow(src, ctx)) return;
|
|
6193
6251
|
const hit = pictureCache.get(src);
|
|
6194
6252
|
if (hit) {
|
|
6195
6253
|
images[src] = hit;
|
|
6196
6254
|
return;
|
|
6197
6255
|
}
|
|
6198
6256
|
try {
|
|
6199
|
-
const
|
|
6200
|
-
const bytes = d ? d.bytes : await load(src);
|
|
6257
|
+
const bytes = d ? d.bytes : await loadPicture(src, gate, ctx);
|
|
6201
6258
|
const kind = sniff(bytes);
|
|
6202
6259
|
const keep = (b) => {
|
|
6203
6260
|
images[src] = b;
|
|
@@ -6214,7 +6271,7 @@ async function prepareAsyncOptions(wb, options) {
|
|
|
6214
6271
|
} catch {
|
|
6215
6272
|
}
|
|
6216
6273
|
}));
|
|
6217
|
-
return { ...options, fonts, images };
|
|
6274
|
+
return { ...options, fonts, images, picturePolicy: gate.policy, allowedPictureOrigins: void 0, onLoadPicture: void 0 };
|
|
6218
6275
|
}
|
|
6219
6276
|
async function exportPdfAsync(source, options = {}) {
|
|
6220
6277
|
return (await exportPdfDetailedAsync(source, options)).bytes;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openworkbook/pdf",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Direct, vector, text-selectable PDF export for @openworkbook/core workbooks (browser and Node.js, no print dialog, no headless browser)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"engines": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"sideEffects": false,
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"fflate": "^0.8.2",
|
|
27
|
-
"@openworkbook/core": "0.
|
|
27
|
+
"@openworkbook/core": "0.2.1"
|
|
28
28
|
},
|
|
29
29
|
"homepage": "https://openworkbook.netlify.app",
|
|
30
30
|
"keywords": [
|