@ggraphic/editor 0.1.0-alpha.5 → 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/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 +28 -3
- 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/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/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,566 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
/**
|
|
3
|
+
* Writes scene ops as the operators of a PDF content stream.
|
|
4
|
+
*
|
|
5
|
+
* - Every op is its own `q ... Q`: clips (in page px, each mapped by its own matrix, `W n`), then
|
|
6
|
+
* the op's matrix as `cm`, then the graphics state and the paint. Nothing leaks to the next op.
|
|
7
|
+
* - Content is page px with y down. The page's single `cm` flips it; `base` is what maps that
|
|
8
|
+
* flipped space to the default space of the stream being written, which a pattern matrix needs.
|
|
9
|
+
* - Alpha is an `ExtGState` (`ca` and `CA`). A gradient with stops of different alpha adds a
|
|
10
|
+
* luminosity soft mask. A group with several children and an alpha is a transparency group
|
|
11
|
+
* (a form XObject), so the alpha applies to the group as one picture.
|
|
12
|
+
* - Text is real text: embedded subset fonts, one `Tm` per run and `TJ` adjustments that put every
|
|
13
|
+
* glyph at the x the browser measured. A font that may not be embedded is drawn as outlines;
|
|
14
|
+
* what no font file covers becomes a raster island.
|
|
15
|
+
* - Raster islands are asked for through `rasterize`; an island nobody could make is reported in
|
|
16
|
+
* `missingElements`, never left out quietly.
|
|
17
|
+
*/
|
|
18
|
+
import { advanceOf, fakeBoldWidth, glyphOutline, splitRuns, } from '../fonts/glyphs.js';
|
|
19
|
+
import { IDENTITY, invert, multiply } from '../scene/matrix.js';
|
|
20
|
+
import { fitPixelRatio } from '../scene/rasterLimit.js';
|
|
21
|
+
import { svgImageGroup } from '../svg/svgImageScene.js';
|
|
22
|
+
import { formatNumber } from '../svg/xml.js';
|
|
23
|
+
import { commandsBounds, growRect, intersectRect, isDegenerate, isIdentity, matrixOperands, num, opBounds, pathOperators, strokePad, textBounds, transformRect, unionRect, unit, } from './pdfGeometry.js';
|
|
24
|
+
const PLAIN_STROKE = {
|
|
25
|
+
width: 1,
|
|
26
|
+
cap: 'butt',
|
|
27
|
+
join: 'miter',
|
|
28
|
+
miterLimit: 10,
|
|
29
|
+
dash: [],
|
|
30
|
+
dashOffset: 0,
|
|
31
|
+
};
|
|
32
|
+
const CAP = { butt: 0, round: 1, square: 2 };
|
|
33
|
+
const JOIN = { miter: 0, round: 1, bevel: 2 };
|
|
34
|
+
/** Nothing to see in a run of these: no island for a zero-width space. */
|
|
35
|
+
const SOFT_HYPHEN = 0xad;
|
|
36
|
+
const INVISIBLE = /^[\p{Cc}\p{Cf}\p{Zs}]*$/u;
|
|
37
|
+
const rgb = (hex) => [1, 3, 5].map((at) => unit(Number.parseInt(hex.slice(at, at + 2), 16) / 255)).join(' ');
|
|
38
|
+
const faceKey = (op) => `${op.font.family}|${op.font.weight}|${op.font.style}`;
|
|
39
|
+
export class ContentWriter {
|
|
40
|
+
env;
|
|
41
|
+
base;
|
|
42
|
+
lines = [];
|
|
43
|
+
/**
|
|
44
|
+
* @param base maps the page px space the ops are in to the default space of the stream this
|
|
45
|
+
* writes: the page flip for the page, the identity inside a form drawn after that flip.
|
|
46
|
+
*/
|
|
47
|
+
constructor(env, base) {
|
|
48
|
+
this.env = env;
|
|
49
|
+
this.base = base;
|
|
50
|
+
}
|
|
51
|
+
raw(line) {
|
|
52
|
+
this.lines.push(line);
|
|
53
|
+
}
|
|
54
|
+
text() {
|
|
55
|
+
return this.lines.join('\n');
|
|
56
|
+
}
|
|
57
|
+
async ops(ops) {
|
|
58
|
+
for (const op of ops)
|
|
59
|
+
await this.op(op);
|
|
60
|
+
}
|
|
61
|
+
async op(op) {
|
|
62
|
+
if (op.clips.some((clip) => clip.commands.length === 0))
|
|
63
|
+
return; // clips everything away
|
|
64
|
+
if (isDegenerate(op.matrix))
|
|
65
|
+
return;
|
|
66
|
+
if (op.shadow)
|
|
67
|
+
await this.shadowIsland(op, op.shadow);
|
|
68
|
+
switch (op.kind) {
|
|
69
|
+
case 'path':
|
|
70
|
+
return this.path(op);
|
|
71
|
+
case 'text':
|
|
72
|
+
return this.textOp(op);
|
|
73
|
+
case 'image':
|
|
74
|
+
return this.image(op);
|
|
75
|
+
case 'group':
|
|
76
|
+
return this.group(op);
|
|
77
|
+
case 'raster':
|
|
78
|
+
return this.raster(op);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// -- graphics state ----------------------------------------------------------------------
|
|
82
|
+
/** `q`, the clips, and the matrix. Every `begin` has an `end`. */
|
|
83
|
+
begin(op, matrix = op.matrix) {
|
|
84
|
+
this.raw('q');
|
|
85
|
+
for (const clip of op.clips)
|
|
86
|
+
this.clip(clip);
|
|
87
|
+
if (!isIdentity(matrix))
|
|
88
|
+
this.raw(`${matrixOperands(matrix)} cm`);
|
|
89
|
+
}
|
|
90
|
+
end() {
|
|
91
|
+
this.raw('Q');
|
|
92
|
+
}
|
|
93
|
+
/** The clip path in page px: its own matrix applied here, so it needs no `cm` of its own. */
|
|
94
|
+
clip(clip) {
|
|
95
|
+
this.raw(`${pathOperators(clip.commands, clip.matrix)} ${clip.rule === 'evenodd' ? 'W*' : 'W'} n`);
|
|
96
|
+
}
|
|
97
|
+
alpha(alpha, softMask = null) {
|
|
98
|
+
return alpha >= 0.99995 && !softMask
|
|
99
|
+
? []
|
|
100
|
+
: [`${this.env.resources.extGState(alpha, softMask)} gs`];
|
|
101
|
+
}
|
|
102
|
+
strokeState(stroke) {
|
|
103
|
+
const s = stroke ?? PLAIN_STROKE;
|
|
104
|
+
const dashed = s.dash.length > 0 &&
|
|
105
|
+
s.dash.every((length) => Number.isFinite(length) && length >= 0) &&
|
|
106
|
+
s.dash.some((length) => length > 0);
|
|
107
|
+
return [
|
|
108
|
+
`${num(s.width)} w`,
|
|
109
|
+
`${CAP[s.cap]} J`,
|
|
110
|
+
`${JOIN[s.join]} j`,
|
|
111
|
+
...(s.join === 'miter' ? [`${num(s.miterLimit)} M`] : []),
|
|
112
|
+
`[${dashed ? s.dash.map(num).join(' ') : ''}] ${dashed ? num(s.dashOffset) : 0} d`,
|
|
113
|
+
];
|
|
114
|
+
}
|
|
115
|
+
// -- paint -------------------------------------------------------------------------------
|
|
116
|
+
/**
|
|
117
|
+
* The operators that set alpha and the colour of a fill or a stroke, or null if the paint draws
|
|
118
|
+
* nothing. `matrix` is the op's, `bounds` the area it touches in its user space (a soft mask is
|
|
119
|
+
* as large as that and no larger).
|
|
120
|
+
*/
|
|
121
|
+
async paint(mode, paint, op, bounds) {
|
|
122
|
+
const { assets, resources } = this.env;
|
|
123
|
+
const stroke = mode === 'stroke';
|
|
124
|
+
switch (paint.type) {
|
|
125
|
+
case 'solid':
|
|
126
|
+
return [...this.alpha(op.alpha * paint.alpha), this.colour(paint.hex, stroke)];
|
|
127
|
+
case 'linear':
|
|
128
|
+
case 'radial': {
|
|
129
|
+
// Every stop in the brand's CMYK map: a CMYK shading. One that is not: RGB, all of it.
|
|
130
|
+
const mapped = paint.stops.length > 0 &&
|
|
131
|
+
paint.stops.every((stop) => assets.cmyk.has(stop.hex.toLowerCase()));
|
|
132
|
+
const shading = assets.shading(paint, mapped ? 'cmyk' : 'rgb');
|
|
133
|
+
if (!shading)
|
|
134
|
+
return null; // canvas paints nothing for these
|
|
135
|
+
if (!mapped)
|
|
136
|
+
for (const stop of paint.stops)
|
|
137
|
+
assets.rgbHexes.add(stop.hex.toLowerCase());
|
|
138
|
+
const first = paint.stops[0]?.alpha ?? 1;
|
|
139
|
+
const uniform = paint.stops.every((stop) => stop.alpha === first);
|
|
140
|
+
const mask = uniform ? null : assets.alphaMask(paint, growRect(bounds, 1));
|
|
141
|
+
const pattern = assets.shadingPattern(shading, multiply(this.base, op.matrix));
|
|
142
|
+
return [
|
|
143
|
+
...this.alpha(op.alpha * (uniform ? first : 1), mask),
|
|
144
|
+
`/Pattern ${stroke ? 'CS' : 'cs'} ${resources.pattern(pattern)} ${stroke ? 'SCN' : 'scn'}`,
|
|
145
|
+
];
|
|
146
|
+
}
|
|
147
|
+
case 'pattern': {
|
|
148
|
+
const tile = paint.image;
|
|
149
|
+
const image = tile.kind === 'bitmap'
|
|
150
|
+
? await assets.bitmap(tile)
|
|
151
|
+
: tile.kind === 'svg'
|
|
152
|
+
? await this.rasterTile(tile)
|
|
153
|
+
: null;
|
|
154
|
+
if (!image) {
|
|
155
|
+
this.missing();
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
const matrix = multiply(this.base, multiply(op.matrix, paint.matrix));
|
|
159
|
+
const pattern = assets.tilingPattern(image, tile.width, tile.height, matrix);
|
|
160
|
+
return [
|
|
161
|
+
...this.alpha(op.alpha),
|
|
162
|
+
`/Pattern ${stroke ? 'CS' : 'cs'} ${resources.pattern(pattern)} ${stroke ? 'SCN' : 'scn'}`,
|
|
163
|
+
];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The operator that sets a fill or stroke colour: DeviceCMYK with the brand's exact values if it
|
|
169
|
+
* has them for this colour, else RGB (which `report.rgbBrandColors` is made from).
|
|
170
|
+
*/
|
|
171
|
+
colour(hex, stroke) {
|
|
172
|
+
const key = hex.toLowerCase();
|
|
173
|
+
const ink = this.env.assets.cmyk.get(key);
|
|
174
|
+
if (ink)
|
|
175
|
+
return `${ink.map(unit).join(' ')} ${stroke ? 'K' : 'k'}`;
|
|
176
|
+
this.env.assets.rgbHexes.add(key);
|
|
177
|
+
return `${rgb(key)} ${stroke ? 'RG' : 'rg'}`;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* An SVG tile cannot be a PDF image: it is drawn once, at its size, by the rasteriser. Once per
|
|
181
|
+
* document, however many paints use it; it is an island only if there is a picture.
|
|
182
|
+
*/
|
|
183
|
+
rasterTile(tile) {
|
|
184
|
+
return this.env.assets.once(tile, async () => {
|
|
185
|
+
const ops = [
|
|
186
|
+
{
|
|
187
|
+
matrix: IDENTITY,
|
|
188
|
+
alpha: 1,
|
|
189
|
+
clips: [],
|
|
190
|
+
shadow: null,
|
|
191
|
+
kind: 'image',
|
|
192
|
+
image: tile,
|
|
193
|
+
sx: 0,
|
|
194
|
+
sy: 0,
|
|
195
|
+
sw: tile.width,
|
|
196
|
+
sh: tile.height,
|
|
197
|
+
dx: 0,
|
|
198
|
+
dy: 0,
|
|
199
|
+
dw: tile.width,
|
|
200
|
+
dh: tile.height,
|
|
201
|
+
},
|
|
202
|
+
];
|
|
203
|
+
const { assets, report, page } = this.env;
|
|
204
|
+
const png = await this.env.rasterize(ops, { x: 0, y: 0, width: tile.width, height: tile.height }, this.env.pixelRatio);
|
|
205
|
+
const image = png ? await assets.image(tile, png, 'image/png') : null;
|
|
206
|
+
if (image) {
|
|
207
|
+
report.rasterIslands.push({
|
|
208
|
+
page,
|
|
209
|
+
elementId: this.env.elementId,
|
|
210
|
+
reason: 'unsupported-pattern',
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return image;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
missing() {
|
|
217
|
+
const { report, page } = this.env;
|
|
218
|
+
report.missingElements.push({
|
|
219
|
+
page,
|
|
220
|
+
elementId: this.env.elementId,
|
|
221
|
+
reason: 'image-unreadable',
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
// -- paths -------------------------------------------------------------------------------
|
|
225
|
+
async path(op) {
|
|
226
|
+
if (op.commands.length === 0)
|
|
227
|
+
return;
|
|
228
|
+
const bounds = commandsBounds(op.commands);
|
|
229
|
+
if (!bounds)
|
|
230
|
+
return;
|
|
231
|
+
await this.paintPath(op, op.commands, bounds, op.mode === 'stroke' ? strokePad(op.stroke) : 0);
|
|
232
|
+
}
|
|
233
|
+
/** `commands` painted with the op's paint, in the op's space; `pad` is how far a stroke reaches. */
|
|
234
|
+
async paintPath(op, commands, bounds, pad) {
|
|
235
|
+
const paint = await this.paint(op.mode, op.paint, op, growRect(bounds, pad));
|
|
236
|
+
if (!paint)
|
|
237
|
+
return;
|
|
238
|
+
this.begin(op);
|
|
239
|
+
for (const line of paint)
|
|
240
|
+
this.raw(line);
|
|
241
|
+
if (op.mode === 'stroke')
|
|
242
|
+
for (const line of this.strokeState(op.stroke))
|
|
243
|
+
this.raw(line);
|
|
244
|
+
this.raw(typeof commands === 'string' ? commands : pathOperators(commands));
|
|
245
|
+
this.raw(op.mode === 'stroke' ? 'S' : op.rule === 'evenodd' ? 'f*' : 'f');
|
|
246
|
+
this.end();
|
|
247
|
+
}
|
|
248
|
+
// -- text --------------------------------------------------------------------------------
|
|
249
|
+
async textOp(op) {
|
|
250
|
+
if (op.text === '' || !(op.font.size > 0))
|
|
251
|
+
return;
|
|
252
|
+
const set = this.env.fonts.get(faceKey(op));
|
|
253
|
+
const runs = set
|
|
254
|
+
? splitRuns(set, op.text, op.xs)
|
|
255
|
+
: [{ file: null, text: op.text, xs: op.xs }];
|
|
256
|
+
const hasFiles = !!set && set.files.length > 0;
|
|
257
|
+
for (const run of runs) {
|
|
258
|
+
if (run.file?.variation === 'default-only') {
|
|
259
|
+
const { defaultInstanceFonts } = this.env.report;
|
|
260
|
+
if (!defaultInstanceFonts.includes(op.font.family))
|
|
261
|
+
defaultInstanceFonts.push(op.font.family);
|
|
262
|
+
}
|
|
263
|
+
if (run.file === null) {
|
|
264
|
+
await this.rasterRun(op, run, hasFiles ? 'missing-glyph' : 'font-unavailable');
|
|
265
|
+
}
|
|
266
|
+
else if (run.file.embeddable === 'bitmap-only') {
|
|
267
|
+
await this.rasterRun(op, run, 'bitmap-only-font');
|
|
268
|
+
}
|
|
269
|
+
else if (run.file.embeddable === 'outlines-only') {
|
|
270
|
+
await this.outlineRun(op, run, run.file);
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
await this.textRun(op, run, run.file, set);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/** Real text: the glyphs of `run` in the embedded subset of `file`, each at its measured x. */
|
|
278
|
+
async textRun(op, run, file, set) {
|
|
279
|
+
const { assets, resources } = this.env;
|
|
280
|
+
const font = await assets.font(file, set.face, set.files.indexOf(file));
|
|
281
|
+
const size = op.font.size;
|
|
282
|
+
const perEm = 1000 / file.font.unitsPerEm;
|
|
283
|
+
// Pen position in user space after each glyph; a number in `TJ` moves it by -n/1000 em.
|
|
284
|
+
const x0 = run.xs[0] ?? 0;
|
|
285
|
+
let pen = x0;
|
|
286
|
+
let hex = '';
|
|
287
|
+
const parts = [];
|
|
288
|
+
Array.from(run.text).forEach((char, index) => {
|
|
289
|
+
const codePoint = char.codePointAt(0) ?? 0;
|
|
290
|
+
// A soft hyphen is not drawn and 0 wide in a canvas (it only shows at a line break, which
|
|
291
|
+
// the recorded text never has): no glyph, and the pen stays where it is.
|
|
292
|
+
if (codePoint === SOFT_HYPHEN)
|
|
293
|
+
return;
|
|
294
|
+
const x = run.xs[index];
|
|
295
|
+
if (index > 0 && x !== undefined) {
|
|
296
|
+
const shift = Number(formatNumber(((pen - x) * 1000) / size, 2));
|
|
297
|
+
if (Math.abs(shift) >= 0.05) {
|
|
298
|
+
if (hex)
|
|
299
|
+
parts.push(`<${hex}>`);
|
|
300
|
+
hex = '';
|
|
301
|
+
parts.push(shift);
|
|
302
|
+
pen -= (shift * size) / 1000;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
// `encodeText` is what makes pdf-lib keep this glyph in the subset.
|
|
306
|
+
hex += font.encodeText(char).toString().slice(1, -1);
|
|
307
|
+
// The advance of the glyphs `encodeText` wrote (it shapes), which is the width in `/W`.
|
|
308
|
+
pen += advanceOf(file.font, codePoint) * perEm * (size / 1000);
|
|
309
|
+
});
|
|
310
|
+
if (hex)
|
|
311
|
+
parts.push(`<${hex}>`);
|
|
312
|
+
if (parts.length === 0)
|
|
313
|
+
return;
|
|
314
|
+
const bounds = textBounds({ ...op, xs: run.xs });
|
|
315
|
+
if (!bounds)
|
|
316
|
+
return;
|
|
317
|
+
const paint = await this.paint(op.mode, op.paint, op, bounds);
|
|
318
|
+
if (!paint)
|
|
319
|
+
return;
|
|
320
|
+
// A regular cut standing in for a bold: filled and stroked in the fill's colour (mode 2), the
|
|
321
|
+
// outline growing by a line of `fakeBoldWidth`.
|
|
322
|
+
const bold = file.fakeBold && op.mode === 'fill';
|
|
323
|
+
const boldStroke = bold ? await this.paint('stroke', op.paint, op, bounds) : null;
|
|
324
|
+
this.begin(op);
|
|
325
|
+
for (const line of paint)
|
|
326
|
+
this.raw(line);
|
|
327
|
+
if (boldStroke) {
|
|
328
|
+
for (const line of boldStroke)
|
|
329
|
+
this.raw(line);
|
|
330
|
+
this.raw(`${num(fakeBoldWidth(size))} w`);
|
|
331
|
+
this.raw(`${JOIN.round} j`);
|
|
332
|
+
}
|
|
333
|
+
if (op.mode === 'stroke')
|
|
334
|
+
for (const line of this.strokeState(op.stroke))
|
|
335
|
+
this.raw(line);
|
|
336
|
+
this.raw('BT');
|
|
337
|
+
if (op.mode === 'stroke')
|
|
338
|
+
this.raw('1 Tr');
|
|
339
|
+
else if (bold)
|
|
340
|
+
this.raw('2 Tr');
|
|
341
|
+
this.raw(`${resources.font(font)} ${num(size)} Tf`);
|
|
342
|
+
// The page is y down, text is y up: a flipped text matrix stands the glyphs up again. An
|
|
343
|
+
// upright cut standing in for an italic is sheared by the `c` term (top of the glyph to the right).
|
|
344
|
+
this.raw(`1 0 ${num(file.slant)} -1 ${num(x0)} ${num(op.y)} Tm`);
|
|
345
|
+
this.raw(`[${parts.join(' ')}] TJ`);
|
|
346
|
+
this.raw('ET');
|
|
347
|
+
this.end();
|
|
348
|
+
}
|
|
349
|
+
/** A font whose licence forbids embedding: its glyph shapes as paths, crisp but not selectable. */
|
|
350
|
+
async outlineRun(op, run, file) {
|
|
351
|
+
const glyphs = glyphOutline(file, run.text, op.font.size);
|
|
352
|
+
const commands = glyphs
|
|
353
|
+
.map((glyph, index) => pathOperators(glyph.path, [1, 0, 0, 1, run.xs[index] ?? 0, op.y]))
|
|
354
|
+
.filter((operators) => operators !== '')
|
|
355
|
+
.join(' ');
|
|
356
|
+
if (commands === '')
|
|
357
|
+
return;
|
|
358
|
+
const { outlinedForLicence } = this.env.report;
|
|
359
|
+
if (!outlinedForLicence.includes(op.font.family))
|
|
360
|
+
outlinedForLicence.push(op.font.family);
|
|
361
|
+
const bounds = textBounds({ ...op, xs: run.xs });
|
|
362
|
+
if (!bounds)
|
|
363
|
+
return;
|
|
364
|
+
await this.paintPath({ ...op, rule: 'nonzero' }, commands, bounds, op.mode === 'stroke' ? strokePad(op.stroke) : 0);
|
|
365
|
+
}
|
|
366
|
+
/** The run as a picture: what no font file covers, drawn by whoever has a font for it. */
|
|
367
|
+
async rasterRun(op, run, reason) {
|
|
368
|
+
if (INVISIBLE.test(run.text))
|
|
369
|
+
return;
|
|
370
|
+
const { report, page } = this.env;
|
|
371
|
+
report.missingGlyphs.push({ page, elementId: this.env.elementId, text: run.text });
|
|
372
|
+
const bounds = textBounds({ ...op, xs: run.xs });
|
|
373
|
+
const box = bounds && this.visible(transformRect(bounds, op.matrix), op.clips);
|
|
374
|
+
if (!box)
|
|
375
|
+
return;
|
|
376
|
+
await this.island([{ ...op, text: run.text, xs: run.xs, shadow: null }], box, reason);
|
|
377
|
+
}
|
|
378
|
+
// -- shadows and islands -----------------------------------------------------------------
|
|
379
|
+
/**
|
|
380
|
+
* A shadow is a picture under the op, which stays vector. The picture holds the shadow alone:
|
|
381
|
+
* the op is replayed 'big' px to the left with its shadow offset by 'big' to the right, so the
|
|
382
|
+
* shape lands off the picture and only its shadow stays (a canvas draws the shadow of a shape
|
|
383
|
+
* wherever it is). The op's own alpha and clips are part of the picture.
|
|
384
|
+
*/
|
|
385
|
+
async shadowIsland(op, shadow) {
|
|
386
|
+
if (!(shadow.alpha > 0))
|
|
387
|
+
return;
|
|
388
|
+
if (shadow.blur === 0 && shadow.offsetX === 0 && shadow.offsetY === 0)
|
|
389
|
+
return; // none is drawn
|
|
390
|
+
const shape = opBounds({ ...op, clips: [] });
|
|
391
|
+
if (!shape)
|
|
392
|
+
return;
|
|
393
|
+
const reach = 1.5 * shadow.blur + 1; // three sigma of the Gaussian, and a pixel
|
|
394
|
+
const moved = growRect({
|
|
395
|
+
x0: shape.x0 + shadow.offsetX,
|
|
396
|
+
y0: shape.y0 + shadow.offsetY,
|
|
397
|
+
x1: shape.x1 + shadow.offsetX,
|
|
398
|
+
y1: shape.y1 + shadow.offsetY,
|
|
399
|
+
}, reach);
|
|
400
|
+
const box = this.visible(moved, op.clips);
|
|
401
|
+
if (!box)
|
|
402
|
+
return;
|
|
403
|
+
const big = Math.ceil(Math.max(0, shape.x1 - box.x0)) + 8;
|
|
404
|
+
const shadowOnly = {
|
|
405
|
+
...op,
|
|
406
|
+
matrix: multiply([1, 0, 0, 1, -big, 0], op.matrix),
|
|
407
|
+
shadow: { ...shadow, offsetX: shadow.offsetX + big },
|
|
408
|
+
};
|
|
409
|
+
await this.island([shadowOnly], box, 'shadow');
|
|
410
|
+
}
|
|
411
|
+
/** The part of `rect` (page px) the clips and the page let through. */
|
|
412
|
+
visible(rect, clips) {
|
|
413
|
+
let result = intersectRect(rect, {
|
|
414
|
+
x0: 0,
|
|
415
|
+
y0: 0,
|
|
416
|
+
x1: this.env.width,
|
|
417
|
+
y1: this.env.height,
|
|
418
|
+
});
|
|
419
|
+
for (const clip of clips) {
|
|
420
|
+
const box = commandsBounds(clip.commands);
|
|
421
|
+
if (!result || !box)
|
|
422
|
+
return null;
|
|
423
|
+
result = intersectRect(result, transformRect(box, clip.matrix));
|
|
424
|
+
}
|
|
425
|
+
return result;
|
|
426
|
+
}
|
|
427
|
+
/** Asks for the picture, places it, reports it; if there is none, reports that instead. */
|
|
428
|
+
async island(ops, box, reason) {
|
|
429
|
+
const { assets, resources, report, page } = this.env;
|
|
430
|
+
// A page-sized island at print resolution is more pixels than a canvas may have.
|
|
431
|
+
const fitted = fitPixelRatio(box.x1 - box.x0, box.y1 - box.y0, this.env.pixelRatio);
|
|
432
|
+
const pixelRatio = fitted.pixelRatio;
|
|
433
|
+
// Whole device px, so the picture and the box it is placed in are the same size.
|
|
434
|
+
const snapped = {
|
|
435
|
+
x0: Math.floor(box.x0 * pixelRatio) / pixelRatio,
|
|
436
|
+
y0: Math.floor(box.y0 * pixelRatio) / pixelRatio,
|
|
437
|
+
x1: Math.ceil(box.x1 * pixelRatio) / pixelRatio,
|
|
438
|
+
y1: Math.ceil(box.y1 * pixelRatio) / pixelRatio,
|
|
439
|
+
};
|
|
440
|
+
const png = await this.env.rasterize(ops, {
|
|
441
|
+
x: snapped.x0,
|
|
442
|
+
y: snapped.y0,
|
|
443
|
+
width: snapped.x1 - snapped.x0,
|
|
444
|
+
height: snapped.y1 - snapped.y0,
|
|
445
|
+
}, pixelRatio);
|
|
446
|
+
const image = png ? await assets.image(png, png, 'image/png') : null;
|
|
447
|
+
if (!image) {
|
|
448
|
+
this.missing(); // not an island: there is no picture
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
report.rasterIslands.push({ page, elementId: this.env.elementId, reason });
|
|
452
|
+
if (fitted.reduced)
|
|
453
|
+
report.reducedRasters.push({ page, elementId: this.env.elementId });
|
|
454
|
+
this.picture(resources.xobject(image.ref), snapped.x0, snapped.y0, snapped.x1 - snapped.x0, snapped.y1 - snapped.y0);
|
|
455
|
+
}
|
|
456
|
+
/** An image XObject over a rect of the (y down) page: the unit square, y up, stood on its head. */
|
|
457
|
+
picture(name, x, y, width, height) {
|
|
458
|
+
this.raw(`q ${matrixOperands([width, 0, 0, -height, x, y + height])} cm ${name} Do Q`);
|
|
459
|
+
}
|
|
460
|
+
// -- images ------------------------------------------------------------------------------
|
|
461
|
+
async image(op) {
|
|
462
|
+
const source = op.image;
|
|
463
|
+
if (op.sw === 0 || op.sh === 0 || op.dw === 0 || op.dh === 0)
|
|
464
|
+
return;
|
|
465
|
+
if (source.kind === 'element') {
|
|
466
|
+
this.missing(); // `resolveScene` leaves none; an unresolved one is not drawn, so it is said
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
if (source.kind === 'svg')
|
|
470
|
+
return this.svgImage(op, source);
|
|
471
|
+
const image = await this.env.assets.bitmap(source);
|
|
472
|
+
if (!image) {
|
|
473
|
+
this.missing();
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
// The canvas draws the source rect stretched onto the destination rect: the whole picture
|
|
477
|
+
// goes where it would land, and anything of it outside the destination rect is clipped.
|
|
478
|
+
const kx = op.dw / op.sw;
|
|
479
|
+
const ky = op.dh / op.sh;
|
|
480
|
+
const whole = num(op.sx) === '0' &&
|
|
481
|
+
num(op.sy) === '0' &&
|
|
482
|
+
num(op.sw) === num(source.width) &&
|
|
483
|
+
num(op.sh) === num(source.height);
|
|
484
|
+
this.begin(op);
|
|
485
|
+
for (const line of this.alpha(op.alpha))
|
|
486
|
+
this.raw(line);
|
|
487
|
+
if (!whole)
|
|
488
|
+
this.raw(`${num(op.dx)} ${num(op.dy)} ${num(op.dw)} ${num(op.dh)} re W n`);
|
|
489
|
+
this.picture(this.env.resources.xobject(image.ref), op.dx - op.sx * kx, op.dy - op.sy * ky, source.width * kx, source.height * ky);
|
|
490
|
+
this.end();
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* An SVG source is drawn as the ops `svgToScene` makes of it, with the image op's alpha, clips
|
|
494
|
+
* and a crop around them as a group (`svgImageGroup`). A source it cannot reproduce completely
|
|
495
|
+
* is one raster island, as a whole.
|
|
496
|
+
*/
|
|
497
|
+
async svgImage(op, source) {
|
|
498
|
+
const { group, unsupported } = svgImageGroup(op, source, this.env.svgDefaults, op.clips);
|
|
499
|
+
if (unsupported.length > 0) {
|
|
500
|
+
const bounds = opBounds({ ...op, clips: [] });
|
|
501
|
+
const box = bounds && this.visible(bounds, op.clips);
|
|
502
|
+
if (box)
|
|
503
|
+
await this.island([{ ...op, shadow: null }], box, 'svg-unsupported');
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
await this.group(group);
|
|
507
|
+
}
|
|
508
|
+
async raster(op) {
|
|
509
|
+
if (!op.png) {
|
|
510
|
+
// No pixels: what the island was made of, each op with its own state.
|
|
511
|
+
if (op.source)
|
|
512
|
+
await this.ops(op.source);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const image = await this.env.assets.image(op.png, op.png, 'image/png');
|
|
516
|
+
if (!image) {
|
|
517
|
+
this.missing();
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
this.begin(op);
|
|
521
|
+
for (const line of this.alpha(op.alpha))
|
|
522
|
+
this.raw(line);
|
|
523
|
+
this.picture(this.env.resources.xobject(image.ref), op.x, op.y, op.width, op.height);
|
|
524
|
+
this.end();
|
|
525
|
+
}
|
|
526
|
+
// -- groups ------------------------------------------------------------------------------
|
|
527
|
+
/**
|
|
528
|
+
* The children in the group's clips. A group is composited from a buffer, so its alpha applies
|
|
529
|
+
* to all of it at once: a transparency group when there are several children and an alpha. One
|
|
530
|
+
* child takes the alpha itself, which comes out the same.
|
|
531
|
+
*/
|
|
532
|
+
async group(op) {
|
|
533
|
+
if (op.ops.length === 0)
|
|
534
|
+
return;
|
|
535
|
+
const alone = op.ops.length === 1 ? op.ops[0] : null;
|
|
536
|
+
const flat = op.alpha >= 0.99995 || alone !== null;
|
|
537
|
+
const needsState = op.clips.length > 0 || !isIdentity(op.matrix);
|
|
538
|
+
if (flat) {
|
|
539
|
+
const children = alone ? [{ ...alone, alpha: alone.alpha * op.alpha }] : op.ops;
|
|
540
|
+
if (!needsState)
|
|
541
|
+
return this.ops(children);
|
|
542
|
+
// The children are drawn under the group's `cm`, so what maps their space to the stream's
|
|
543
|
+
// default space (a pattern matrix) has the group's matrix in it.
|
|
544
|
+
const inner = new ContentWriter(this.env, multiply(this.base, op.matrix));
|
|
545
|
+
await inner.ops(children);
|
|
546
|
+
this.begin(op);
|
|
547
|
+
// Not `push(...lines)`: the spread of a huge group overflows the stack.
|
|
548
|
+
for (const line of inner.lines)
|
|
549
|
+
this.lines.push(line);
|
|
550
|
+
this.end();
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const inner = new ContentWriter(this.env, IDENTITY);
|
|
554
|
+
await inner.ops(op.ops);
|
|
555
|
+
// The children are page px; the group's matrix moves the whole picture, so the form's box has
|
|
556
|
+
// to reach wherever the page lands under it.
|
|
557
|
+
const page = { x0: 0, y0: 0, x1: this.env.width, y1: this.env.height };
|
|
558
|
+
const bbox = unionRect(page, transformRect(page, invert(op.matrix)));
|
|
559
|
+
const form = this.env.assets.form(inner.text(), bbox, this.env.resources.snapshot(), {});
|
|
560
|
+
this.begin(op);
|
|
561
|
+
for (const line of this.alpha(op.alpha))
|
|
562
|
+
this.raw(line);
|
|
563
|
+
this.raw(`${this.env.resources.xobject(form)} Do`);
|
|
564
|
+
this.end();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fontkit that `pdf-lib` embeds fonts with, repaired for WOFF2.
|
|
3
|
+
*
|
|
4
|
+
* `embedFont(bytes, { subset: true })` has fontkit cut a subset out of the font: for every glyph
|
|
5
|
+
* it copies the glyph's bytes from the `glyf` table, found through `loca`. A WOFF2 file has no
|
|
6
|
+
* such tables. Its `glyf` and `loca` are stored transformed, fontkit decodes the glyphs straight
|
|
7
|
+
* from that form and never rebuilds the tables, so `font.loca` holds numbers that point nowhere
|
|
8
|
+
* (measured on Instrument Sans: offsets that go backwards). The copy then reads other glyphs'
|
|
9
|
+
* data and produces a font program whose glyphs are empty or damaged: the PDF is valid, the text
|
|
10
|
+
* is invisible. Worse, a composite glyph (`"`, `:`, every accented capital) writes past the end of
|
|
11
|
+
* its copy, in a timer callback, so the exception is not catchable and `save()` never settles.
|
|
12
|
+
*
|
|
13
|
+
* What does work in a WOFF2 font is `glyph.path`, which fontkit builds from the decoded glyphs and
|
|
14
|
+
* which the SVG writer already draws. The subset of such a font is therefore made from the paths:
|
|
15
|
+
* every glyph is written as a simple glyph (composites come out flattened) without instructions.
|
|
16
|
+
* fontkit has an encoder for this (`encodeSimple`, made for variable fonts); it leaves out the
|
|
17
|
+
* repeat count of a trailing run of equal flags, which makes the glyph unreadable, so the record is
|
|
18
|
+
* written here. Other fonts (TrueType, OpenType, WOFF) keep fontkit's own copy, exact for them.
|
|
19
|
+
*
|
|
20
|
+
* This reaches into fontkit's private parts (`TtfSubset`), so `@pdf-lib/fontkit` is pinned to an
|
|
21
|
+
* exact version in package.json (1.1.1): a bump is a decision, checked against `pdfFontkit.vitest.ts`,
|
|
22
|
+
* whose first describe pins each of these, one test per member:
|
|
23
|
+
*
|
|
24
|
+
* - `font.directory.tables.glyf.transformed` true for WOFF2 (the test for a repaired subset)
|
|
25
|
+
* - `font.createSubset()` replaced, to patch the subset it returns
|
|
26
|
+
* - `subset._addGlyph(id)` replaced by `addGlyphFromPath`
|
|
27
|
+
* - `subset.font.getGlyph(id)` glyph advance and path
|
|
28
|
+
* - `subset.glyphEncoder.encodeSimple(...)` only to reach the glyph-record buffer class
|
|
29
|
+
* - `subset.glyf`, `subset.loca.offsets`, `subset.hmtx.metrics`, `subset.offset`
|
|
30
|
+
* the tables `_addGlyph` appends to
|
|
31
|
+
* - `<record>.constructor.from(bytes)` makes a record of the class fontkit's stream takes
|
|
32
|
+
*/
|
|
33
|
+
import type { FontFile } from '../fonts/fontFiles.js';
|
|
34
|
+
import type * as FontkitModule from '@pdf-lib/fontkit';
|
|
35
|
+
import type { PDFDocument } from 'pdf-lib';
|
|
36
|
+
/** What `registerFontkit` takes; pdf-lib does not export the name. */
|
|
37
|
+
type Fontkit = Parameters<PDFDocument['registerFontkit']>[0];
|
|
38
|
+
interface PathSegment {
|
|
39
|
+
command: 'moveTo' | 'lineTo' | 'quadraticCurveTo' | 'bezierCurveTo' | 'closePath';
|
|
40
|
+
args: readonly number[];
|
|
41
|
+
}
|
|
42
|
+
/** The simple glyph record of `glyf`, aligned to four bytes, and the glyph's left edge. */
|
|
43
|
+
export declare function encodeSimpleGlyph(commands: readonly PathSegment[]): {
|
|
44
|
+
bytes: Uint8Array;
|
|
45
|
+
xMin: number;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The bytes to give `embedFont` for `file`: its own bytes, or for a variation instance a view of
|
|
49
|
+
* them that `fontkitForPdf(...).create` recognises (identity, not content).
|
|
50
|
+
*/
|
|
51
|
+
export declare function embeddableBytes(file: Pick<FontFile, 'bytes' | 'font' | 'variation'>): Uint8Array;
|
|
52
|
+
/** What `registerFontkit` takes: `create` as fontkit has it, with the WOFF2 subset repaired. */
|
|
53
|
+
export declare function fontkitForPdf(fontkit: typeof FontkitModule): Fontkit;
|
|
54
|
+
export {};
|