resvg-napi 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,17 @@
1
- # resvg-napi
1
+ # Render and inspect SVG
2
2
 
3
- Node.js bindings for [resvg](https://github.com/linebender/resvg) 0.48: render
4
- SVG to PNG, and read back what usvg made of the document — the resolved tree,
5
- text metrics, paint, geometry.
3
+ [![npm](https://img.shields.io/npm/v/resvg-napi)](https://www.npmjs.com/package/resvg-napi)
4
+ [![conformance](https://img.shields.io/badge/resvg%20conformance-1715%2F1715-brightgreen)](#conformance)
5
+ [![licence](https://img.shields.io/npm/l/resvg-napi)](#licence)
6
6
 
7
- Generated from the upstream Rust sources, so the TypeScript surface is usvg's
8
- own, names and doc comments included.
7
+ Render an SVG to PNG, and read back what the renderer made of the document — the
8
+ resolved tree, text metrics, paint, geometry. Node.js bindings for
9
+ [resvg](https://github.com/linebender/resvg) 0.48, generated from the upstream
10
+ Rust sources, so the TypeScript surface is usvg's own, names and doc comments
11
+ included.
12
+
13
+ **[Try it in the browser](https://p8nut.github.io/resvg-napi/)** — the same
14
+ bindings compiled to WASI, rendering in the page, nothing to install.
9
15
 
10
16
  ```bash
11
17
  npm install resvg-napi
@@ -20,35 +26,58 @@ doc.renderRaw({ crop: doc.absLayerBoundingBox() }) // RGBA8, trimmed
20
26
  await renderAsync(svg, options, { width: 1200 }) // off the event loop
21
27
  ```
22
28
 
23
- ## What you can read back
29
+ `index.d.ts` is the reference — it is generated, so it cannot drift. What follows
30
+ is the map.
24
31
 
25
- `index.d.ts` is the reference — it is generated, so it cannot drift. This is
26
- the map.
32
+ ## Render SVG to PNG
27
33
 
28
- **Render.** Parse once with `new Resvg(svg, options?, fonts?, images?)`, then
29
- render as often as you like.
34
+ Parse once with `new Resvg(svg, options?, fonts?, images?)`, then render as often
35
+ as you like.
30
36
 
31
37
  | | |
32
38
  |---|---|
33
39
  | `renderPng(params?)` | `Buffer` |
34
40
  | `renderRaw(params?)` | `RawImage`, un-premultiplied RGBA8 |
35
- | `toString(opts?)` | the resolved tree, back as SVG |
41
+ | `toString(opts?)` | the resolved tree, back as SVG — text as paths unless `preserveText` |
36
42
  | `renderPngAsync` · `renderRawAsync` · `toStringAsync` | the same, off the event loop, `AbortSignal`-aware |
37
43
 
38
44
  `params` carries `width` / `height` / `scale`, a `background` colour and a
39
45
  `crop` box. `Resvg.parseAsync` moves the parse off the loop too.
40
46
 
41
- **Walk the tree.** `node(id)` and `children()` hand back `SvgNode`s, and each
42
- one knows what it is:
47
+ ## Text as outlines
48
+
49
+ `toString()` hands back the resolved tree with **the text converted to paths** —
50
+ an SVG that draws the same where the font is not installed, which is what a
51
+ print or PDF pipeline needs from a template:
52
+
53
+ ```js
54
+ const doc = new Resvg(svg, { fontFamily: 'DejaVu Sans' }, fonts)
55
+ doc.toString() // one <path> per glyph, no <text>
56
+ doc.toString({ preserveText: true }) // <text> kept, resolved but not outlined
57
+ ```
58
+
59
+ The outlines come from the same layout `renderPng` draws, so a glyph sits where
60
+ the raster puts it — and `extent()` measured it before either.
61
+
62
+ ## Inspect the usvg tree
63
+
64
+ `node(id)` and `children()` hand back `SvgNode`s, and each one knows what it is:
43
65
 
44
66
  ```js
45
67
  const n = doc.node('surname')
46
68
  n.kind // 'group' | 'path' | 'image' | 'text'
47
69
  n.path() // geometry, fill, stroke — null unless it is a shape
48
- n.text() // chunks, layouted spans, positioned glyphs
70
+ n.text() // chunks, layouted spans, positioned glyphs, decoration
49
71
  n.renderPng() // that element alone, cropped to its own extent
50
72
  ```
51
73
 
74
+ A span carries what it is drawn with, down to the lines through it:
75
+
76
+ ```js
77
+ const span = n.text().chunks[0].spans[0]
78
+ span.decoration.underline?.fill?.paint // …and .overline, .lineThrough
79
+ ```
80
+
52
81
  Paint is a discriminated union, so TypeScript narrows it:
53
82
 
54
83
  ```ts
@@ -57,23 +86,90 @@ if (paint?.type === 'color') paint.value // { red, green, blue }
57
86
  else paint?.id // the gradient or pattern it names
58
87
  ```
59
88
 
60
- **Measure.** Every node reports `boundingBox()`, `absBoundingBox()`,
61
- `strokeBoundingBox()`, `absLayerBoundingBox()` and `extent()` — in the
62
- document's own units, which is not the canvas. See *Fitting text* below for why
89
+ ## Measure text and geometry
90
+
91
+ Every node reports `boundingBox()`, `absBoundingBox()`, `strokeBoundingBox()`,
92
+ `absLayerBoundingBox()` and `extent()` — in the document's own units, which is
93
+ not the canvas. See [Fitting text to a width](#fitting-text-to-a-width) for why
63
94
  that distinction bites.
64
95
 
65
- **Fonts.** `FontDatabase` is `fontdb` itself: `loadSystemFonts()`,
66
- `loadFontData(buffer)`, `loadFontFile(path)`, `faces()`, `query()`, and the
67
- generic-family setters. `pendingFonts()` on a parsed document names the
68
- families it wanted and did not get; `pendingImages()` does the same for hrefs.
96
+ ## Fonts
97
+
98
+ `FontDatabase` is `fontdb` itself: `loadSystemFonts()`, `loadFontData(buffer)`,
99
+ `loadFontFile(path)`, `faces()`, `query()`, and the generic-family setters. A
100
+ face reports its `families`, `weight`, `style` (`'normal' | 'italic' |
101
+ 'oblique'`) and whether it is `monospaced`. `pendingFonts()` on a parsed document
102
+ names the families it wanted and did not get; `pendingImages()` does the same for
103
+ hrefs.
104
+
105
+ `pendingFonts()` names the families nobody had. `faceOf(glyph)` names the face
106
+ that drew the text instead — the substitution a document-wide list cannot show,
107
+ and the one that survives to print:
108
+
109
+ ```js
110
+ const text = doc.node('title').text()
111
+ text.chunks[0].spans[0].font.families // ['Brand Sans', 'DejaVu Sans'] — asked for
112
+ for (const glyph of text.layouted[0].positionedGlyphs) {
113
+ doc.faceOf(glyph)?.postScriptName // 'DejaVuSans' — what actually drew it
114
+ }
115
+ ```
116
+
117
+ `faceOf` returns `null` only for a glyph from another document: the id a glyph
118
+ carries is a key into the font database its own document was parsed with.
119
+
120
+ ## Paint servers
121
+
122
+ `linearGradients()`, `radialGradients()`, `patterns()`, `clipPaths()`, `masks()`,
123
+ `filters()` — the paint servers an element's `id` refers to.
124
+
125
+ ## Examples
126
+
127
+ Four templates in [`demo/examples/`](demo/examples), each rendered by
128
+ `node demo/render.mjs <template.svg>`: Liquid fills the template from the JSON
129
+ file next to it, this binding rasterises the result. The images below are that
130
+ command's output.
131
+
132
+ ### Roster — a table from a JSON array
133
+
134
+ ![roster](https://raw.githubusercontent.com/p8nut/resvg-napi/main/demo/assets/roster.png)
135
+
136
+ A `staff` array becomes rows, with an embedded logo and a QR code generated
137
+ during templating. The fourth name runs straight into the column beside it —
138
+ measuring that overflow, and compressing it away, is what [Fitting text to a
139
+ width](#fitting-text-to-a-width) below is for.
69
140
 
70
- **Definitions.** `linearGradients()`, `radialGradients()`, `patterns()`,
71
- `clipPaths()`, `masks()`, `filters()` — the paint servers an element's `id`
72
- refers to.
141
+ ### Photo card — images and glyphs
73
142
 
74
- Something missing? The generator keeps a report of every upstream member it
75
- left alone, with the reason. `RESVG_NAPI_CODEGEN_LOG=1 cargo build` prints it,
76
- and [CONTRIBUTING.md](CONTRIBUTING.md) explains what the reasons mean.
143
+ ![photo card](https://raw.githubusercontent.com/p8nut/resvg-napi/main/demo/assets/photo-card.png)
144
+
145
+ Everything a card does with raster images and type, and nothing it does with
146
+ data.
147
+
148
+ ### Badge sheet — one template, stamped per record
149
+
150
+ ![badge sheet](https://raw.githubusercontent.com/p8nut/resvg-napi/main/demo/assets/badge-sheet.png)
151
+
152
+ Pulls `badge.svg` in as a partial and repeats it. A guided tour, where every zone
153
+ of the page is one Liquid capability.
154
+
155
+ `sheet.svg` covers the data half — pagination, grouping, theming, and
156
+ `--lang fr` driving `<switch systemLanguage>`, which usvg picks nothing from
157
+ without a language.
158
+
159
+ ## Conformance
160
+
161
+ resvg's own test corpus, rendered through these bindings: **1715 of 1715 match**
162
+ the reference PNGs upstream asserts on, within 1/255 per channel — a tolerance
163
+ measured rather than chosen, with the reason recorded in
164
+ [`scripts/conformance.mjs`](scripts/conformance.mjs).
165
+
166
+ ```bash
167
+ npm run conformance:fetch # the corpus, at the tag Cargo.toml pins
168
+ npm run conformance # 15 seconds including the fetch
169
+ ```
170
+
171
+ CI runs it on every pull request, so a resvg bump that changes a render shows up
172
+ as a diff rather than passing unnoticed.
77
173
 
78
174
  ## Platforms
79
175
 
@@ -112,7 +208,6 @@ generated shims and test run are a different code path. The other eleven build
112
208
  on the merge, on a `v*` tag, on a manual dispatch, or on a pull request labelled
113
209
  `full-matrix` when the proof is wanted before merging rather than after.
114
210
 
115
-
116
211
  ## Fitting text to a width
117
212
 
118
213
  An Illustrator template says how wide a field may be on the element itself
@@ -147,7 +242,7 @@ left untouched, and a constraint that cannot be honoured says why: no `id` to
147
242
  measure by, no visible extent, or an unusable width. It compresses glyphs rather
148
243
  than reducing `font-size` — the choice the templates already made.
149
244
 
150
- ## Diagnostics
245
+ ## Warnings and logs
151
246
 
152
247
  usvg and resvg report every recoverable problem through the `log` crate —
153
248
  unparsable values, skipped shapes, unmatched font families, images that could not
@@ -166,12 +261,50 @@ takeLogs()
166
261
  `takeLogs()` drains the buffer, which is capped at 500 entries so a pathological
167
262
  document cannot grow it without end.
168
263
 
169
- ## Elsewhere
264
+ ## Troubleshooting
265
+
266
+ **A font family did not apply.** `pendingFonts()` on the parsed document names
267
+ the families it asked for and did not get, and `faceOf(glyph)` names the face
268
+ that was used in their place. Supply them with
269
+ `loadFontFile(path)` or `loadFontData(buffer)` before rendering. Under WASI,
270
+ `loadSystemFonts()` finds nothing inside the sandbox, so every face has to be
271
+ loaded by hand.
272
+
273
+ **An image did not appear.** `pendingImages()` names the hrefs that could not be
274
+ resolved.
275
+
276
+ **A measurement disagrees with the numbers in the file.** Bounding boxes are in
277
+ the document's own units and usvg normalises the tree, so they are not canvas
278
+ pixels. See [Fitting text to a width](#fitting-text-to-a-width) for the arithmetic.
279
+
280
+ **Something was dropped and nothing said so.** usvg reports it through the `log`
281
+ crate and nothing consumes that by default — see [Warnings and
282
+ logs](#warnings-and-logs).
283
+
284
+ **A member is missing from the TypeScript surface.** The generator keeps a report
285
+ of every upstream member it left alone, with the reason.
286
+ `RESVG_NAPI_CODEGEN_LOG=1 cargo build` prints it, and
287
+ [CONTRIBUTING.md](CONTRIBUTING.md) explains what the reasons mean.
288
+
289
+ ## Demo
290
+
291
+ A browser proof bench for the same bindings compiled to WASI: Liquid templating,
292
+ an array editor, per-element export, live diagnostics. Deployed from `main` at
293
+ **[p8nut.github.io/resvg-napi](https://p8nut.github.io/resvg-napi/)**, and it
294
+ runs locally too:
295
+
296
+ ```bash
297
+ npm run demo
298
+ ```
299
+
300
+ ![the proof bench](https://raw.githubusercontent.com/p8nut/resvg-napi/main/demo/assets/screenshot.png)
301
+
302
+ [demo/README.md](demo/README.md) describes the page.
303
+
304
+ ## Contributing
170
305
 
171
- - **[demo/](demo/README.md)** — a browser proof bench: Liquid templating, an
172
- array editor, per-element export, live diagnostics. `npm run demo`.
173
- - **[CONTRIBUTING.md](CONTRIBUTING.md)** — how the bindings are generated, and
174
- what to read before touching `build.rs`.
306
+ [CONTRIBUTING.md](CONTRIBUTING.md) — how the bindings are generated, and what to
307
+ read before touching the generator.
175
308
 
176
309
  ## Licence
177
310
 
package/fit.d.mts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Horizontal text fitting, driven by `data-maxwidth`.
3
+ *
4
+ * Declarations for `fit.mjs`, which is JavaScript with JSDoc: written by hand,
5
+ * unlike `index.d.ts`, so they can drift. `npm run typecheck` reads them.
6
+ */
7
+
8
+ /** A `Resvg` instance, however the caller chose to build one. */
9
+ type Renderer = {
10
+ node(id: string): { extent(): { width: number } | null } | null
11
+ }
12
+
13
+ /** One element carrying a width constraint, and what is needed to rewrite it. */
14
+ export interface WidthConstraint {
15
+ /** The element's opening tag, verbatim. */
16
+ tag: string
17
+ /** The tag name: `text`, `tspan`, ... */
18
+ name: string
19
+ /** The attribute text inside that tag, verbatim. */
20
+ attrs: string
21
+ /** The element's `id`, or null when it had none and one must be generated. */
22
+ id: string | null
23
+ /** The limit, in the document's own units -- not canvas pixels. */
24
+ max: number
25
+ /** Byte offset of the tag in the source string. */
26
+ index: number
27
+ }
28
+
29
+ /** One element that was compressed, and by how much. */
30
+ export interface Adjustment {
31
+ id: string
32
+ /** Measured width before, in the document's units. */
33
+ from: number
34
+ /** The limit it was fitted to. */
35
+ to: number
36
+ /** The horizontal scale applied: `to / from`. */
37
+ factor: number
38
+ /** Measured width after, as a check on the one-pass assumption. */
39
+ measured: number
40
+ }
41
+
42
+ export interface FitResult {
43
+ /** The source, with a `scale(k 1)` composed onto each fitted element. */
44
+ svg: string
45
+ adjustments: Adjustment[]
46
+ /** Constraints that could not be honoured, each saying why. */
47
+ problems: string[]
48
+ }
49
+
50
+ /** Elements carrying a width constraint, with the tag text needed to rewrite it. */
51
+ export function findWidthConstraints(svg: string): WidthConstraint[]
52
+
53
+ /**
54
+ * Fits every `data-maxwidth` element by compressing it horizontally.
55
+ *
56
+ * @param svg source, after any templating
57
+ * @param render `(svg) => Resvg`; supply fonts and options here
58
+ */
59
+ export function fitTextWidths(
60
+ svg: string,
61
+ render: (svg: string) => Renderer,
62
+ ): FitResult