@qrcommunication/gigapdf-lib 0.41.0 → 0.43.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/CHANGELOG.md CHANGED
@@ -4,6 +4,58 @@ All notable changes to `@qrcommunication/gigapdf-lib` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/) and the
5
5
  project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.43.0] - 2026-06-18
8
+
9
+ ### Added
10
+
11
+ - **Native bare-CFF font embedding.** PDF `FontFile3 /Subtype /Type1C` programs
12
+ (the common compact-font case) are embedded by wrapping the bare CFF into an
13
+ OpenType-CFF (`OTTO`) sfnt with a synthesised `cmap`, so the engine no longer
14
+ needs an external converter (e.g. FontForge) for Type1C faces. The cmap maps
15
+ CFF Standard Strings 1–95 to ASCII and 96–228 to Latin-1 (covering French and
16
+ Western-European accents), plus `uniXXXX` / single-character glyph names.
17
+ - **Glyphless Type0 OCR text layer for any script.** `add_text_layer` now
18
+ carries non-WinAnsi text (Cyrillic, Greek, Arabic, Bengali, Devanagari,
19
+ Tamil…) through an embedded glyphless Type0 font (`CIDFontType2`, empty
20
+ `glyf`, Identity `CIDToGIDMap`, `Identity-H`) with a `/ToUnicode` CMap.
21
+ Drawn in render mode 3 (invisible), the layer makes OCR output searchable and
22
+ copyable regardless of script. WinAnsi runs keep the compact Helvetica path.
23
+ - **SDK `loadOcrModel(model)` / `clearOcrModels()`.** Hosts can load CRNN OCR
24
+ model blobs at runtime (the wasm ships none), enabling multi-script
25
+ recognition (Latin, Cyrillic, Greek, Arabic, Devanagari, Bengali, Tamil).
26
+
27
+ ### Changed
28
+
29
+ - **SDK `load()` / `loadDefault()` are bundler-opaque.** The Node-only built-in
30
+ imports in `loadDefault()` are indirected so bundlers (Turbopack, webpack,
31
+ Vite) no longer try to statically resolve `node:fs/promises` / `node:url` in
32
+ browser builds.
33
+
34
+ ## [0.42.0] - 2026-06-18
35
+
36
+ ### Changed
37
+
38
+ - **Cryptography now uses audited RustCrypto crates** (`rsa`, `sha2`, `aes`,
39
+ `cbc`, `des`, `rc2`, `hmac`, `x509-cert`, `cms`) instead of hand-rolled
40
+ primitives — for PDF signing (RSA/X.509/CMS) and the standard security handler
41
+ (AES/RC4/3DES/RC2). The public ABI and SDK are unchanged.
42
+ - **The HTML→PDF inline-`<script>` engine is now Boa** (`boa_engine`), replacing
43
+ the hand-written interpreter. `js::run_inline_scripts` / `js::eval` keep their
44
+ signatures; Boa is a full ES2021+ engine, so generators, `async`/`await`,
45
+ `RegExp`, `Map`/`Set` and the rest behave per spec. ~14k lines of the former
46
+ engine were removed.
47
+ - The wasm engine stays **`wasm-bindgen`-free**. Entropy (RSA blinding, Boa
48
+ `Math.random`) is drawn through a single host import, **`env.gp_host_random`**,
49
+ which the SDK's `load()` fills from `crypto.getRandomValues`. **Hosts that
50
+ instantiate the `.wasm` directly must now provide this import** (the import
51
+ object was previously empty). Dropping the `wasm_js` getrandom backend also
52
+ removed the transitive `wasm-bindgen`/`js-sys` dependency tree.
53
+
54
+ > Rationale: rolling your own cryptography (timing/oracle side-channels, eIDAS
55
+ > non-conformance) and maintaining a JS engine are liabilities better delegated
56
+ > to audited, wasm-compatible crates. The "no third-party PDF/Office/image
57
+ > library" invariant is unchanged — see `THIRD-PARTY-LICENSES.md`.
58
+
7
59
  ## [0.41.0] - 2026-06-17
8
60
 
9
61
  ### Fixed
package/README.md CHANGED
@@ -99,6 +99,139 @@ if (face) {
99
99
  }
100
100
  ```
101
101
 
102
+ ## Recipes
103
+
104
+ Task-oriented snippets using the high-level classes. Each assumes
105
+ `const giga = await GigaPdfEngine.loadDefault()` (Node) or
106
+ `GigaPdfEngine.load(url)` (browser), `Uint8Array` in/out, and a final `close()`.
107
+
108
+ ### Merge several PDFs
109
+
110
+ ```ts
111
+ const doc = giga.open(first); // the base document
112
+ for (const extra of [second, third]) doc.appendPages(extra); // append every page
113
+ const merged = doc.saveCompressed();
114
+ doc.close();
115
+ ```
116
+
117
+ ### Split — extract a page range into a new PDF
118
+
119
+ ```ts
120
+ const doc = giga.open(pdfBytes);
121
+ const partA = doc.extractPages([1, 2, 3]); // a NEW, self-contained PDF…
122
+ const partB = doc.extractPages([4, 5, 6]); // …links / fields / dests to dropped pages pruned
123
+ doc.close();
124
+ ```
125
+
126
+ ### Encrypt (AES-256) and re-open
127
+
128
+ ```ts
129
+ // `fileId` is the document /ID (any stable string). AES-256 auto-generates the
130
+ // 32-byte key via Web Crypto; pass `opts.keySeed` to supply your own.
131
+ const locked = doc.saveEncrypted("user-pw", "doc-001", {
132
+ ownerPassword: "owner-pw",
133
+ algorithm: "aes256", // "rc4" | "aes128" | "aes256" (default)
134
+ // permissions: -44, // PDF permission bitmask (optional)
135
+ });
136
+ doc.close();
137
+
138
+ const reopened = giga.openEncrypted(locked, "user-pw"); // null on a wrong password
139
+ reopened?.close();
140
+ // Inspect without opening:
141
+ const info = giga.encryptionInfo(locked); // { encrypted, permissions, version, revision }
142
+ ```
143
+
144
+ ### Digital signature
145
+
146
+ ```ts
147
+ // (a) Self-signed — an ephemeral digital ID. `random` ≥ 256 host-entropy bytes.
148
+ // fields = "name\treason\tdate\tnotBefore\tnotAfter" (PDF date strings).
149
+ const fields = "Jane Doe\tApproved\tD:20260618120000Z\t260618000000Z\t360618000000Z";
150
+ const random = crypto.getRandomValues(new Uint8Array(256));
151
+ const signed = doc.sign(fields, random);
152
+
153
+ // (b) PKCS#12 — your CA / eIDAS certificate + RSA key (.p12/.pfx), imported
154
+ // natively. Throws on a wrong password / malformed file.
155
+ const signed2 = doc.signP12(p12Bytes, "p12-password", {
156
+ name: "Jane Doe",
157
+ reason: "I approve this document",
158
+ date: "D:20260618120000Z",
159
+ location: "Paris",
160
+ });
161
+ doc.close();
162
+ ```
163
+
164
+ ### Annotate, then flatten
165
+
166
+ ```ts
167
+ doc.addHighlight(1, 72, 690, 252, 704, 0xffff00);
168
+ doc.addTextNote(1, 300, 700, 0xff0000, { contents: "Check this clause", author: "Reviewer" });
169
+ doc.addSquare(1, 60, 680, 264, 712, 0xff0000, null); // stroke red, no fill
170
+ const all = doc.annotations(1); // read back, with full metadata
171
+ doc.flattenAnnotations(1); // bake into page content (non-interactive)
172
+ const out = doc.save();
173
+ doc.close();
174
+ ```
175
+
176
+ ### HTML + CSS → PDF with auto-fetched Google Fonts
177
+
178
+ ```ts
179
+ import type { HtmlFontRequest, HtmlFont } from "@qrcommunication/gigapdf-lib";
180
+
181
+ // Phase 1: ask the engine which fonts the HTML needs; the HOST fetches them
182
+ // (the wasm has no network). Phase 2: render with those fonts embedded.
183
+ async function fetchFonts(reqs: HtmlFontRequest[]): Promise<HtmlFont[]> {
184
+ return Promise.all(reqs.map(async (r) => {
185
+ const css = await (await fetch(r.url, {
186
+ headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0)" }, // → TTF, not WOFF2
187
+ })).text();
188
+ const ttf = new Uint8Array(await (await fetch(giga.parseCssFontUrl(css))).arrayBuffer());
189
+ return { family: r.family, weight: r.weight, italic: r.italic, ttf };
190
+ }));
191
+ }
192
+
193
+ const html = `<body style="font-family: Roboto"><h1>Invoice</h1><p>Net 30.</p></body>`;
194
+ const fonts = await fetchFonts(giga.htmlNeededFonts(html));
195
+ const pdf = giga.htmlRender(html, fonts, 595, 842, 36); // A4 in points, 36pt margin
196
+ // Named sizes, per-side margins and a header/footer with {{page}}/{{pages}} tokens:
197
+ // giga.htmlRenderWith(html, fonts, { pageSize: "A4", header, footer });
198
+ ```
199
+
200
+ ### Make a scanned PDF searchable (OCR → invisible text layer)
201
+
202
+ ```ts
203
+ const doc = giga.open(scannedPdf);
204
+ const scale = 2; // rasterise at 2× = 144 dpi for OCR
205
+ for (let page = 1; page <= doc.pageCount(); page++) {
206
+ const { height } = doc.pageInfo(page);
207
+ const words = doc.ocr(page, scale); // OcrWord[] in raster pixels (top-left)
208
+ // Map each word box back to PDF user space (bottom-left, Y up) and stamp an
209
+ // invisible (render-mode 3) text layer — selectable & searchable, pixel-aligned.
210
+ doc.addTextLayer(page, words.map((w) => ({
211
+ x: w.x / scale,
212
+ y: height - (w.y + w.h) / scale,
213
+ size: w.h / scale,
214
+ text: w.text,
215
+ })));
216
+ }
217
+ const searchable = doc.save();
218
+ doc.close();
219
+ ```
220
+
221
+ ### Metadata & bookmarks (outline)
222
+
223
+ ```ts
224
+ doc.setMetadata("Title", "Quarterly report");
225
+ doc.setMetadata("Author", "Finance");
226
+ doc.setOutline([
227
+ { title: "Summary", level: 0, page: 1 },
228
+ { title: "Details", level: 0, page: 2 },
229
+ { title: "Appendix", level: 1, page: 5 },
230
+ ]);
231
+ const out = doc.save();
232
+ doc.close();
233
+ ```
234
+
102
235
  ## Next.js (`output: "standalone"`)
103
236
 
104
237
  `loadDefault()` reads `gigapdf.wasm` from the package directory. In standalone
package/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -60,11 +50,28 @@ var GigaPdfEngine = class _GigaPdfEngine {
60
50
  } else {
61
51
  bytes = source;
62
52
  }
53
+ let ex;
63
54
  const { instance } = await WebAssembly.instantiate(
64
55
  bytes instanceof Uint8Array ? bytes.slice().buffer : bytes,
65
- {}
56
+ {
57
+ env: {
58
+ gp_host_random: (ptr, len) => {
59
+ const c = globalThis.crypto;
60
+ if (!c?.getRandomValues) {
61
+ throw new Error(
62
+ "gigapdf: wasm entropy needs Web Crypto (globalThis.crypto.getRandomValues)"
63
+ );
64
+ }
65
+ const mem = new Uint8Array(ex.memory.buffer, ptr, len);
66
+ for (let off = 0; off < len; off += 65536) {
67
+ c.getRandomValues(mem.subarray(off, Math.min(off + 65536, len)));
68
+ }
69
+ }
70
+ }
71
+ }
66
72
  );
67
- return new _GigaPdfEngine(instance.exports);
73
+ ex = instance.exports;
74
+ return new _GigaPdfEngine(ex);
68
75
  }
69
76
  /**
70
77
  * Convenience loader for Node: instantiate from the `gigapdf.wasm` shipped
@@ -75,8 +82,13 @@ var GigaPdfEngine = class _GigaPdfEngine {
75
82
  * for the consuming route so the `.wasm` is copied into the standalone bundle.
76
83
  */
77
84
  static async loadDefault() {
78
- const { readFile } = await import("fs/promises");
79
- const { fileURLToPath } = await import("url");
85
+ const nodeImport = (m) => import(
86
+ /* webpackIgnore: true */
87
+ /* @vite-ignore */
88
+ m
89
+ );
90
+ const { readFile } = await nodeImport("node:fs/promises");
91
+ const { fileURLToPath } = await nodeImport("node:url");
80
92
  const wasmPath = fileURLToPath(new URL("../gigapdf.wasm", importMetaUrl));
81
93
  return _GigaPdfEngine.load(await readFile(wasmPath));
82
94
  }
@@ -375,6 +387,23 @@ var GigaPdfEngine = class _GigaPdfEngine {
375
387
  const dv = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
376
388
  return { width: dv.getUint32(0, true), height: dv.getUint32(4, true), rgba: framed.subarray(8) };
377
389
  }
390
+ // ── OCR models (host-loaded `.gpocr` blobs — multi-script line recognizer) ─
391
+ /**
392
+ * Load a `.gpocr` line-level OCR model blob into the engine's runtime registry
393
+ * — Latin/Cyrillic/Greek (`alpha`), Arabic (RTL), Devanagari, Bengali, Tamil…
394
+ * The host supplies the bytes (the wasm ships no weights, like fonts), so the
395
+ * module stays lean. Once loaded, {@link GigaPdfDoc.ocr} / {@link GigaPdfDoc.ocrText}
396
+ * route to the CRNN+CTC line recognizer (per-page fallback to the built-in
397
+ * mono-glyph Latin classifier). Models are global to the engine; call after
398
+ * `load`/`loadDefault`. Returns `true` on success, `false` on a malformed blob.
399
+ */
400
+ loadOcrModel(model) {
401
+ return this._withBytes(model, (p, l) => this.ex.gp_ocr_load_model(p, l)) === 1;
402
+ }
403
+ /** Drop every runtime-loaded OCR model (reverts to the mono-glyph classifier). */
404
+ clearOcrModels() {
405
+ this.ex.gp_ocr_clear_models();
406
+ }
378
407
  // ── fonts (catalog / Google Fonts URL — the host performs the fetch) ───────
379
408
  fontCatalog() {
380
409
  return this._json((o) => this.ex.gp_font_catalog_json(o));