@ggraphic/editor 0.1.0-alpha.4 → 0.1.0-alpha.6
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/CanvasEditorProvider.d.ts +6 -1
- package/dist/collab/useYjsPageStateSync.d.ts +1 -1
- package/dist/collab/useYjsPageStateSync.js +5 -2
- package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
- package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
- package/dist/components/CanvasEditor/types.d.ts +28 -0
- package/dist/components/GenericCanvas.d.ts +19 -2
- package/dist/components/GenericCanvas.js +30 -5
- package/dist/components/PagePreview.d.ts +8 -1
- package/dist/components/PagePreview.js +4 -1
- package/dist/components/TopBar/DownloadSection.d.ts +24 -3
- package/dist/components/TopBar/DownloadSection.js +45 -7
- package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
- package/dist/components/TopBar/ShareDropdown.js +2 -2
- package/dist/entries/export.d.ts +14 -1
- package/dist/entries/export.js +14 -1
- package/dist/entries/services.d.ts +1 -1
- package/dist/export/fonts/fontFiles.d.ts +100 -0
- package/dist/export/fonts/fontFiles.js +333 -0
- package/dist/export/fonts/glyphs.d.ts +113 -0
- package/dist/export/fonts/glyphs.js +120 -0
- package/dist/export/fonts/variation.d.ts +23 -0
- package/dist/export/fonts/variation.js +43 -0
- package/dist/export/pdf/pdfContent.d.ts +108 -0
- package/dist/export/pdf/pdfContent.js +566 -0
- package/dist/export/pdf/pdfFontkit.d.ts +54 -0
- package/dist/export/pdf/pdfFontkit.js +159 -0
- package/dist/export/pdf/pdfGeometry.d.ts +54 -0
- package/dist/export/pdf/pdfGeometry.js +228 -0
- package/dist/export/pdf/pdfResources.d.ts +109 -0
- package/dist/export/pdf/pdfResources.js +314 -0
- package/dist/export/pdf/writePdf.d.ts +34 -0
- package/dist/export/pdf/writePdf.js +165 -0
- package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
- package/dist/export/pptx/exportPptxDeck.js +5 -2
- package/dist/export/pptx/svgPicture.d.ts +19 -0
- package/dist/export/pptx/svgPicture.js +64 -0
- package/dist/export/pptx/vectorizeElement.d.ts +9 -0
- package/dist/export/pptx/vectorizeElement.js +118 -0
- package/dist/export/pptx/writePptx.d.ts +13 -0
- package/dist/export/pptx/writePptx.js +17 -0
- package/dist/export/printPdf.d.ts +1 -0
- package/dist/export/printPdf.js +1 -1
- package/dist/export/scene/browserDeps.d.ts +32 -0
- package/dist/export/scene/browserDeps.js +174 -0
- package/dist/export/scene/imageBytes.d.ts +79 -0
- package/dist/export/scene/imageBytes.js +330 -0
- package/dist/export/scene/itemBounds.d.ts +9 -0
- package/dist/export/scene/itemBounds.js +40 -0
- package/dist/export/scene/matrix.d.ts +13 -0
- package/dist/export/scene/matrix.js +32 -0
- package/dist/export/scene/rasterLimit.d.ts +13 -0
- package/dist/export/scene/rasterLimit.js +24 -0
- package/dist/export/scene/rebaseOps.d.ts +8 -0
- package/dist/export/scene/rebaseOps.js +51 -0
- package/dist/export/scene/recordPageScene.d.ts +28 -0
- package/dist/export/scene/recordPageScene.js +224 -0
- package/dist/export/scene/recordingCanvas.d.ts +55 -0
- package/dist/export/scene/recordingCanvas.js +71 -0
- package/dist/export/scene/recordingContext.d.ts +162 -0
- package/dist/export/scene/recordingContext.js +1031 -0
- package/dist/export/scene/replayScene.d.ts +31 -0
- package/dist/export/scene/replayScene.js +213 -0
- package/dist/export/scene/resolveScene.d.ts +48 -0
- package/dist/export/scene/resolveScene.js +236 -0
- package/dist/export/scene/trustedSvgImages.d.ts +3 -0
- package/dist/export/scene/trustedSvgImages.js +21 -0
- package/dist/export/scene/types.d.ts +241 -0
- package/dist/export/scene/types.js +38 -0
- package/dist/export/slidesPdf.d.ts +10 -2
- package/dist/export/slidesPdf.js +8 -4
- package/dist/export/svg/__fixtures__/barChart.svg +1 -0
- package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
- package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
- package/dist/export/svg/inlineSvg.d.ts +10 -0
- package/dist/export/svg/inlineSvg.js +119 -0
- package/dist/export/svg/scopeCss.d.ts +45 -0
- package/dist/export/svg/scopeCss.js +214 -0
- package/dist/export/svg/svgColor.d.ts +8 -0
- package/dist/export/svg/svgColor.js +46 -0
- package/dist/export/svg/svgImageScene.d.ts +41 -0
- package/dist/export/svg/svgImageScene.js +128 -0
- package/dist/export/svg/svgPathData.d.ts +31 -0
- package/dist/export/svg/svgPathData.js +466 -0
- package/dist/export/svg/svgToScene.d.ts +19 -0
- package/dist/export/svg/svgToScene.js +1183 -0
- package/dist/export/svg/writeSvg.d.ts +33 -0
- package/dist/export/svg/writeSvg.js +594 -0
- package/dist/export/svg/xml.d.ts +23 -0
- package/dist/export/svg/xml.js +49 -0
- package/dist/export/vectorDeps.d.ts +27 -0
- package/dist/export/vectorDeps.js +37 -0
- package/dist/export/vectorExport.d.ts +85 -0
- package/dist/export/vectorExport.js +287 -0
- package/dist/hostServices.d.ts +15 -0
- package/dist/i18n/de.d.ts +26 -9
- package/dist/i18n/de.js +26 -10
- package/dist/i18n/en.js +24 -0
- package/dist/primitives/AssetPrimitive.js +7 -2
- package/dist/primitives/CanvasIcons.js +6 -0
- package/dist/primitives/CanvasStage.js +2 -2
- package/dist/primitives/ChartPrimitive.d.ts +11 -1
- package/dist/primitives/ChartPrimitive.js +73 -19
- package/dist/primitives/IconPrimitive.js +3 -0
- package/dist/primitives/IllustrationPrimitive.js +14 -1
- package/dist/primitives/chartFont.d.ts +30 -0
- package/dist/primitives/chartFont.js +127 -0
- package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
- package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
- package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
- package/dist/sidebar/sections/assets/assetAudience.js +18 -0
- package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
- package/dist/stores/createCanvasEditorStore.d.ts +5 -2
- package/dist/stores/createCanvasEditorStore.js +9 -5
- package/dist/styles/compiled.css +1 -1
- package/dist/utils/canvasAssets.d.ts +11 -1
- package/dist/utils/canvasAssets.js +8 -0
- package/dist/utils/canvasIcons.js +5 -3
- package/dist/utils/captureStage.d.ts +19 -0
- package/dist/utils/captureStage.js +14 -1
- package/dist/utils/externalIcons.d.ts +7 -0
- package/dist/utils/externalIcons.js +70 -3
- package/dist/utils/illustrations/svgCache.js +6 -1
- package/dist/utils/imageFilters.d.ts +13 -0
- package/dist/utils/imageFilters.js +11 -0
- package/dist/utils/rebaseHistoryState.d.ts +9 -0
- package/dist/utils/rebaseHistoryState.js +26 -0
- package/dist/utils/zipPageImages.d.ts +8 -0
- package/dist/utils/zipPageImages.js +16 -4
- package/package.json +6 -2
- package/skills/ggraphic-embed/SKILL.md +33 -1
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
/**
|
|
3
|
+
* The objects a PDF page draws with, made through pdf-lib: embedded fonts and images (shared by
|
|
4
|
+
* the whole document), and the page's resource dictionary with the names content streams use
|
|
5
|
+
* (`/F1`, `/Im1`, `/GS1`, ...), plus the dictionaries the writer builds by hand: shadings,
|
|
6
|
+
* tiling patterns, transparency groups and soft masks.
|
|
7
|
+
*
|
|
8
|
+
* pdf-lib loads by dynamic `import()` in `writePdf`; this file only holds its types and gets the
|
|
9
|
+
* module passed in.
|
|
10
|
+
*/
|
|
11
|
+
import { subsetTag } from '../fonts/fontFiles.js';
|
|
12
|
+
import { embeddableBytes } from './pdfFontkit.js';
|
|
13
|
+
import { unit } from './pdfGeometry.js';
|
|
14
|
+
const FS_NO_SUBSETTING = 0x0100;
|
|
15
|
+
/** `OS/2.fsType` bit 8: the font may be embedded, but only whole. */
|
|
16
|
+
function forbidsSubsetting(fsType) {
|
|
17
|
+
if (fsType === undefined)
|
|
18
|
+
return false;
|
|
19
|
+
return typeof fsType === 'number' ? (fsType & FS_NO_SUBSETTING) !== 0 : !!fsType.noSubsetting;
|
|
20
|
+
}
|
|
21
|
+
/** TrueType (`0x00010000`, `true`) or OpenType (`OTTO`): the files PDF takes as a font program. */
|
|
22
|
+
function isSfnt(bytes) {
|
|
23
|
+
const tag = String.fromCharCode(bytes[0] ?? 0, bytes[1] ?? 0, bytes[2] ?? 0, bytes[3] ?? 0);
|
|
24
|
+
return tag === '\u0000\u0001\u0000\u0000' || tag === 'true' || tag === 'OTTO';
|
|
25
|
+
}
|
|
26
|
+
/** The PostScript name with the characters a PDF name cannot carry left out. */
|
|
27
|
+
function safeName(name) {
|
|
28
|
+
return name.replace(/[^A-Za-z0-9_-]/g, '') || 'Font';
|
|
29
|
+
}
|
|
30
|
+
const alphaKey = (alpha) => unit(Math.min(1, Math.max(0, alpha)));
|
|
31
|
+
export class PdfAssets {
|
|
32
|
+
lib;
|
|
33
|
+
doc;
|
|
34
|
+
cmyk;
|
|
35
|
+
/** The hex (lower case) of every colour written as RGB, for `report.rgbBrandColors`. */
|
|
36
|
+
rgbHexes = new Set();
|
|
37
|
+
fonts = new Map();
|
|
38
|
+
images = new Map();
|
|
39
|
+
shadings = new Map();
|
|
40
|
+
patterns = new Map();
|
|
41
|
+
made = new Map();
|
|
42
|
+
/**
|
|
43
|
+
* @param cmyk the colours (hex, lower case) the brand has print values for; whatever paints
|
|
44
|
+
* with one of them is DeviceCMYK, whatever does not is RGB
|
|
45
|
+
*/
|
|
46
|
+
constructor(lib, doc, cmyk = new Map()) {
|
|
47
|
+
this.lib = lib;
|
|
48
|
+
this.doc = doc;
|
|
49
|
+
this.cmyk = cmyk;
|
|
50
|
+
}
|
|
51
|
+
get context() {
|
|
52
|
+
return this.doc.context;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* A subset of the font file, named `ABCDEF+PostScriptName` (pdf-lib's own default has no such
|
|
56
|
+
* tag).
|
|
57
|
+
*
|
|
58
|
+
* A font whose licence says "no subsetting" goes in whole, under its plain name (the prefix
|
|
59
|
+
* tells a reader the font is a subset). An sfnt file (TrueType, OpenType) is embedded as it is.
|
|
60
|
+
* A WOFF or WOFF2 file cannot be: pdf-lib would write its bytes unchanged and no viewer reads a
|
|
61
|
+
* WOFF as a font program. Such a font goes through the subsetter with every glyph it has.
|
|
62
|
+
*/
|
|
63
|
+
font(file, face, fileIndex) {
|
|
64
|
+
let font = this.fonts.get(file);
|
|
65
|
+
if (!font) {
|
|
66
|
+
const name = safeName(file.font.postscriptName ?? face.family);
|
|
67
|
+
if (!forbidsSubsetting(file.font['OS/2']?.fsType)) {
|
|
68
|
+
font = this.doc.embedFont(embeddableBytes(file), {
|
|
69
|
+
subset: true,
|
|
70
|
+
customName: `${subsetTag(face, fileIndex)}+${name}`,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
else if (isSfnt(file.bytes)) {
|
|
74
|
+
font = this.doc.embedFont(file.bytes, { subset: false, customName: name });
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
font = this.doc
|
|
78
|
+
.embedFont(embeddableBytes(file), { subset: true, customName: name })
|
|
79
|
+
.then((whole) => {
|
|
80
|
+
// `encodeText` is what puts a glyph into the subset.
|
|
81
|
+
for (const codePoint of file.font.characterSet) {
|
|
82
|
+
whole.encodeText(String.fromCodePoint(codePoint));
|
|
83
|
+
}
|
|
84
|
+
return whole;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
this.fonts.set(file, font);
|
|
88
|
+
}
|
|
89
|
+
return font;
|
|
90
|
+
}
|
|
91
|
+
/** The image once per `key` (the source object or the PNG bytes); null if pdf-lib cannot read it. */
|
|
92
|
+
image(key, bytes, mime) {
|
|
93
|
+
let image = this.images.get(key);
|
|
94
|
+
if (!image) {
|
|
95
|
+
image = (mime === 'image/jpeg' ? this.doc.embedJpg(bytes) : this.doc.embedPng(bytes)).catch(() => null);
|
|
96
|
+
this.images.set(key, image);
|
|
97
|
+
}
|
|
98
|
+
return image;
|
|
99
|
+
}
|
|
100
|
+
/** The picture `make` draws for `key`, made the first time it is asked for and not again. */
|
|
101
|
+
once(key, make) {
|
|
102
|
+
let image = this.made.get(key);
|
|
103
|
+
if (!image) {
|
|
104
|
+
image = make();
|
|
105
|
+
this.made.set(key, image);
|
|
106
|
+
}
|
|
107
|
+
return image;
|
|
108
|
+
}
|
|
109
|
+
bitmap(source) {
|
|
110
|
+
return this.image(source, source.bytes, source.mime);
|
|
111
|
+
}
|
|
112
|
+
// -- shadings --------------------------------------------------------------------------
|
|
113
|
+
/**
|
|
114
|
+
* The shading of a gradient: axial (type 2) or radial (type 3), extended past both ends as a
|
|
115
|
+
* canvas gradient is. `channel` picks what the colour function returns: the RGB of the stops,
|
|
116
|
+
* their CMYK (every stop must be in the brand's map), or their alpha as a gray value (for a soft
|
|
117
|
+
* mask). Null when the geometry paints nothing.
|
|
118
|
+
*/
|
|
119
|
+
shading(paint, channel) {
|
|
120
|
+
if (paint.type === 'linear' && paint.x0 === paint.x1 && paint.y0 === paint.y1)
|
|
121
|
+
return null;
|
|
122
|
+
if (paint.type === 'radial' &&
|
|
123
|
+
paint.x0 === paint.x1 &&
|
|
124
|
+
paint.y0 === paint.y1 &&
|
|
125
|
+
paint.r0 === paint.r1) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
const key = `${channel}\0${JSON.stringify(paint)}`;
|
|
129
|
+
let ref = this.shadings.get(key);
|
|
130
|
+
if (!ref) {
|
|
131
|
+
ref = this.context.register(this.context.obj({
|
|
132
|
+
ShadingType: paint.type === 'linear' ? 2 : 3,
|
|
133
|
+
ColorSpace: channel === 'rgb' ? 'DeviceRGB' : channel === 'cmyk' ? 'DeviceCMYK' : 'DeviceGray',
|
|
134
|
+
Coords: paint.type === 'linear'
|
|
135
|
+
? [paint.x0, paint.y0, paint.x1, paint.y1]
|
|
136
|
+
: [paint.x0, paint.y0, paint.r0, paint.x1, paint.y1, paint.r1],
|
|
137
|
+
Domain: [0, 1],
|
|
138
|
+
Function: this.colourFunction(paint.stops, channel),
|
|
139
|
+
Extend: [true, true],
|
|
140
|
+
}));
|
|
141
|
+
this.shadings.set(key, ref);
|
|
142
|
+
}
|
|
143
|
+
return ref;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* A stitching function (type 3) of exponential segments (type 2, N = 1) from stop to stop. The
|
|
147
|
+
* ends are extended to 0 and 1 with the first and last colour; a hard stop (two stops at one
|
|
148
|
+
* offset) is a segment of no width and is left out, so the bounds rise strictly.
|
|
149
|
+
*/
|
|
150
|
+
colourFunction(stops, channel) {
|
|
151
|
+
const sorted = stops
|
|
152
|
+
.map((stop, index) => ({ stop, index }))
|
|
153
|
+
.sort((a, b) => a.stop.offset - b.stop.offset || a.index - b.index)
|
|
154
|
+
.map(({ stop }) => ({ ...stop, offset: Math.min(1, Math.max(0, stop.offset)) }));
|
|
155
|
+
const first = sorted[0];
|
|
156
|
+
const last = sorted.at(-1);
|
|
157
|
+
if (first.offset > 0)
|
|
158
|
+
sorted.unshift({ ...first, offset: 0 });
|
|
159
|
+
if (last.offset < 1)
|
|
160
|
+
sorted.push({ ...last, offset: 1 });
|
|
161
|
+
const colour = (stop) => channel === 'alpha'
|
|
162
|
+
? [stop.alpha]
|
|
163
|
+
: channel === 'cmyk'
|
|
164
|
+
? [...this.cmyk.get(stop.hex.toLowerCase())]
|
|
165
|
+
: [1, 3, 5].map((at) => Number.parseInt(stop.hex.slice(at, at + 2), 16) / 255);
|
|
166
|
+
const segments = [];
|
|
167
|
+
for (let i = 0; i + 1 < sorted.length; i++) {
|
|
168
|
+
if (sorted[i + 1].offset > sorted[i].offset)
|
|
169
|
+
segments.push({ from: sorted[i], to: sorted[i + 1] });
|
|
170
|
+
}
|
|
171
|
+
// All stops on one offset: what is left is the colour after it.
|
|
172
|
+
if (segments.length === 0)
|
|
173
|
+
segments.push({ from: last, to: last });
|
|
174
|
+
const exponential = ({ from, to }) => this.context.obj({ FunctionType: 2, Domain: [0, 1], C0: colour(from), C1: colour(to), N: 1 });
|
|
175
|
+
if (segments.length === 1)
|
|
176
|
+
return exponential(segments[0]);
|
|
177
|
+
return this.context.obj({
|
|
178
|
+
FunctionType: 3,
|
|
179
|
+
Domain: [0, 1],
|
|
180
|
+
Functions: segments.map(exponential),
|
|
181
|
+
Bounds: segments.slice(1).map((segment) => segment.from.offset),
|
|
182
|
+
Encode: segments.flatMap(() => [0, 1]),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** A shading pattern (type 2). `matrix` maps the pattern space to the default space of its content stream. */
|
|
186
|
+
shadingPattern(shading, matrix) {
|
|
187
|
+
return this.pattern(`${shading.tag}\0${matrix.join(',')}`, () => this.context.obj({ PatternType: 2, Shading: shading, Matrix: [...matrix] }));
|
|
188
|
+
}
|
|
189
|
+
/** One pattern object per key: a chart's bars share a gradient and a matrix. */
|
|
190
|
+
pattern(key, make) {
|
|
191
|
+
let ref = this.patterns.get(key);
|
|
192
|
+
if (!ref) {
|
|
193
|
+
ref = this.context.register(make());
|
|
194
|
+
this.patterns.set(key, ref);
|
|
195
|
+
}
|
|
196
|
+
return ref;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* A tiling pattern (type 1) that draws `image` at `width` x `height` once per cell, upright in a
|
|
200
|
+
* y-down pattern space as a canvas pattern is. `matrix` as for `shadingPattern`.
|
|
201
|
+
*/
|
|
202
|
+
tilingPattern(image, width, height, matrix) {
|
|
203
|
+
return this.pattern(`${image.ref.tag}\0${width}x${height}\0${matrix.join(',')}`, () => {
|
|
204
|
+
const content = `q ${unit(width)} 0 0 ${unit(-height)} 0 ${unit(height)} cm /Im1 Do Q`;
|
|
205
|
+
return this.context.flateStream(content, {
|
|
206
|
+
Type: 'Pattern',
|
|
207
|
+
PatternType: 1,
|
|
208
|
+
PaintType: 1,
|
|
209
|
+
TilingType: 1,
|
|
210
|
+
BBox: [0, 0, width, height],
|
|
211
|
+
XStep: width,
|
|
212
|
+
YStep: height,
|
|
213
|
+
Resources: { XObject: { Im1: image.ref } },
|
|
214
|
+
Matrix: [...matrix],
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
// -- forms -----------------------------------------------------------------------------
|
|
219
|
+
/** A form XObject; `group` makes it a transparency group, drawn as one picture with the alpha set outside. */
|
|
220
|
+
form(content, bbox, resources, group) {
|
|
221
|
+
return this.context.register(this.context.flateStream(content, {
|
|
222
|
+
Type: 'XObject',
|
|
223
|
+
Subtype: 'Form',
|
|
224
|
+
BBox: [bbox.x0, bbox.y0, bbox.x1, bbox.y1],
|
|
225
|
+
Resources: resources,
|
|
226
|
+
Group: group
|
|
227
|
+
? { S: 'Transparency', I: true, ...(group.colourSpace && { CS: group.colourSpace }) }
|
|
228
|
+
: undefined,
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* The soft mask that lets a gradient's alpha through: a luminosity mask whose group paints the
|
|
233
|
+
* gradient's alpha as gray. It is evaluated in the space the graphics state is set in, so the
|
|
234
|
+
* shading's coordinates are the op's own. `bbox` is the area the op can touch, in that space.
|
|
235
|
+
*/
|
|
236
|
+
alphaMask(paint, bbox) {
|
|
237
|
+
const shading = this.shading(paint, 'alpha');
|
|
238
|
+
if (!shading)
|
|
239
|
+
return null;
|
|
240
|
+
return this.form('/Sh1 sh', bbox, this.context.obj({ Shading: { Sh1: shading } }), {
|
|
241
|
+
colourSpace: 'DeviceGray',
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const PREFIX = {
|
|
246
|
+
Font: 'F',
|
|
247
|
+
XObject: 'Im',
|
|
248
|
+
ExtGState: 'GS',
|
|
249
|
+
Pattern: 'P',
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* The resource dictionary of a page. The content of a form XObject on the page is written with the
|
|
253
|
+
* same names, so a form gets a copy of the dictionary as it is when the form is made (`snapshot`):
|
|
254
|
+
* it holds what the form draws with, and not itself.
|
|
255
|
+
*/
|
|
256
|
+
export class PageResources {
|
|
257
|
+
assets;
|
|
258
|
+
ref;
|
|
259
|
+
dict;
|
|
260
|
+
names = new Map();
|
|
261
|
+
counts = new Map();
|
|
262
|
+
states = new Map();
|
|
263
|
+
constructor(assets) {
|
|
264
|
+
this.assets = assets;
|
|
265
|
+
this.dict = assets.context.obj({});
|
|
266
|
+
this.ref = assets.context.register(this.dict);
|
|
267
|
+
}
|
|
268
|
+
add(category, target) {
|
|
269
|
+
const key = `${category}\0${target.tag}`;
|
|
270
|
+
let name = this.names.get(key);
|
|
271
|
+
if (!name) {
|
|
272
|
+
const n = (this.counts.get(category) ?? 0) + 1;
|
|
273
|
+
this.counts.set(category, n);
|
|
274
|
+
name = `${PREFIX[category]}${n}`;
|
|
275
|
+
this.names.set(key, name);
|
|
276
|
+
const { PDFName, PDFDict } = this.assets.lib;
|
|
277
|
+
const section = PDFName.of(category);
|
|
278
|
+
let dict = this.dict.get(section);
|
|
279
|
+
if (!(dict instanceof PDFDict)) {
|
|
280
|
+
dict = this.assets.context.obj({});
|
|
281
|
+
this.dict.set(section, dict);
|
|
282
|
+
}
|
|
283
|
+
dict.set(PDFName.of(name), target);
|
|
284
|
+
}
|
|
285
|
+
return `/${name}`;
|
|
286
|
+
}
|
|
287
|
+
font = (font) => this.add('Font', font.ref);
|
|
288
|
+
xobject = (ref) => this.add('XObject', ref);
|
|
289
|
+
pattern = (ref) => this.add('Pattern', ref);
|
|
290
|
+
/** `ca` and `CA` together, optionally with a soft mask; one dictionary per distinct state. */
|
|
291
|
+
extGState(alpha, softMask = null) {
|
|
292
|
+
const key = `${alphaKey(alpha)}\0${softMask?.tag ?? ''}`;
|
|
293
|
+
let ref = this.states.get(key);
|
|
294
|
+
if (!ref) {
|
|
295
|
+
ref = this.assets.context.register(this.assets.context.obj({
|
|
296
|
+
Type: 'ExtGState',
|
|
297
|
+
ca: Number(alphaKey(alpha)),
|
|
298
|
+
CA: Number(alphaKey(alpha)),
|
|
299
|
+
SMask: softMask ? { Type: 'Mask', S: 'Luminosity', G: softMask } : undefined,
|
|
300
|
+
}));
|
|
301
|
+
this.states.set(key, ref);
|
|
302
|
+
}
|
|
303
|
+
return this.add('ExtGState', ref);
|
|
304
|
+
}
|
|
305
|
+
/** A copy of the dictionary now: the sections are copied too, so what is added later is not in it. */
|
|
306
|
+
snapshot() {
|
|
307
|
+
const { PDFDict } = this.assets.lib;
|
|
308
|
+
const copy = this.assets.context.obj({});
|
|
309
|
+
for (const [name, section] of this.dict.entries()) {
|
|
310
|
+
copy.set(name, section instanceof PDFDict ? section.clone() : section);
|
|
311
|
+
}
|
|
312
|
+
return copy;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type SizeMm } from '../printPdf.js';
|
|
2
|
+
import { type RasterizeOps } from './pdfContent.js';
|
|
3
|
+
import type { FontFileSet } from '../fonts/fontFiles.js';
|
|
4
|
+
import type { ExportReport, ExportScene, FontSpec } from '../scene/types.js';
|
|
5
|
+
/** `#rrggbb` (lower case) to the four ink values, 0..100. */
|
|
6
|
+
export type CmykMap = Readonly<Record<string, readonly [number, number, number, number]>>;
|
|
7
|
+
export interface WritePdfOptions {
|
|
8
|
+
mode: 'digital' | 'slides' | 'print';
|
|
9
|
+
/** Required for `print`: the scenes cover trim + bleed. */
|
|
10
|
+
print?: {
|
|
11
|
+
trimMm: SizeMm;
|
|
12
|
+
bleedMm: number;
|
|
13
|
+
};
|
|
14
|
+
/** The brand's print values; without it every colour is RGB. Keys are case-insensitive. */
|
|
15
|
+
cmyk?: CmykMap;
|
|
16
|
+
/** The brand colours (hex), for `report.rgbBrandColors`. */
|
|
17
|
+
brandPalette?: readonly string[];
|
|
18
|
+
/** The files of every face the scenes draw text in, by `${family}|${weight}|${style}`. */
|
|
19
|
+
fonts: ReadonlyMap<string, FontFileSet>;
|
|
20
|
+
title?: string;
|
|
21
|
+
/** Draws ops (page px, each with its own state) in a box of the page; see `rebaseOps`. */
|
|
22
|
+
rasterize: RasterizeOps;
|
|
23
|
+
/** Pixels of a raster island per page px. */
|
|
24
|
+
rasterPixelRatio: number;
|
|
25
|
+
/**
|
|
26
|
+
* The font an SVG image inherits where it names none (chart labels). Default: the family drawn
|
|
27
|
+
* most often in the scenes' own text.
|
|
28
|
+
*/
|
|
29
|
+
defaultFont?: FontSpec;
|
|
30
|
+
}
|
|
31
|
+
export declare function writePdf(pages: readonly ExportScene[], options: WritePdfOptions): Promise<{
|
|
32
|
+
bytes: Uint8Array;
|
|
33
|
+
report: ExportReport;
|
|
34
|
+
}>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
/**
|
|
3
|
+
* Writes resolved export scenes as a PDF with vector content: paths, real text in embedded subset
|
|
4
|
+
* fonts, gradients, patterns, clips, alpha and images, with the pictures only a rasteriser can make
|
|
5
|
+
* (blurred shadows, text no font covers, SVG it cannot convert) placed in between.
|
|
6
|
+
*
|
|
7
|
+
* `pdf-lib` and fontkit load here, by dynamic `import()`, and never with the module. The output
|
|
8
|
+
* depends on nothing but the scenes and the options: same input, same bytes.
|
|
9
|
+
*
|
|
10
|
+
* Three page layouts, one page per scene:
|
|
11
|
+
* - digital: 1 px = 1 pt.
|
|
12
|
+
* - slides: `SLIDE_PDF_PAGE_PT`, the scene stretched onto it.
|
|
13
|
+
* - print: the sheet of `pdfPageGeometry` (trim + bleed + the margin for crop marks); the scene,
|
|
14
|
+
* which covers trim + bleed, is placed on the bleed box and clipped to it, the boxes are set,
|
|
15
|
+
* and `cropMarkLines` are drawn in 100 % K.
|
|
16
|
+
*
|
|
17
|
+
* Colours: a solid paint (and a gradient of which every stop) in a colour of `options.cmyk` is
|
|
18
|
+
* written as DeviceCMYK with the brand's exact values; everything else is RGB.
|
|
19
|
+
*/
|
|
20
|
+
import { loadFontkit } from '../fonts/glyphs.js';
|
|
21
|
+
import { cropMarkLines, MARK_STROKE_PT, pdfPageGeometry } from '../printPdf.js';
|
|
22
|
+
import { emptyReport, mergeReports } from '../scene/types.js';
|
|
23
|
+
import { SLIDE_PDF_PAGE_PT } from '../slidesPdf.js';
|
|
24
|
+
import { mostUsedFont, svgDefaultsFor } from '../svg/svgImageScene.js';
|
|
25
|
+
import { ContentWriter } from './pdfContent.js';
|
|
26
|
+
import { fontkitForPdf } from './pdfFontkit.js';
|
|
27
|
+
import { matrixOperands, normalHex, num } from './pdfGeometry.js';
|
|
28
|
+
import { PageResources, PdfAssets } from './pdfResources.js';
|
|
29
|
+
export async function writePdf(pages, options) {
|
|
30
|
+
if (options.mode === 'print' && !options.print) {
|
|
31
|
+
throw new Error('writePdf: the print mode needs the trim size and the bleed of the format');
|
|
32
|
+
}
|
|
33
|
+
const lib = await import('pdf-lib');
|
|
34
|
+
const doc = await lib.PDFDocument.create({ updateMetadata: false });
|
|
35
|
+
doc.registerFontkit(fontkitForPdf(await loadFontkit()));
|
|
36
|
+
if (options.title)
|
|
37
|
+
doc.setTitle(options.title);
|
|
38
|
+
const assets = new PdfAssets(lib, doc, inksOf(options.cmyk));
|
|
39
|
+
const svgDefaults = svgDefaultsFor(options.fonts, options.defaultFont ?? mostUsedFont(pages));
|
|
40
|
+
let report = emptyReport();
|
|
41
|
+
for (const [index, scene] of pages.entries()) {
|
|
42
|
+
const own = emptyReport();
|
|
43
|
+
const resources = new PageResources(assets);
|
|
44
|
+
const env = {
|
|
45
|
+
assets,
|
|
46
|
+
resources,
|
|
47
|
+
page: index + 1,
|
|
48
|
+
width: scene.width,
|
|
49
|
+
height: scene.height,
|
|
50
|
+
fonts: options.fonts,
|
|
51
|
+
report: own,
|
|
52
|
+
rasterize: options.rasterize,
|
|
53
|
+
pixelRatio: options.rasterPixelRatio,
|
|
54
|
+
svgDefaults,
|
|
55
|
+
elementId: null,
|
|
56
|
+
};
|
|
57
|
+
const layout = layoutOf(scene, options);
|
|
58
|
+
const content = new ContentWriter(env, layout.matrix);
|
|
59
|
+
if (layout.print) {
|
|
60
|
+
// Crop marks outside the bleed box, then the scene inside it: art that hangs out of the
|
|
61
|
+
// canvas must not reach the margin the marks stand in.
|
|
62
|
+
content.raw('q');
|
|
63
|
+
for (const line of layout.print.marks)
|
|
64
|
+
content.raw(line);
|
|
65
|
+
content.raw('Q');
|
|
66
|
+
content.raw('q');
|
|
67
|
+
content.raw(layout.print.clip);
|
|
68
|
+
}
|
|
69
|
+
// Content is page px with y down; one transform puts it on the page.
|
|
70
|
+
content.raw(`${matrixOperands(layout.matrix)} cm`);
|
|
71
|
+
for (const item of scene.items) {
|
|
72
|
+
env.elementId = item.elementId;
|
|
73
|
+
await content.ops(item.ops);
|
|
74
|
+
}
|
|
75
|
+
if (layout.print)
|
|
76
|
+
content.raw('Q');
|
|
77
|
+
const page = doc.addPage([layout.width, layout.height]);
|
|
78
|
+
if (layout.print) {
|
|
79
|
+
const { bleedBox, trimBox } = layout.print;
|
|
80
|
+
page.setBleedBox(bleedBox.x, bleedBox.y, bleedBox.width, bleedBox.height);
|
|
81
|
+
page.setTrimBox(trimBox.x, trimBox.y, trimBox.width, trimBox.height);
|
|
82
|
+
}
|
|
83
|
+
page.node.set(lib.PDFName.of('Resources'), resources.ref);
|
|
84
|
+
page.node.set(lib.PDFName.of('Contents'), doc.context.register(doc.context.flateStream(content.text())));
|
|
85
|
+
report = mergeReports(mergeReports(report, scene.report), own);
|
|
86
|
+
}
|
|
87
|
+
// The brand colours that ended up RGB: all of them in a pack without a map, the unmapped ones
|
|
88
|
+
// in a pack with one.
|
|
89
|
+
const palette = new Set((options.brandPalette ?? []).flatMap((colour) => normalHex(colour) ?? []));
|
|
90
|
+
report = mergeReports(report, {
|
|
91
|
+
...emptyReport(),
|
|
92
|
+
rgbBrandColors: [...assets.rgbHexes].filter((hex) => palette.has(hex)),
|
|
93
|
+
});
|
|
94
|
+
report.rgbBrandColors.sort();
|
|
95
|
+
// Object streams would hide the dictionaries from anyone who looks into the file.
|
|
96
|
+
return { bytes: await doc.save({ useObjectStreams: false }), report };
|
|
97
|
+
}
|
|
98
|
+
function layoutOf(scene, options) {
|
|
99
|
+
if (options.mode === 'slides') {
|
|
100
|
+
const { width, height } = SLIDE_PDF_PAGE_PT;
|
|
101
|
+
return {
|
|
102
|
+
width,
|
|
103
|
+
height,
|
|
104
|
+
matrix: [width / scene.width, 0, 0, -height / scene.height, 0, height],
|
|
105
|
+
print: null,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
if (options.mode === 'print') {
|
|
109
|
+
const { trimMm, bleedMm } = options.print;
|
|
110
|
+
const { mediaBox, bleedBox, trimBox } = pdfPageGeometry({ trimMm, bleedMm });
|
|
111
|
+
return {
|
|
112
|
+
width: mediaBox.width,
|
|
113
|
+
height: mediaBox.height,
|
|
114
|
+
matrix: [
|
|
115
|
+
bleedBox.width / scene.width,
|
|
116
|
+
0,
|
|
117
|
+
0,
|
|
118
|
+
-bleedBox.height / scene.height,
|
|
119
|
+
bleedBox.x,
|
|
120
|
+
bleedBox.y + bleedBox.height,
|
|
121
|
+
],
|
|
122
|
+
print: {
|
|
123
|
+
bleedBox,
|
|
124
|
+
trimBox,
|
|
125
|
+
clip: `${num(bleedBox.x)} ${num(bleedBox.y)} ${num(bleedBox.width)} ${num(bleedBox.height)} re W n`,
|
|
126
|
+
// 100 % K: a registration colour, never mixed from the brand's inks.
|
|
127
|
+
marks: [
|
|
128
|
+
'0 0 0 1 K',
|
|
129
|
+
`${num(MARK_STROKE_PT)} w`,
|
|
130
|
+
...cropMarkLines({ trimMm, bleedMm }).map(({ start, end }) => `${num(start.x)} ${num(start.y)} m ${num(end.x)} ${num(end.y)} l S`),
|
|
131
|
+
],
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
width: scene.width,
|
|
137
|
+
height: scene.height,
|
|
138
|
+
matrix: [1, 0, 0, -1, 0, scene.height],
|
|
139
|
+
print: null,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
// ---------------------------------------------------------------------------------------------
|
|
143
|
+
// Colour
|
|
144
|
+
/**
|
|
145
|
+
* The map by lower-case `#rrggbb`, in 0..1 (`#FFF` and `#0F3A52` both match what a scene paints).
|
|
146
|
+
* An entry whose key is no hex colour, or whose value is not four numbers, is left out: its colour
|
|
147
|
+
* would silently stay RGB, so the entries are named in one warning.
|
|
148
|
+
*/
|
|
149
|
+
function inksOf(map) {
|
|
150
|
+
const inks = new Map();
|
|
151
|
+
const unusable = [];
|
|
152
|
+
for (const [key, values] of Object.entries(map ?? {})) {
|
|
153
|
+
const hex = normalHex(key);
|
|
154
|
+
if (!hex || values.length !== 4 || !values.every(Number.isFinite)) {
|
|
155
|
+
unusable.push(key);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const [c, m, y, k] = values.map((value) => Math.min(100, Math.max(0, value)) / 100);
|
|
159
|
+
inks.set(hex, [c, m, y, k]);
|
|
160
|
+
}
|
|
161
|
+
if (unusable.length > 0) {
|
|
162
|
+
console.warn(`[writePdf] CMYK entries left out, those colours stay RGB: ${unusable.join(', ')}`);
|
|
163
|
+
}
|
|
164
|
+
return inks;
|
|
165
|
+
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Browser-Seite des PPTX-Exports: Seitenzustände → Modell → Datei. Texte
|
|
3
3
|
* werden mit derselben Messung wie auf dem Canvas vermessen, Raster-Anfragen
|
|
4
|
-
* gehen an das Stage der jeweiligen Seite,
|
|
4
|
+
* gehen an das Stage der jeweiligen Seite (als SVG, wo die Aufnahme ganz Vektor ist, sonst als
|
|
5
|
+
* PNG), Bilder werden als PNG/JPEG geladen.
|
|
5
6
|
*/
|
|
6
7
|
import { type BrandPack } from '@ggraphic/core';
|
|
7
8
|
import { type PptxPageState } from './buildPptxModel.js';
|
|
8
9
|
import { type PptxLoadedImage, type PptxRasterImage } from './writePptx.js';
|
|
9
10
|
import type { CanvasFormat } from '../../formats/index.js';
|
|
11
|
+
import type { VectorExportDeps } from '../vectorExport.js';
|
|
10
12
|
/**
|
|
11
13
|
* Ein Bild als PNG/JPEG-Data-URL mit Eigenmaßen. WebP, GIF und SVG kennt
|
|
12
14
|
* nicht jedes Präsentationsprogramm, sie werden zu PNG. `null`, wenn die
|
|
@@ -18,9 +20,15 @@ export interface ExportPptxDeckOptions {
|
|
|
18
20
|
format: CanvasFormat;
|
|
19
21
|
/** Rastert ein Element der Seite `slideIndex`; null ohne Knoten. */
|
|
20
22
|
rasterizeElement: (slideIndex: number, elementId: string) => Promise<PptxRasterImage | null>;
|
|
23
|
+
/**
|
|
24
|
+
* What the SVG export records pages with (`recordPage(slideIndex)` among it). With it, an
|
|
25
|
+
* element that would be a PNG is an SVG image when its recording is vector all the way; the PNG
|
|
26
|
+
* stays for the rest. Each slide is recorded once, and only if one of its elements asks.
|
|
27
|
+
*/
|
|
28
|
+
vector?: VectorExportDeps;
|
|
21
29
|
title?: string;
|
|
22
30
|
/** Das Paket des Dokuments (`FullCanvasConfig.brand`); ohne: das aktive. */
|
|
23
31
|
brand?: BrandPack;
|
|
24
32
|
onProgress?: (done: number, total: number) => void;
|
|
25
33
|
}
|
|
26
|
-
export declare function exportPptxDeck({ pages, format, rasterizeElement, title, brand, onProgress, }: ExportPptxDeckOptions): Promise<Blob>;
|
|
34
|
+
export declare function exportPptxDeck({ pages, format, rasterizeElement, vector, title, brand, onProgress, }: ExportPptxDeckOptions): Promise<Blob>;
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Browser-Seite des PPTX-Exports: Seitenzustände → Modell → Datei. Texte
|
|
4
4
|
* werden mit derselben Messung wie auf dem Canvas vermessen, Raster-Anfragen
|
|
5
|
-
* gehen an das Stage der jeweiligen Seite,
|
|
5
|
+
* gehen an das Stage der jeweiligen Seite (als SVG, wo die Aufnahme ganz Vektor ist, sonst als
|
|
6
|
+
* PNG), Bilder werden als PNG/JPEG geladen.
|
|
6
7
|
*/
|
|
7
8
|
import { measureTextWidthWithFont } from '../../utils/textUtils.js';
|
|
8
9
|
import { buildPptxModel } from './buildPptxModel.js';
|
|
10
|
+
import { createVectorizer } from './vectorizeElement.js';
|
|
9
11
|
import { writePptx } from './writePptx.js';
|
|
10
12
|
const PPTX_IMAGE_TYPES = ['image/png', 'image/jpeg'];
|
|
11
13
|
/** SVGs ohne Eigenmaße werden in dieser Breite gerastert. */
|
|
@@ -65,13 +67,14 @@ export async function loadPptxImage(src) {
|
|
|
65
67
|
return null;
|
|
66
68
|
}
|
|
67
69
|
}
|
|
68
|
-
export async function exportPptxDeck({ pages, format, rasterizeElement, title, brand, onProgress, }) {
|
|
70
|
+
export async function exportPptxDeck({ pages, format, rasterizeElement, vector, title, brand, onProgress, }) {
|
|
69
71
|
const model = buildPptxModel(pages, format, {
|
|
70
72
|
measure: measureTextWidthWithFont,
|
|
71
73
|
...(brand ? { brand } : {}),
|
|
72
74
|
});
|
|
73
75
|
const { blob } = await writePptx(model, {
|
|
74
76
|
rasterize: (request, slideIndex) => rasterizeElement(slideIndex, request.elementId),
|
|
77
|
+
...(vector ? { vectorize: createVectorizer(vector) } : {}),
|
|
75
78
|
loadImage: loadPptxImage,
|
|
76
79
|
...(title ? { title } : {}),
|
|
77
80
|
...(onProgress ? { onProgress } : {}),
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the PPTX export checks of an SVG before it puts it in a slide. pptxgenjs makes the PNG
|
|
3
|
+
* preview of every SVG image in one `Promise.all` with the rest of the media: an SVG that the
|
|
4
|
+
* browser cannot decode, or that taints the canvas the preview is drawn on, rejects the lot and
|
|
5
|
+
* the whole deck is lost. The same checks made here cost only that element its SVG.
|
|
6
|
+
*/
|
|
7
|
+
/** The data URL pptxgenjs is given (and hands to its own `Image`). UTF-8, not Latin-1. */
|
|
8
|
+
export declare function svgDataUrl(svg: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Whether the text parses as an SVG document. A label with a control character, say, makes
|
|
11
|
+
* invalid XML that no `Image` loads. Without a `DOMParser` (node) there is nothing to ask.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isWellFormedSvg(svg: string): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Whether a browser decodes the SVG and lets a canvas export it: what `createSvgPngPreview` of
|
|
16
|
+
* pptxgenjs does, minus the size (one pixel is enough to see a refusal, and costs no memory).
|
|
17
|
+
* Browser only.
|
|
18
|
+
*/
|
|
19
|
+
export declare function canPreviewSvg(svg: string): Promise<boolean>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
/**
|
|
3
|
+
* What the PPTX export checks of an SVG before it puts it in a slide. pptxgenjs makes the PNG
|
|
4
|
+
* preview of every SVG image in one `Promise.all` with the rest of the media: an SVG that the
|
|
5
|
+
* browser cannot decode, or that taints the canvas the preview is drawn on, rejects the lot and
|
|
6
|
+
* the whole deck is lost. The same checks made here cost only that element its SVG.
|
|
7
|
+
*/
|
|
8
|
+
/** The data URL pptxgenjs is given (and hands to its own `Image`). UTF-8, not Latin-1. */
|
|
9
|
+
export function svgDataUrl(svg) {
|
|
10
|
+
const bytes = new TextEncoder().encode(svg);
|
|
11
|
+
let binary = '';
|
|
12
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
13
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
14
|
+
}
|
|
15
|
+
return `data:image/svg+xml;base64,${btoa(binary)}`;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Whether the text parses as an SVG document. A label with a control character, say, makes
|
|
19
|
+
* invalid XML that no `Image` loads. Without a `DOMParser` (node) there is nothing to ask.
|
|
20
|
+
*/
|
|
21
|
+
export function isWellFormedSvg(svg) {
|
|
22
|
+
if (typeof DOMParser === 'undefined')
|
|
23
|
+
return true;
|
|
24
|
+
try {
|
|
25
|
+
const document = new DOMParser().parseFromString(svg, 'image/svg+xml');
|
|
26
|
+
return (document.documentElement.localName === 'svg' &&
|
|
27
|
+
document.getElementsByTagName('parsererror').length === 0);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Whether a browser decodes the SVG and lets a canvas export it: what `createSvgPngPreview` of
|
|
35
|
+
* pptxgenjs does, minus the size (one pixel is enough to see a refusal, and costs no memory).
|
|
36
|
+
* Browser only.
|
|
37
|
+
*/
|
|
38
|
+
export function canPreviewSvg(svg) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
const image = new Image();
|
|
41
|
+
image.onload = () => {
|
|
42
|
+
// pptxgenjs treats an image without a size as an error.
|
|
43
|
+
if (image.width + image.height === 0)
|
|
44
|
+
return resolve(false);
|
|
45
|
+
try {
|
|
46
|
+
const canvas = document.createElement('canvas');
|
|
47
|
+
canvas.width = 1;
|
|
48
|
+
canvas.height = 1;
|
|
49
|
+
const context = canvas.getContext('2d');
|
|
50
|
+
if (!context)
|
|
51
|
+
return resolve(false);
|
|
52
|
+
context.drawImage(image, 0, 0, 1, 1);
|
|
53
|
+
// Throws on a tainted canvas.
|
|
54
|
+
canvas.toDataURL('image/png');
|
|
55
|
+
resolve(true);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
resolve(false);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
image.onerror = () => resolve(false);
|
|
62
|
+
image.src = svgDataUrl(svg);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type VectorExportDeps } from '../vectorExport.js';
|
|
2
|
+
import type { PptxRasterRequest } from './types.js';
|
|
3
|
+
import type { PptxVectorImage } from './writePptx.js';
|
|
4
|
+
export type Vectorize = (request: PptxRasterRequest, slideIndex: number) => Promise<PptxVectorImage | null>;
|
|
5
|
+
export interface VectorizeOptions {
|
|
6
|
+
/** Whether a browser decodes this SVG and lets a canvas export it. Default: `canPreviewSvg`. */
|
|
7
|
+
canPreview?: (svg: string) => Promise<boolean>;
|
|
8
|
+
}
|
|
9
|
+
export declare function createVectorizer(deps: VectorExportDeps, { canPreview }?: VectorizeOptions): Vectorize;
|