@qrcommunication/gigapdf-lib 0.42.0 → 0.44.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,56 @@ 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.44.0] - 2026-06-18
8
+
9
+ ### Added
10
+
11
+ - **Raw Type1 (PFB/PFA) font embedding.** Classic encrypted Type1 programs
12
+ (PDF `FontFile`, PFB, PFA) are parsed (eexec + charstring decryption),
13
+ transcoded to Type2 and embedded through the bare-CFF → OpenType path — the
14
+ last font format that required an external converter (FontForge).
15
+ - **Bundled per-script OCR models + multi-language recognition.** The `.gpocr`
16
+ CRNN models ship under `models/`; `GigaPdfEngine.loadAllBundledOcrModels()`
17
+ (plus `loadBundledOcrModel` / `loadBundledOcrModels` and the `OcrScript` type)
18
+ load them so `doc.ocr` recognizes non-Latin scripts — Cyrillic, Greek, Arabic,
19
+ Urdu, Hebrew (the RTL group), Devanagari, Bengali, Tamil — routed per line by
20
+ the engine's script detector. The wasm still ships no weights.
21
+
22
+ ### Fixed
23
+
24
+ - **Glyph counters are now hollow in `renderPage`.** Each glyph contour was
25
+ filled separately, painting counters (the holes in O, e, a, 0, 8, B…) solid.
26
+ Every contour of a glyph is now accumulated and filled once with the non-zero
27
+ winding rule, so inner contours carve out correctly — fixing blobby,
28
+ low-quality text in the rasterized page (editor background, OCR input).
29
+
30
+ ## [0.43.0] - 2026-06-18
31
+
32
+ ### Added
33
+
34
+ - **Native bare-CFF font embedding.** PDF `FontFile3 /Subtype /Type1C` programs
35
+ (the common compact-font case) are embedded by wrapping the bare CFF into an
36
+ OpenType-CFF (`OTTO`) sfnt with a synthesised `cmap`, so the engine no longer
37
+ needs an external converter (e.g. FontForge) for Type1C faces. The cmap maps
38
+ CFF Standard Strings 1–95 to ASCII and 96–228 to Latin-1 (covering French and
39
+ Western-European accents), plus `uniXXXX` / single-character glyph names.
40
+ - **Glyphless Type0 OCR text layer for any script.** `add_text_layer` now
41
+ carries non-WinAnsi text (Cyrillic, Greek, Arabic, Bengali, Devanagari,
42
+ Tamil…) through an embedded glyphless Type0 font (`CIDFontType2`, empty
43
+ `glyf`, Identity `CIDToGIDMap`, `Identity-H`) with a `/ToUnicode` CMap.
44
+ Drawn in render mode 3 (invisible), the layer makes OCR output searchable and
45
+ copyable regardless of script. WinAnsi runs keep the compact Helvetica path.
46
+ - **SDK `loadOcrModel(model)` / `clearOcrModels()`.** Hosts can load CRNN OCR
47
+ model blobs at runtime (the wasm ships none), enabling multi-script
48
+ recognition (Latin, Cyrillic, Greek, Arabic, Devanagari, Bengali, Tamil).
49
+
50
+ ### Changed
51
+
52
+ - **SDK `load()` / `loadDefault()` are bundler-opaque.** The Node-only built-in
53
+ imports in `loadDefault()` are indirected so bundlers (Turbopack, webpack,
54
+ Vite) no longer try to statically resolve `node:fs/promises` / `node:url` in
55
+ browser builds.
56
+
7
57
  ## [0.42.0] - 2026-06-18
8
58
 
9
59
  ### Changed
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,19 +15,12 @@ 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
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
23
+ ALL_OCR_SCRIPTS: () => ALL_OCR_SCRIPTS,
33
24
  GigaPdfDoc: () => GigaPdfDoc,
34
25
  GigaPdfEngine: () => GigaPdfEngine
35
26
  });
@@ -42,6 +33,20 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
42
33
  // src/index.ts
43
34
  var enc = new TextEncoder();
44
35
  var dec = new TextDecoder();
36
+ var OCR_MODEL_FILES = {
37
+ alpha: "ocr_alpha.gpocr",
38
+ arabic: "ocr_arabic.gpocr",
39
+ devanagari: "ocr_deva.gpocr",
40
+ bengali: "ocr_beng.gpocr",
41
+ tamil: "ocr_taml.gpocr"
42
+ };
43
+ var ALL_OCR_SCRIPTS = [
44
+ "alpha",
45
+ "arabic",
46
+ "devanagari",
47
+ "bengali",
48
+ "tamil"
49
+ ];
45
50
  var GigaPdfEngine = class _GigaPdfEngine {
46
51
  constructor(ex) {
47
52
  this.ex = ex;
@@ -92,8 +97,13 @@ var GigaPdfEngine = class _GigaPdfEngine {
92
97
  * for the consuming route so the `.wasm` is copied into the standalone bundle.
93
98
  */
94
99
  static async loadDefault() {
95
- const { readFile } = await import("fs/promises");
96
- const { fileURLToPath } = await import("url");
100
+ const nodeImport = (m) => import(
101
+ /* webpackIgnore: true */
102
+ /* @vite-ignore */
103
+ m
104
+ );
105
+ const { readFile } = await nodeImport("node:fs/promises");
106
+ const { fileURLToPath } = await nodeImport("node:url");
97
107
  const wasmPath = fileURLToPath(new URL("../gigapdf.wasm", importMetaUrl));
98
108
  return _GigaPdfEngine.load(await readFile(wasmPath));
99
109
  }
@@ -392,6 +402,87 @@ var GigaPdfEngine = class _GigaPdfEngine {
392
402
  const dv = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
393
403
  return { width: dv.getUint32(0, true), height: dv.getUint32(4, true), rgba: framed.subarray(8) };
394
404
  }
405
+ // ── OCR models (host-loaded `.gpocr` blobs — multi-script line recognizer) ─
406
+ /**
407
+ * Load a `.gpocr` line-level OCR model blob into the engine's runtime registry
408
+ * — Latin/Cyrillic/Greek (`alpha`), Arabic (RTL), Devanagari, Bengali, Tamil…
409
+ * The host supplies the bytes (the wasm ships no weights, like fonts), so the
410
+ * module stays lean. Once loaded, {@link GigaPdfDoc.ocr} / {@link GigaPdfDoc.ocrText}
411
+ * route to the CRNN+CTC line recognizer (per-page fallback to the built-in
412
+ * mono-glyph Latin classifier). Models are global to the engine; call after
413
+ * `load`/`loadDefault`. Returns `true` on success, `false` on a malformed blob.
414
+ */
415
+ loadOcrModel(model) {
416
+ return this._withBytes(model, (p, l) => this.ex.gp_ocr_load_model(p, l)) === 1;
417
+ }
418
+ /** Drop every runtime-loaded OCR model (reverts to the mono-glyph classifier). */
419
+ clearOcrModels() {
420
+ this.ex.gp_ocr_clear_models();
421
+ }
422
+ /**
423
+ * Resolve a bundled `.gpocr` model (shipped under `models/`) and load it into
424
+ * the engine via {@link loadOcrModel}. **Node hosts only** — it reads the blob
425
+ * from disk the same way {@link loadDefault} resolves the wasm. Returns `true`
426
+ * on success. Use this to recognize non-Latin scripts (Arabic, Devanagari,
427
+ * Bengali, Tamil) or to upgrade Latin/Cyrillic/Greek to the CRNN (`alpha`).
428
+ */
429
+ async loadBundledOcrModel(script) {
430
+ const nodeImport = (m) => import(
431
+ /* webpackIgnore: true */
432
+ /* @vite-ignore */
433
+ m
434
+ );
435
+ const { readFile } = await nodeImport("node:fs/promises");
436
+ const { fileURLToPath } = await nodeImport("node:url");
437
+ const path = fileURLToPath(
438
+ new URL(`../models/${OCR_MODEL_FILES[script]}`, importMetaUrl)
439
+ );
440
+ return this.loadOcrModel(await readFile(path));
441
+ }
442
+ /**
443
+ * Load several bundled OCR models (idempotent per call). Returns the scripts
444
+ * that loaded successfully. Pass {@link ALL_OCR_SCRIPTS} to recognize text in
445
+ * any supported language; the engine's script detector routes each line to the
446
+ * right model.
447
+ */
448
+ async loadBundledOcrModels(scripts) {
449
+ const loaded = [];
450
+ for (const script of scripts) {
451
+ if (await this.loadBundledOcrModel(script)) loaded.push(script);
452
+ }
453
+ return loaded;
454
+ }
455
+ /**
456
+ * Discover and load EVERY bundled `.gpocr` model (Node hosts only). The
457
+ * engine's script detector then routes each recognized line to the matching
458
+ * model, so the OCR recognizes text in any shipped script — Latin, Cyrillic,
459
+ * Greek, Arabic, Urdu, Hebrew (the RTL group), Devanagari, Bengali, Tamil, and
460
+ * any model added later — with no code change. Returns the number loaded.
461
+ */
462
+ async loadAllBundledOcrModels() {
463
+ const nodeImport = (m) => import(
464
+ /* webpackIgnore: true */
465
+ /* @vite-ignore */
466
+ m
467
+ );
468
+ const { readFile, readdir } = await nodeImport("node:fs/promises");
469
+ const { fileURLToPath } = await nodeImport("node:url");
470
+ let entries;
471
+ try {
472
+ entries = await readdir(fileURLToPath(new URL("../models/", importMetaUrl)));
473
+ } catch {
474
+ return 0;
475
+ }
476
+ let count = 0;
477
+ for (const name of entries) {
478
+ if (!name.endsWith(".gpocr")) continue;
479
+ const bytes = await readFile(
480
+ fileURLToPath(new URL(`../models/${name}`, importMetaUrl))
481
+ );
482
+ if (this.loadOcrModel(bytes)) count += 1;
483
+ }
484
+ return count;
485
+ }
395
486
  // ── fonts (catalog / Google Fonts URL — the host performs the fetch) ───────
396
487
  fontCatalog() {
397
488
  return this._json((o) => this.ex.gp_font_catalog_json(o));
@@ -1556,6 +1647,7 @@ var GigaPdfDoc = class {
1556
1647
  };
1557
1648
  // Annotate the CommonJS export names for ESM import in node:
1558
1649
  0 && (module.exports = {
1650
+ ALL_OCR_SCRIPTS,
1559
1651
  GigaPdfDoc,
1560
1652
  GigaPdfEngine
1561
1653
  });