@qrcommunication/gigapdf-lib 0.72.0 → 0.105.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/dist/index.cjs CHANGED
@@ -22,12 +22,17 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  GigaPdfDoc: () => GigaPdfDoc,
24
24
  GigaPdfEngine: () => GigaPdfEngine,
25
+ PAGE_BOX_KINDS: () => PAGE_BOX_KINDS,
26
+ PAGE_TRANSITION_STYLES: () => PAGE_TRANSITION_STYLES,
25
27
  defaultCrlGet: () => defaultCrlGet,
26
28
  defaultOcspPost: () => defaultOcspPost,
27
29
  defaultTsaPost: () => defaultTsaPost
28
30
  });
29
31
  module.exports = __toCommonJS(index_exports);
30
32
  var import_node_fs = require("./node-fs.js");
33
+ function pdfVersionCode(v) {
34
+ return v === "2.0" ? 1 : 0;
35
+ }
31
36
  var enc = new TextEncoder();
32
37
  var dec = new TextDecoder();
33
38
  var ALL_PERMISSIONS = {
@@ -150,6 +155,24 @@ var GigaPdfEngine = class _GigaPdfEngine {
150
155
  this.ex.gp_free(lenPtr, 4);
151
156
  return s ? JSON.parse(s) : [];
152
157
  }
158
+ /**
159
+ * Like {@link _str} but distinguishes a **null** result (the export returned a
160
+ * null pointer — e.g. an `Option::None`) from a present-but-empty string.
161
+ * Returns `null` only for the null pointer; otherwise the decoded string.
162
+ */
163
+ _strOrNull(call) {
164
+ const lenPtr = this.ex.gp_alloc(4);
165
+ const dataPtr = call(lenPtr);
166
+ if (dataPtr === 0) {
167
+ this.ex.gp_free(lenPtr, 4);
168
+ return null;
169
+ }
170
+ const len = this.dv().getUint32(lenPtr, true);
171
+ const s = dec.decode(this.u8().slice(dataPtr, dataPtr + len));
172
+ this.ex.gp_free(dataPtr, len);
173
+ this.ex.gp_free(lenPtr, 4);
174
+ return s;
175
+ }
153
176
  /**
154
177
  * Decode standard Base64 (RFC 4648) to bytes. Pure-JS table decode, so it
155
178
  * works identically in Node and the browser with no dependency (used to turn
@@ -244,6 +267,23 @@ var GigaPdfEngine = class _GigaPdfEngine {
244
267
  this._free(pwPtr, b.length);
245
268
  return handle === 0 ? null : new GigaPdfDoc(this, handle);
246
269
  }
270
+ /**
271
+ * Open a **public-key (certificate) encrypted** PDF (`/Filter /Adobe.PubSec`,
272
+ * ISO 32000-1 §7.6.5) with a recipient's DER `certificate` + PKCS#1 RSA
273
+ * `privateKey`. `null` if this key is not a recipient. Counterpart of
274
+ * {@link GigaPdfDoc.encryptForRecipients}.
275
+ */
276
+ openWithPrivateKey(pdf, certificate, privateKey) {
277
+ const cP = this._toWasm(certificate);
278
+ const kP = this._toWasm(privateKey);
279
+ const handle = this._withBytes(
280
+ pdf,
281
+ (p, l) => this.ex.gp_open_with_private_key(p, l, cP, certificate.length, kP, privateKey.length)
282
+ );
283
+ this._free(cP, certificate.length);
284
+ this._free(kP, privateKey.length);
285
+ return handle === 0 ? null : new GigaPdfDoc(this, handle);
286
+ }
247
287
  /**
248
288
  * Inspect a PDF's encryption **without decrypting it** (no password needed):
249
289
  * whether it has an `/Encrypt` dictionary, plus its `/P` permission bitmask
@@ -372,19 +412,34 @@ var GigaPdfEngine = class _GigaPdfEngine {
372
412
  );
373
413
  }
374
414
  /**
375
- * Merge several PDFs into one by appending their pages in order. Returns an
376
- * empty document for an empty list, or the single input unchanged for a list
377
- * of one. Each subsequent PDF is appended onto the first via
415
+ * Merge several PDFs into one by appending their pages in order. Each input is
416
+ * either raw bytes (every page) or a {@link MergePart} `{ pdf, pages? }` that
417
+ * selects 1-based page numbers (ISO 32000-1 §7.7.3) — so the two forms can be
418
+ * mixed (e.g. `[whole, { pdf: b, pages: [1, 3] }]`). Returns an empty document
419
+ * for an empty list, or — when the only input is a whole PDF (no `pages`) —
420
+ * that input unchanged. Each subsequent part is appended onto the first via
378
421
  * {@link GigaPdfDoc.appendPages}; the merged bytes are returned and the working
379
422
  * document is closed.
380
423
  */
381
- mergePdfs(pdfs) {
382
- if (pdfs.length === 0) return new Uint8Array(0);
383
- if (pdfs.length === 1) return pdfs[0];
384
- const base = this.open(pdfs[0]);
424
+ mergePdfs(parts) {
425
+ if (parts.length === 0) return new Uint8Array(0);
426
+ const part = (p) => p instanceof Uint8Array ? { pdf: p } : p;
427
+ const first = part(parts[0]);
428
+ if (parts.length === 1 && first.pages === void 0) return first.pdf;
429
+ let seed = first.pdf;
430
+ if (first.pages !== void 0) {
431
+ const head = this.open(first.pdf);
432
+ try {
433
+ seed = head.extractPages(first.pages);
434
+ } finally {
435
+ head.close();
436
+ }
437
+ }
438
+ const base = this.open(seed);
385
439
  try {
386
- for (let i = 1; i < pdfs.length; i++) {
387
- base.appendPages(pdfs[i]);
440
+ for (let i = 1; i < parts.length; i++) {
441
+ const p = part(parts[i]);
442
+ base.appendPages(p.pdf, p.pages);
388
443
  }
389
444
  return base.save();
390
445
  } finally {
@@ -955,7 +1010,48 @@ function frameBlobs(blobs) {
955
1010
  }
956
1011
  return out;
957
1012
  }
1013
+ var AF_RELATIONSHIP_CODE = {
1014
+ source: 0,
1015
+ data: 1,
1016
+ alternative: 2,
1017
+ supplement: 3,
1018
+ unspecified: 4
1019
+ };
1020
+ var PAGE_BOX_KINDS = ["media", "crop", "bleed", "trim", "art"];
1021
+ var PAGE_LABEL_STYLE_TOKEN = {
1022
+ decimal: "D",
1023
+ romanLower: "r",
1024
+ romanUpper: "R",
1025
+ alphaLower: "a",
1026
+ alphaUpper: "A",
1027
+ none: "-"
1028
+ };
1029
+ var PAGE_TRANSITION_STYLES = [
1030
+ "split",
1031
+ "blinds",
1032
+ "box",
1033
+ "wipe",
1034
+ "dissolve",
1035
+ "glitter",
1036
+ "fly",
1037
+ "push",
1038
+ "cover",
1039
+ "uncover",
1040
+ "fade",
1041
+ "replace"
1042
+ ];
958
1043
  var RGB = (rgb) => rgb & 16777215;
1044
+ function cryptoRandom(n) {
1045
+ const c = globalThis.crypto;
1046
+ if (!c?.getRandomValues) {
1047
+ throw new Error(
1048
+ "this operation needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit seed"
1049
+ );
1050
+ }
1051
+ const out = new Uint8Array(n);
1052
+ c.getRandomValues(out);
1053
+ return out;
1054
+ }
959
1055
  function styleArgs(s = {}) {
960
1056
  const hasBorder = s.border === null ? 0 : 1;
961
1057
  const borderRgb = s.border == null ? 0 : s.border;
@@ -993,6 +1089,47 @@ var GigaPdfDoc = class {
993
1089
  saveCompressed() {
994
1090
  return this.g._buffer((o) => this.ex().gp_save_compressed(this.h, o));
995
1091
  }
1092
+ /**
1093
+ * Serialize with PDF 1.5+ **object streams** + a **cross-reference stream**
1094
+ * (ISO 32000-1 §7.5.7 / §7.5.8) — the most compact output. `objectStreams`
1095
+ * (default `true`) packs non-stream objects into compressed `/ObjStm`s (needs
1096
+ * the xref stream); `xrefStreams` (default `true`) writes a `/XRef` stream.
1097
+ * `version` selects the `%PDF-x.y` header banner (default `"1.7"`).
1098
+ * Uncompressed streams are Flate-compressed first, like {@link saveCompressed}.
1099
+ * Linearization (Fast Web View) is not performed.
1100
+ */
1101
+ saveOptimized(opts = {}) {
1102
+ const obj = opts.objectStreams ?? true;
1103
+ const xref = opts.xrefStreams ?? true;
1104
+ const ver = pdfVersionCode(opts.version);
1105
+ return this.g._buffer(
1106
+ (o) => this.ex().gp_save_optimized(this.h, obj ? 1 : 0, xref ? 1 : 0, ver, o)
1107
+ );
1108
+ }
1109
+ /**
1110
+ * Serialize as a **linearized** ("Fast Web View") PDF (ISO 32000-1 Annex F).
1111
+ *
1112
+ * The first page and only the objects needed to render it — together with a
1113
+ * `/Linearized` parameter dictionary and a primary hint stream — are written at
1114
+ * the **front** of the file, so a web viewer can display page 1 before the rest
1115
+ * of the document has downloaded (progressive rendering / byte-range serving).
1116
+ * The remaining pages follow, then a main cross-reference table; the first-page
1117
+ * cross-reference section chains to it via `/Prev`. Streams are Flate-compressed
1118
+ * first (like {@link saveCompressed}) and embedded fonts are subset.
1119
+ *
1120
+ * Falls back to the plain {@link save} output if the document cannot be
1121
+ * linearized (no catalog / page tree / zero pages). `version` selects the
1122
+ * `%PDF-x.y` header banner (default `"1.7"`).
1123
+ */
1124
+ toLinearized(version = "1.7") {
1125
+ return this.g._buffer(
1126
+ (o) => this.ex().gp_to_linearized(this.h, pdfVersionCode(version), o)
1127
+ );
1128
+ }
1129
+ /** Alias of {@link toLinearized} — serialize as a linearized (Fast Web View) PDF. */
1130
+ saveLinearized(version = "1.7") {
1131
+ return this.toLinearized(version);
1132
+ }
996
1133
  // text intelligence
997
1134
  textRuns(page) {
998
1135
  return this.g._json((o) => this.ex().gp_text_runs_json(this.h, page, o));
@@ -1239,6 +1376,212 @@ var GigaPdfDoc = class {
1239
1376
  opacity
1240
1377
  ) === 0;
1241
1378
  }
1379
+ /**
1380
+ * Paint a **linear** or **radial** gradient over `rect` on `page` (ISO 32000-1
1381
+ * §8.7.4 shading + §8.7.3 pattern). `coords` is `[x0,y0,x1,y1]` for `"linear"`
1382
+ * or `[x0,y0,r0,x1,y1,r1]` for `"radial"`; `stops` is ≥ 2 colour stops
1383
+ * (`offset` 0…1, `rgb` packed `0xRRGGBB`). `extend` (default `[true,true]`)
1384
+ * sets `/Extend`; `opacity` (default `1`) is the fill alpha.
1385
+ *
1386
+ * @example
1387
+ * doc.addGradient(1, {
1388
+ * kind: "linear", coords: [50, 50, 250, 50],
1389
+ * stops: [{ offset: 0, rgb: 0xff0000 }, { offset: 1, rgb: 0x0000ff }],
1390
+ * rect: { x: 50, y: 40, w: 200, h: 60 },
1391
+ * });
1392
+ */
1393
+ addGradient(page, spec) {
1394
+ const kind = spec.kind === "radial" ? 1 : 0;
1395
+ const offsets = spec.stops.map((s) => s.offset);
1396
+ const colors = spec.stops.map((s) => RGB(s.rgb));
1397
+ const [es, ee] = spec.extend ?? [true, true];
1398
+ const opacity = spec.opacity ?? 1;
1399
+ const r = spec.rect;
1400
+ return this.g._withF64(
1401
+ spec.coords,
1402
+ (cp, cc) => this.g._withF64(
1403
+ offsets,
1404
+ (op, _oc) => this.g._withU32(
1405
+ colors,
1406
+ (clp, _clc) => this.ex().gp_add_gradient(
1407
+ this.h,
1408
+ page,
1409
+ kind,
1410
+ cp,
1411
+ cc,
1412
+ op,
1413
+ clp,
1414
+ offsets.length,
1415
+ r.x,
1416
+ r.y,
1417
+ r.w,
1418
+ r.h,
1419
+ es ? 1 : 0,
1420
+ ee ? 1 : 0,
1421
+ opacity
1422
+ )
1423
+ )
1424
+ )
1425
+ ) === 0;
1426
+ }
1427
+ /**
1428
+ * Encode a {@link Color} into the ABI's `(kind, comps, name, profile)` buffers
1429
+ * and invoke `fn` with the resulting pointers. Internal.
1430
+ */
1431
+ _color(color, fn) {
1432
+ let kind;
1433
+ let comps;
1434
+ let name = "";
1435
+ let profile = null;
1436
+ switch (color.space) {
1437
+ case "cmyk":
1438
+ kind = 1;
1439
+ comps = [color.c, color.m, color.y, color.k];
1440
+ break;
1441
+ case "gray":
1442
+ kind = 2;
1443
+ comps = [color.gray];
1444
+ break;
1445
+ case "separation":
1446
+ kind = 3;
1447
+ comps = [color.tint, ...color.cmyk];
1448
+ name = color.name;
1449
+ break;
1450
+ case "icc":
1451
+ kind = 4;
1452
+ comps = color.components;
1453
+ profile = color.profile;
1454
+ break;
1455
+ default: {
1456
+ const c = RGB(color.rgb);
1457
+ kind = 0;
1458
+ comps = [(c >> 16 & 255) / 255, (c >> 8 & 255) / 255, (c & 255) / 255];
1459
+ }
1460
+ }
1461
+ return this.g._withF64(
1462
+ comps,
1463
+ (cp, cc) => this.g._withOptStr(
1464
+ name,
1465
+ (np, nl) => profile ? this.g._withBytes(profile, (pp, pl) => fn(kind, cp, cc, np, nl, pp, pl)) : fn(kind, cp, cc, np, nl, 0, 0)
1466
+ )
1467
+ );
1468
+ }
1469
+ /**
1470
+ * Fill a rectangle with `color` in **any** colour space — the press-ready
1471
+ * counterpart of {@link addRectangle} (CMYK, spot `Separation`, gray, ICC).
1472
+ *
1473
+ * @example
1474
+ * doc.addFilledRectangle(1, { x: 40, y: 700, w: 200, h: 40 },
1475
+ * { space: "cmyk", c: 0.1, m: 0.8, y: 0.9, k: 0 });
1476
+ */
1477
+ addFilledRectangle(page, rect, color, opacity = 1) {
1478
+ return this._color(
1479
+ color,
1480
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_filled_rectangle(
1481
+ this.h,
1482
+ page,
1483
+ rect.x,
1484
+ rect.y,
1485
+ rect.w,
1486
+ rect.h,
1487
+ kind,
1488
+ cp,
1489
+ cc,
1490
+ np,
1491
+ nl,
1492
+ pp,
1493
+ pl,
1494
+ opacity
1495
+ )
1496
+ ) === 0;
1497
+ }
1498
+ /**
1499
+ * Fill a polygon through flat `[x0,y0,x1,y1,…]` `points` (≥ 3 vertices) with
1500
+ * `color` in any colour space. The path is closed automatically.
1501
+ */
1502
+ addFilledPolygon(page, points, color, opacity = 1) {
1503
+ return this.g._withF64(
1504
+ points,
1505
+ (ptsPtr, ptsCount) => this._color(
1506
+ color,
1507
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_filled_polygon(
1508
+ this.h,
1509
+ page,
1510
+ ptsPtr,
1511
+ ptsCount,
1512
+ kind,
1513
+ cp,
1514
+ cc,
1515
+ np,
1516
+ nl,
1517
+ pp,
1518
+ pl,
1519
+ opacity
1520
+ )
1521
+ )
1522
+ ) === 0;
1523
+ }
1524
+ /**
1525
+ * Draw a base-14 text run in **any** colour space — the press-ready
1526
+ * counterpart of {@link addTextStandard}. `font` is a base-14 family
1527
+ * (`Helvetica`, `Times-Roman`, `Courier`, …).
1528
+ */
1529
+ addTextColor(page, x, y, size, text, font, color, opts = {}) {
1530
+ const { opacity = 1, rotation = 0, underline = false, strikethrough = false } = opts;
1531
+ return this.g._withStr(
1532
+ text,
1533
+ (tp, tl) => this.g._withStr(
1534
+ font,
1535
+ (fp, fl) => this._color(
1536
+ color,
1537
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_text_color(
1538
+ this.h,
1539
+ page,
1540
+ x,
1541
+ y,
1542
+ size,
1543
+ tp,
1544
+ tl,
1545
+ fp,
1546
+ fl,
1547
+ kind,
1548
+ cp,
1549
+ cc,
1550
+ np,
1551
+ nl,
1552
+ pp,
1553
+ pl,
1554
+ opacity,
1555
+ rotation,
1556
+ underline ? 1 : 0,
1557
+ strikethrough ? 1 : 0
1558
+ )
1559
+ )
1560
+ )
1561
+ ) === 0;
1562
+ }
1563
+ /**
1564
+ * Turn **overprint** on/off for content drawn **after** this call (`/op` fill,
1565
+ * `/OP` stroke, `/OPM` mode — `0` independent colorants, `1` non-erasing).
1566
+ * Essential for prepress black-overprint / trapping.
1567
+ */
1568
+ setOverprint(page, fill, stroke, mode = 1) {
1569
+ return this.ex().gp_set_overprint(this.h, page, fill ? 1 : 0, stroke ? 1 : 0, mode) === 0;
1570
+ }
1571
+ /**
1572
+ * Add a document-level **OutputIntent** embedding the ICC `profile` (its `/N`
1573
+ * is read from the profile), with `condition` as the output-condition
1574
+ * identifier (e.g. `"Coated FOGRA39"`). Decoupled from the PDF/A path.
1575
+ */
1576
+ addOutputIntent(profile, condition) {
1577
+ return this.g._withBytes(
1578
+ profile,
1579
+ (pp, pl) => this.g._withStr(
1580
+ condition,
1581
+ (cp, cl) => this.ex().gp_add_output_intent(this.h, pp, pl, cp, cl)
1582
+ )
1583
+ ) === 0;
1584
+ }
1242
1585
  /**
1243
1586
  * Draw a polyline/polygon through flat `[x0,y0,x1,y1,…]` points. `close` joins
1244
1587
  * the last vertex back to the first. `0xRRGGBB` colours, or `null` to omit.
@@ -1295,6 +1638,27 @@ var GigaPdfDoc = class {
1295
1638
  (p, l) => this.ex().gp_add_image(this.h, page, p, l, x, y, w, h, opacity)
1296
1639
  ) === 0;
1297
1640
  }
1641
+ /**
1642
+ * Replace the pixels of an **existing image XObject in place** — swap a logo or
1643
+ * photo while every reference to it stays intact (ISO 32000-1 §8.9). `index` is
1644
+ * the **unified element index** of an image on `page`, exactly the `index`
1645
+ * reported by {@link imageElements} (and accepted by {@link removeElement} /
1646
+ * {@link transformElement}); `data` is a fresh PNG or JPEG.
1647
+ *
1648
+ * Unlike a delete-then-re-add, the image keeps its object number, **every `/Do`
1649
+ * placement, and its position / scale / rotation / clip matrix** — only the
1650
+ * stream bytes and the image dictionary (`/Width`, `/Height`, `/ColorSpace`,
1651
+ * `/BitsPerComponent`, `/Filter`) are rewritten. The new raster is re-encoded
1652
+ * through the same path as {@link addImage} (PNG alpha → a fresh `/SMask`; JPEG
1653
+ * → `/DCTDecode` passthrough). It need not match the old pixel size — it is
1654
+ * drawn into the same box (transform the element first to re-fit it).
1655
+ *
1656
+ * Returns `false` if `page`/`index` doesn't resolve to a top-level image, or the
1657
+ * bytes aren't a decodable PNG/JPEG.
1658
+ */
1659
+ replaceImage(page, index, data) {
1660
+ return this.g._withBytes(data, (p, l) => this.ex().gp_replace_image(this.h, page, index, p, l)) === 0;
1661
+ }
1298
1662
  /**
1299
1663
  * Stamp an **image watermark** across pages from raw image bytes. Accepts the
1300
1664
  * same five formats the engine decodes — **PNG, JPEG, WebP, GIF, AVIF**. The
@@ -1391,8 +1755,25 @@ var GigaPdfDoc = class {
1391
1755
  movePage(from, to) {
1392
1756
  return this.ex().gp_move_page(this.h, from, to) === 0;
1393
1757
  }
1394
- appendPages(otherPdf) {
1395
- return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;
1758
+ /**
1759
+ * Append pages of another PDF onto this document. With no `pages`, every page
1760
+ * is appended (powers *merge*). With `pages` — 1-based page numbers, in the
1761
+ * order given — only that selection is brought in (ISO 32000-1 §7.7.3), each
1762
+ * page keeping its content, resources, annotations and box geometry. Numbers
1763
+ * out of range are skipped; an empty/all-out-of-range selection returns
1764
+ * `false`.
1765
+ */
1766
+ appendPages(otherPdf, pages) {
1767
+ if (pages === void 0) {
1768
+ return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;
1769
+ }
1770
+ return this.g._withBytes(
1771
+ otherPdf,
1772
+ (bp, bl) => this.g._withU32(
1773
+ pages,
1774
+ (pp, pc) => this.ex().gp_append_pages_subset(this.h, bp, bl, pp, pc)
1775
+ )
1776
+ ) === 0;
1396
1777
  }
1397
1778
  /**
1398
1779
  * Add an invisible (text render mode 3) standard-Helvetica text layer to
@@ -1435,10 +1816,71 @@ var GigaPdfDoc = class {
1435
1816
  (p, c) => this.g._buffer((o) => this.ex().gp_extract_pages(this.h, p, c, o))
1436
1817
  );
1437
1818
  }
1438
- /** Resize a page's MediaBox to `width`×`height` points. */
1819
+ /**
1820
+ * Resize a page's `/MediaBox` to `width`×`height` points — **box geometry
1821
+ * only**. The drawn content keeps its own coordinates (it is *not* rescaled to
1822
+ * the new box, so it may clip or float). To scale the page content along with
1823
+ * the box (keeping annotations aligned) use {@link scalePageContent} or
1824
+ * {@link scalePageTo}; for large-format authoring see {@link setUserUnit}.
1825
+ */
1439
1826
  resizePage(page, width, height) {
1440
1827
  return this.ex().gp_resize_page(this.h, page, width, height) === 0;
1441
1828
  }
1829
+ /**
1830
+ * Scale a page's **content** uniformly by `factor` about the page origin (ISO
1831
+ * 32000-1 §8.3.4) — a true zoom of the whole page, not just the box. Three
1832
+ * things move together: (1) the content stream is wrapped in
1833
+ * `q <factor 0 0 factor 0 0> cm … Q`; (2) `/MediaBox` and `/CropBox` (resolved
1834
+ * through inheritance) plus any locally declared `/BleedBox`/`/TrimBox`/
1835
+ * `/ArtBox` are scaled about the origin; (3) every annotation `/Rect` is scaled,
1836
+ * so widget/stamp appearances — mapped from their `/BBox` into the `/Rect` per
1837
+ * §12.5.5 — rescale to stay aligned automatically. `factor` must be finite and
1838
+ * positive. `false` on engine error (bad page number / non-positive factor).
1839
+ */
1840
+ scalePageContent(page, factor) {
1841
+ return this.ex().gp_scale_page_content(this.h, page, factor) === 0;
1842
+ }
1843
+ /**
1844
+ * Anisotropic {@link scalePageContent}: scale a page's content by `sx`
1845
+ * horizontally and `sy` vertically about the origin, scaling the boxes and
1846
+ * annotation `/Rect`s by the same factors. Both must be finite and positive.
1847
+ * `false` on engine error.
1848
+ */
1849
+ scalePageContentXY(page, sx, sy) {
1850
+ return this.ex().gp_scale_page_content_xy(this.h, page, sx, sy) === 0;
1851
+ }
1852
+ /**
1853
+ * Scale a page's content to **fit within** `width`×`height` points (shrink- or
1854
+ * grow-to-fit), preserving aspect ratio — equivalent to {@link scalePageContent}
1855
+ * with `min(width / currentWidth, height / currentHeight)` over the page's
1856
+ * displayed size (`/MediaBox` with `/Rotate` applied). Returns the uniform
1857
+ * factor applied, or `null` on engine error (bad page number, non-positive
1858
+ * target, or zero-area page).
1859
+ */
1860
+ scalePageTo(page, width, height) {
1861
+ const factor = this.ex().gp_scale_page_to(this.h, page, width, height);
1862
+ return factor < 0 ? null : factor;
1863
+ }
1864
+ /**
1865
+ * Set a page's `/UserUnit` (ISO 32000-1 §14.11.2) for **large-format
1866
+ * authoring**: one default user-space unit becomes `unit`⁄72 inch, so the same
1867
+ * coordinates render larger (e.g. `2.0` doubles the physical size, lifting the
1868
+ * ~200-inch coordinate ceiling). `1.0` is the default and removes the key. This
1869
+ * is distinct from {@link scalePageContent}: it rescales the coordinate system
1870
+ * (a viewer-level zoom of the medium), not the content or boxes. `unit` must be
1871
+ * finite and positive. `false` on engine error.
1872
+ */
1873
+ setUserUnit(page, unit) {
1874
+ return this.ex().gp_set_user_unit(this.h, page, unit) === 0;
1875
+ }
1876
+ /**
1877
+ * A page's `/UserUnit` (ISO 32000-1 §14.11.2), defaulting to `1.0` when absent.
1878
+ * Returns `null` on engine error (bad page number).
1879
+ */
1880
+ pageUserUnit(page) {
1881
+ const unit = this.ex().gp_page_user_unit(this.h, page);
1882
+ return unit < 0 ? null : unit;
1883
+ }
1442
1884
  /** Insert a blank page after the 1-based `after` page (0 = front); returns its id. */
1443
1885
  addPage(width, height, after = 0) {
1444
1886
  return this.ex().gp_add_page(this.h, width, height, after);
@@ -1447,6 +1889,56 @@ var GigaPdfDoc = class {
1447
1889
  copyPage(page) {
1448
1890
  return this.ex().gp_copy_page(this.h, page);
1449
1891
  }
1892
+ /**
1893
+ * N-up imposition (ISO 32000-1 §8.10): draw the **content** of the 1-based
1894
+ * `source` page, scaled and translated, onto the 1-based `target` page — the
1895
+ * basis for 2-up/4-up, booklets, contact sheets and page-on-page stamping. The
1896
+ * source page becomes a Form XObject (its content + `/Resources`, so its fonts
1897
+ * and images come along) and is drawn with `q <cm> /Fmn Do Q` appended to the
1898
+ * target. `(x, y)` is where the visible page's lower-left corner lands and
1899
+ * `(scaleX, scaleY)` scale the page **as displayed** (its `/MediaBox` origin
1900
+ * and `/Rotate` are absorbed into the matrix). Wrapped in `q`/`Q`, so it never
1901
+ * disturbs existing target content and is **composable** — call it repeatedly
1902
+ * (different sources and/or cells) to build an N-up sheet. `source` and
1903
+ * `target` may be the same page. `false` on engine error (bad page number).
1904
+ */
1905
+ placePage(target, source, x, y, scaleX, scaleY) {
1906
+ return this.ex().gp_place_page(this.h, target, source, x, y, scaleX, scaleY) === 0;
1907
+ }
1908
+ /**
1909
+ * Place `source` onto `target` (both 1-based) using an explicit content-stream
1910
+ * matrix `[a, b, c, d, e, f]` — the low-level primitive behind
1911
+ * {@link placePage} for full control of the affine (shear, arbitrary rotation,
1912
+ * reflection). The matrix maps the source page's form space (its user space,
1913
+ * including the `/MediaBox` origin) to the target; unlike {@link placePage} no
1914
+ * origin/rotation normalisation is applied, so identity draws the source 1:1
1915
+ * at the target origin. `false` on engine error.
1916
+ */
1917
+ placePageMatrix(target, source, matrix) {
1918
+ const [a, b, c, d, e, f] = matrix;
1919
+ return this.ex().gp_place_page_matrix(this.h, target, source, a, b, c, d, e, f) === 0;
1920
+ }
1921
+ /**
1922
+ * Impose **all** existing pages `cols × rows` per sheet onto freshly added
1923
+ * sheets (2-up, 4-up, booklet thumbnails, contact sheets). Pages go
1924
+ * left-to-right, top-to-bottom; each is scaled uniformly to fit its cell
1925
+ * (aspect preserved) and centred. The new sheets are appended after the last
1926
+ * original page and the **originals are removed**, leaving only the imposed
1927
+ * sheets. Returns the number of sheets produced (negative on error: `cols`/
1928
+ * `rows` 0, or an empty document). `sheetWidth`/`sheetHeight` default to A4
1929
+ * portrait; `margin`/`gutter` to 14 pt.
1930
+ */
1931
+ nUp(cols, rows, opts = {}) {
1932
+ return this.ex().gp_n_up(
1933
+ this.h,
1934
+ cols,
1935
+ rows,
1936
+ opts.sheetWidth ?? 595.28,
1937
+ opts.sheetHeight ?? 841.89,
1938
+ opts.margin ?? 14,
1939
+ opts.gutter ?? 14
1940
+ );
1941
+ }
1450
1942
  /** A page's size (points) and `/Rotate` (0/90/180/270). */
1451
1943
  pageInfo(page) {
1452
1944
  return this.g._json((o) => this.ex().gp_page_info_json(this.h, page, o));
@@ -1466,6 +1958,154 @@ var GigaPdfDoc = class {
1466
1958
  setPageMargins(page, m) {
1467
1959
  return this.ex().gp_set_page_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;
1468
1960
  }
1961
+ /**
1962
+ * Store an **opaque** JSON string as the document's GigaPDF editor-metadata
1963
+ * sidecar — private editor state that travels with the PDF (catalog
1964
+ * `/GigaPDF /EditorMeta`, a FlateDecode-compressed stream). It is ignored by
1965
+ * every standard PDF reader and the round-trip survives save/open. Pass a JSON
1966
+ * **object** if you also use {@link setEditorMargins} (which read-modify-writes
1967
+ * that object's `margins` key). Returns `true` on success.
1968
+ */
1969
+ setEditorMeta(json) {
1970
+ return this.g._withStr(json, (p, l) => this.ex().gp_set_editor_meta(this.h, p, l)) === 0;
1971
+ }
1972
+ /**
1973
+ * The document's GigaPDF editor-metadata sidecar string (set by
1974
+ * {@link setEditorMeta}), or `null` when the document carries none.
1975
+ */
1976
+ editorMeta() {
1977
+ return this.g._strOrNull((o) => this.ex().gp_editor_meta(this.h, o));
1978
+ }
1979
+ /**
1980
+ * Record the editor's per-page **display** margins (points) in the
1981
+ * editor-metadata sidecar (under `margins`, keyed by page) **without touching
1982
+ * `/CropBox` or `/MediaBox`** — distinct from {@link setPageMargins}, which
1983
+ * performs a real visible recrop. Any other host keys in the sidecar are
1984
+ * preserved. Returns `true` on success.
1985
+ */
1986
+ setEditorMargins(page, m) {
1987
+ return this.ex().gp_set_editor_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;
1988
+ }
1989
+ /**
1990
+ * The editor's per-page display margins (points) recorded for `page` by
1991
+ * {@link setEditorMargins}, or `null` when none were stored. Reads only the
1992
+ * sidecar — never `/CropBox`.
1993
+ */
1994
+ editorMargins(page) {
1995
+ return this.g._jsonOrNull((o) => this.ex().gp_editor_margins(this.h, page, o));
1996
+ }
1997
+ /**
1998
+ * All five page boundary boxes (`media`/`crop`/`bleed`/`trim`/`art`) for the
1999
+ * 1-based `page`, each as `[x0, y0, x1, y1]` in points, with ISO 32000-1
2000
+ * inheritance and defaults applied. See {@link PageBoxes} for the exact
2001
+ * default chain and the `declared` flags.
2002
+ */
2003
+ getPageBoxes(page) {
2004
+ return this.g._json((o) => this.ex().gp_page_boxes_json(this.h, page, o));
2005
+ }
2006
+ /**
2007
+ * Set one of a page's boundary boxes. `kind` is one of {@link PAGE_BOX_KINDS}
2008
+ * and `box` is given as `{ x, y, w, h }` (origin + size, points); it is written
2009
+ * as `[x, y, x+w, y+h]`, normalised so reversed sizes are accepted. Sibling
2010
+ * boxes are preserved. Returns `true` on success, `false` for an unknown kind,
2011
+ * a degenerate box (zero/negative area), or a bad page number.
2012
+ *
2013
+ * Setting `"trim"`/`"bleed"` is the prerequisite for PDF/X and commercial-print
2014
+ * (imposition, bleed, finished-size) pipelines.
2015
+ */
2016
+ setPageBox(page, kind, box) {
2017
+ const k = PAGE_BOX_KINDS.indexOf(kind);
2018
+ if (k < 0) return false;
2019
+ return this.ex().gp_set_page_box(this.h, page, k, box.x, box.y, box.x + box.w, box.y + box.h) === 0;
2020
+ }
2021
+ /**
2022
+ * The document's page-label ranges (`/PageLabels`, ISO 32000-1 §12.4.2), sorted
2023
+ * by `startPage` (1-based). Empty when the document declares no page labels.
2024
+ */
2025
+ getPageLabels() {
2026
+ return this.g._json((o) => this.ex().gp_page_labels_json(this.h, o));
2027
+ }
2028
+ /**
2029
+ * Replace the document's page labels. Pass an **empty** array to remove all
2030
+ * labels. Ranges are sorted by `startPage` and collapsed to one entry per page
2031
+ * (last wins). Returns `true` on success.
2032
+ *
2033
+ * @example
2034
+ * // Front matter in lowercase roman, body in decimal, appendix "A-1, A-2…".
2035
+ * doc.setPageLabels([
2036
+ * { startPage: 1, style: "romanLower", prefix: "", startNumber: 1 },
2037
+ * { startPage: 5, style: "decimal", prefix: "", startNumber: 1 },
2038
+ * { startPage: 20, style: "decimal", prefix: "A-", startNumber: 1 },
2039
+ * ]);
2040
+ */
2041
+ setPageLabels(ranges) {
2042
+ const text = ranges.map(
2043
+ (r) => `${r.startPage} ${PAGE_LABEL_STYLE_TOKEN[r.style] ?? "-"} ${r.startNumber ?? 1} ${r.prefix ?? ""}`
2044
+ ).join("\n");
2045
+ return this.g._withOptStr(text, (p, l) => this.ex().gp_set_page_labels(this.h, p, l)) === 0;
2046
+ }
2047
+ /**
2048
+ * The viewer-visible label string for the 1-based `page` (e.g. `"iv"`, `"A-3"`),
2049
+ * resolving the applicable `/PageLabels` range; the decimal page number when no
2050
+ * range applies (including a document with no page labels).
2051
+ */
2052
+ pageLabel(page) {
2053
+ return this.g._str((o) => this.ex().gp_page_label(this.h, page, o));
2054
+ }
2055
+ /**
2056
+ * Author a presentation transition + auto-advance on `page` (1-based),
2057
+ * ISO 32000-1 §12.4.4. Writes the page's `/Trans` dictionary from
2058
+ * {@link PageTransition.style} plus only the optional sub-keys that apply to
2059
+ * that style (`dimension`/`motion` for `split`, `direction`/`scale`/
2060
+ * `flyAreaOpaque` for `fly`, …) — inapplicable fields are dropped.
2061
+ * {@link PageTransition.displayDuration} becomes the page's `/Dur`
2062
+ * (auto-advance); omitting it removes any existing `/Dur`. Re-calling replaces
2063
+ * the prior transition in full (idempotent). Returns `true` on success,
2064
+ * `false` for an unknown style, a negative/non-finite `duration`/`scale`/
2065
+ * `displayDuration`, or a bad page number.
2066
+ *
2067
+ * @example
2068
+ * // Kiosk slideshow: every page wipes in over 0.5 s, auto-advancing after 5 s.
2069
+ * for (let p = 1; p <= doc.pageCount(); p++) {
2070
+ * doc.setPageTransition(p, { style: "wipe", duration: 0.5, displayDuration: 5 });
2071
+ * }
2072
+ */
2073
+ setPageTransition(page, trans) {
2074
+ const style = PAGE_TRANSITION_STYLES.indexOf(trans.style);
2075
+ if (style < 0) return false;
2076
+ const dimension = trans.dimension === "horizontal" ? 0 : trans.dimension === "vertical" ? 1 : -1;
2077
+ const motion = trans.motion === "inward" ? 0 : trans.motion === "outward" ? 1 : -1;
2078
+ const direction = trans.direction === void 0 ? -2 : trans.direction === "none" ? -1 : trans.direction;
2079
+ const flyB = trans.flyAreaOpaque === void 0 ? -1 : trans.flyAreaOpaque ? 1 : 0;
2080
+ return this.ex().gp_set_page_transition(
2081
+ this.h,
2082
+ page,
2083
+ style,
2084
+ trans.duration ?? Number.NaN,
2085
+ dimension,
2086
+ motion,
2087
+ direction,
2088
+ trans.scale ?? Number.NaN,
2089
+ flyB,
2090
+ trans.displayDuration ?? Number.NaN
2091
+ ) === 0;
2092
+ }
2093
+ /**
2094
+ * The presentation transition declared on `page` (1-based), or `null` when the
2095
+ * page has no `/Trans` (ISO 32000-1 §12.4.4). Optional fields that do not apply
2096
+ * to the recovered style are omitted from the result.
2097
+ */
2098
+ getPageTransition(page) {
2099
+ return this.g._jsonOrNull((o) => this.ex().gp_page_transition_json(this.h, page, o));
2100
+ }
2101
+ /**
2102
+ * Remove any presentation transition from `page` (1-based) — drops the page's
2103
+ * `/Trans` dictionary and its `/Dur` auto-advance entry. A no-op if neither is
2104
+ * present. Returns `true` on success.
2105
+ */
2106
+ clearPageTransition(page) {
2107
+ return this.ex().gp_clear_page_transition(this.h, page) === 0;
2108
+ }
1469
2109
  /**
1470
2110
  * Bake a running header onto every in-range page (idempotent: re-baking
1471
2111
  * replaces the prior header). Returns `true` on success.
@@ -1500,6 +2140,78 @@ var GigaPdfDoc = class {
1500
2140
  (o) => this.ex().gp_header_footer(this.h, o)
1501
2141
  );
1502
2142
  }
2143
+ /**
2144
+ * Bake a **rich**, Word-like running header/footer from a {@link RunningHeaderFooter}
2145
+ * `def` (the source of truth — stored in the editor-meta sidecar, its visible
2146
+ * `/GPHF` band regenerated on every page). Text is set in an embedded font
2147
+ * (each item's `fontRef`, else the bundled OFL face — never base-14) and images
2148
+ * via the same path as {@link addImage}; both live inside the `/GPHF` span, so
2149
+ * they are excluded from {@link elements}/{@link textRuns} and masked by
2150
+ * {@link renderPageExcludingMarkedContent}. Idempotent (re-baking replaces the
2151
+ * prior band).
2152
+ *
2153
+ * `opts.date` is the bake date for `{{date}}` (the engine is clockless — pass
2154
+ * e.g. `new Date().toISOString().slice(0, 10)`); omit to fall back to the
2155
+ * document's `/Info` date. `opts.images` supplies the pixels each
2156
+ * `HFItem` of `type: "image"` references by `imageId` — an iterable of
2157
+ * `[imageId, bytes]` (a `Map<number, Uint8Array>` works directly); an image
2158
+ * whose id is absent is skipped. Returns `true` on success.
2159
+ *
2160
+ * @example
2161
+ * doc.setRunningHeaderFooter(
2162
+ * {
2163
+ * default: {
2164
+ * header: [{ type: "image", imageId: 1, w: 80, h: 24, anchor: "left" }],
2165
+ * footer: [{ type: "text", text: "{{title}} — {{page}}/{{pages}}", anchor: "center" }],
2166
+ * },
2167
+ * firstPage: { header: [], footer: [] }, // blank cover
2168
+ * differentFirstPage: true,
2169
+ * differentOddEven: true,
2170
+ * evenPage: { header: [{ type: "text", text: "{{page}}", anchor: "left" }], footer: [] },
2171
+ * oddPage: { header: [{ type: "text", text: "{{page}}", anchor: "right" }], footer: [] },
2172
+ * },
2173
+ * { date: new Date().toISOString().slice(0, 10), images: new Map([[1, logoPng]]) }
2174
+ * );
2175
+ */
2176
+ setRunningHeaderFooter(def, opts) {
2177
+ const entries = opts?.images ? Array.from(opts.images) : [];
2178
+ let total = 4;
2179
+ for (const [, bytes] of entries) total += 8 + bytes.length;
2180
+ const blob = new Uint8Array(total);
2181
+ const dv = new DataView(blob.buffer);
2182
+ let off = 0;
2183
+ dv.setUint32(off, entries.length >>> 0, true);
2184
+ off += 4;
2185
+ for (const [id, bytes] of entries) {
2186
+ dv.setUint32(off, id >>> 0, true);
2187
+ off += 4;
2188
+ dv.setUint32(off, bytes.length >>> 0, true);
2189
+ off += 4;
2190
+ blob.set(bytes, off);
2191
+ off += bytes.length;
2192
+ }
2193
+ return this.g._withStr(
2194
+ JSON.stringify(def),
2195
+ (dp, dl) => this.g._withOptStr(
2196
+ opts?.date,
2197
+ (tp, tl) => this.g._withBytes(
2198
+ blob,
2199
+ (ip, il) => this.ex().gp_set_running_header_footer(this.h, dp, dl, tp, tl, ip, il)
2200
+ )
2201
+ )
2202
+ ) === 0;
2203
+ }
2204
+ /**
2205
+ * The rich {@link RunningHeaderFooter} definition recorded by
2206
+ * {@link setRunningHeaderFooter} (read from the editor-meta sidecar — the
2207
+ * source of truth), or a minimal one reconstructed from a legacy flat
2208
+ * {@link setHeader}/{@link setFooter} bake, or `null` when neither is present.
2209
+ */
2210
+ runningHeaderFooter() {
2211
+ return this.g._jsonOrNull(
2212
+ (o) => this.ex().gp_running_header_footer(this.h, o)
2213
+ );
2214
+ }
1503
2215
  // render
1504
2216
  renderPage(page, scale = 1) {
1505
2217
  return this.g._buffer((o) => this.ex().gp_render_page(this.h, page, scale, o));
@@ -1536,6 +2248,33 @@ var GigaPdfDoc = class {
1536
2248
  )
1537
2249
  );
1538
2250
  }
2251
+ /**
2252
+ * Rasterize a page to a PNG **excluding the ops inside a baked marked-content
2253
+ * span** named `marker` — and, when `skipText` is true, the page's text too — in
2254
+ * a **single** raster pass. For `marker = "GPHF"` (the default) this drops the
2255
+ * baked running header/footer band: the extraction views ({@link elements},
2256
+ * {@link textRuns}) already omit that band (it is never editable body content),
2257
+ * and this render omits it from the picture so it cannot double against an
2258
+ * editable overlay. With `skipText = true` it is the editor's text-free display
2259
+ * background minus the band; with `skipText = false`, the full page minus the
2260
+ * band. Like {@link renderPageNoText}, form-field widget appearances are omitted.
2261
+ */
2262
+ renderPageExcludingMarkedContent(page, scale = 1, skipText = true, marker = "GPHF") {
2263
+ return this.g._buffer(
2264
+ (o) => this.g._withStr(
2265
+ marker,
2266
+ (p, l) => this.ex().gp_render_page_excluding_marked_content(
2267
+ this.h,
2268
+ page,
2269
+ scale,
2270
+ skipText ? 1 : 0,
2271
+ p,
2272
+ l,
2273
+ o
2274
+ )
2275
+ )
2276
+ );
2277
+ }
1539
2278
  // fonts — embed a downloaded font, then add real selectable text
1540
2279
  /**
1541
2280
  * Embed an outline font program as a Type0 font and return its object number
@@ -1707,8 +2446,73 @@ var GigaPdfDoc = class {
1707
2446
  toRtf() {
1708
2447
  return this.g._buffer((o) => this.ex().gp_to_rtf(this.h, o));
1709
2448
  }
1710
- toPdfA() {
1711
- return this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, o));
2449
+ /**
2450
+ * Re-serialize the document as **PDF/A** (archival).
2451
+ *
2452
+ * `level` selects the conformance flavour (default `"pdfa-2b"`):
2453
+ * - `"pdfa-1b"` — ISO 19005-1, based on PDF 1.4.
2454
+ * - `"pdfa-1a"` — ISO 19005-1 **Tagged PDF** (level A): 1b + a logical
2455
+ * structure tree, marked content and `/Lang`. Built from the structure the
2456
+ * engine reconstructs (paragraphs, headings, tables, lists).
2457
+ * - `"pdfa-2b"` — ISO 19005-2 (default).
2458
+ * - `"pdfa-2u"` — like 2b but requires every glyph Unicode-mapped (a
2459
+ * `/ToUnicode` CMap on each font); only validator-clean when the source
2460
+ * fonts already carry one — otherwise prefer `"pdfa-2b"`.
2461
+ * - `"pdfa-2a"` — ISO 19005-2 **Tagged PDF** (level A): 2u + a logical
2462
+ * structure tree and marked content (`/StructTreeRoot`, `/MarkInfo`).
2463
+ * - `"pdfa-3b"` — ISO 19005-3; permits embedded file attachments.
2464
+ *
2465
+ * Full conformance also requires every font embedded — this method does not
2466
+ * embed missing fonts (see the Rust `to_pdfa_level` docs). For the level-A
2467
+ * (`1a`/`2a`) flavours the tagging is rendering-neutral: it only inserts
2468
+ * balanced marked-content operators and a structure tree, never changing the
2469
+ * page appearance.
2470
+ */
2471
+ toPdfA(level = "pdfa-2b") {
2472
+ return this.g._withStr(
2473
+ level,
2474
+ (p, l) => this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, p, l, o))
2475
+ );
2476
+ }
2477
+ /**
2478
+ * Author a **tagged (accessible) PDF** — a `/StructTreeRoot` logical-structure
2479
+ * tree (`P`/`H1`–`H6`/`Table`/`L`/`Figure` …) with marked content, `/MarkInfo`,
2480
+ * `/Lang`, `/RoleMap` and `/Alt` on figures — **without** forcing PDF/A. Pass
2481
+ * `{ pdfUa: true }` to also stamp the PDF/UA-1 identifier (ISO 14289). If the
2482
+ * document has no reconstructable structure the plain PDF is returned.
2483
+ * ISO 32000-1 §14.7/§14.8.
2484
+ */
2485
+ toTagged(opts = {}) {
2486
+ return this.g._buffer((o) => this.ex().gp_to_tagged(this.h, opts.pdfUa ? 1 : 0, o));
2487
+ }
2488
+ /**
2489
+ * The number of taggable **figures** the engine reconstructs across the whole
2490
+ * document — the valid range `0..figureCount()` for {@link setFigureAlt}'s
2491
+ * `index`. Each figure is an image the geometric reconstruction surfaces; the
2492
+ * Tagged-PDF / PDF-A-level-A export emits one `/Figure` structure element per
2493
+ * figure, in this same order.
2494
+ */
2495
+ figureCount() {
2496
+ return this.ex().gp_figure_count(this.h);
2497
+ }
2498
+ /**
2499
+ * Attach **author-supplied alternate text** (`/Alt`) to a figure so assistive
2500
+ * technology can describe the image (WCAG / PDF/UA, ISO 32000-1 §14.9.3).
2501
+ *
2502
+ * `index` is the **document-global figure index** — figures are numbered
2503
+ * `0, 1, 2, …` in page order, then in page-content order within each page (the
2504
+ * Nth image of the whole document is figure `N`; {@link figureCount} bounds the
2505
+ * range). The text lands on the matching `/Figure` structure element's `/Alt`
2506
+ * when an accessible export is produced — {@link toTagged} or {@link toPdfA}
2507
+ * with `"pdfa-1a"`/`"pdfa-2a"`. Figures with no author-supplied text keep a
2508
+ * generic non-empty placeholder, so the output stays structurally valid even
2509
+ * for unlabeled figures.
2510
+ *
2511
+ * Returns `true` on success; `false` if `alt` is empty (a `/Alt` must be
2512
+ * non-empty) or the call otherwise fails.
2513
+ */
2514
+ setFigureAlt(index, alt) {
2515
+ return this.g._withStr(alt, (p, l) => this.ex().gp_set_figure_alt(this.h, index, p, l)) === 0;
1712
2516
  }
1713
2517
  // security
1714
2518
  /**
@@ -1763,6 +2567,117 @@ var GigaPdfDoc = class {
1763
2567
  )
1764
2568
  );
1765
2569
  }
2570
+ /**
2571
+ * Re-encrypt an already-opened (decrypted) document with **new** passwords,
2572
+ * discarding the prior encryption (ISO 32000-1 §7.6). Opening with the old
2573
+ * password is what authorises the change. Mirrors {@link saveEncrypted} plus
2574
+ * `encryptMetadata` (when `false`, the metadata stream is left in the clear).
2575
+ */
2576
+ changePasswords(newPassword, fileId, opts = {}) {
2577
+ const algo = opts.algorithm ?? "aes256";
2578
+ const algoCode = algo === "rc4" ? 0 : algo === "aes128" ? 1 : 2;
2579
+ const permissions = opts.flags !== void 0 ? this.g.permissionsToP(opts.flags) : opts.permissions ?? this.g.permissionsToP();
2580
+ let key = opts.keySeed ?? new Uint8Array(0);
2581
+ if (algoCode === 2 && key.length < 32) {
2582
+ key = cryptoRandom(32);
2583
+ }
2584
+ const encMeta = opts.encryptMetadata ?? true;
2585
+ return this.g._withStr(
2586
+ newPassword,
2587
+ (pwP, pwL) => this.g._withOptStr(
2588
+ opts.ownerPassword,
2589
+ (oP, oL) => this.g._withStr(
2590
+ fileId,
2591
+ (idP, idL) => this.g._withBytes(
2592
+ key,
2593
+ (kP, kL) => this.g._buffer(
2594
+ (o) => this.ex().gp_change_passwords(
2595
+ this.h,
2596
+ pwP,
2597
+ pwL,
2598
+ oP,
2599
+ oL,
2600
+ idP,
2601
+ idL,
2602
+ kP,
2603
+ kL,
2604
+ algoCode,
2605
+ permissions,
2606
+ encMeta ? 1 : 0,
2607
+ o
2608
+ )
2609
+ )
2610
+ )
2611
+ )
2612
+ )
2613
+ );
2614
+ }
2615
+ /**
2616
+ * Strip encryption from an already-opened (decrypted) document, returning a
2617
+ * **plaintext** PDF. The document must have been opened with a valid password.
2618
+ */
2619
+ removeEncryption() {
2620
+ return this.g._buffer((o) => this.ex().gp_remove_encryption(this.h, o));
2621
+ }
2622
+ /**
2623
+ * Encrypt the document to one or more **X.509 recipients** (public-key /
2624
+ * certificate security, ISO 32000-1 §7.6.5, `/Filter /Adobe.PubSec`): only a
2625
+ * holder of a recipient private key can open it — no shared password.
2626
+ * `certificates` are DER X.509 certs. `seed`/`rngSeed` default to Web Crypto
2627
+ * randomness. Open the result with {@link GigaPdfEngine.openWithPrivateKey}.
2628
+ */
2629
+ encryptForRecipients(certificates, opts = {}) {
2630
+ if (certificates.length === 0) {
2631
+ throw new Error("encryptForRecipients needs at least one recipient certificate");
2632
+ }
2633
+ const total = certificates.reduce((n, c) => n + c.length, 0);
2634
+ const blob = new Uint8Array(total);
2635
+ const lens = [];
2636
+ let off = 0;
2637
+ for (const c of certificates) {
2638
+ blob.set(c, off);
2639
+ off += c.length;
2640
+ lens.push(c.length);
2641
+ }
2642
+ const permissions = opts.flags !== void 0 ? this.g.permissionsToP(opts.flags) : opts.permissions ?? this.g.permissionsToP();
2643
+ const aes256 = opts.aes256 ?? true;
2644
+ const encMeta = opts.encryptMetadata ?? true;
2645
+ const seed = opts.seed ?? cryptoRandom(20);
2646
+ const rng = opts.rngSeed ?? cryptoRandom(32);
2647
+ const out = this.g._withBytes(
2648
+ blob,
2649
+ (cP, cL) => this.g._withU32(
2650
+ lens,
2651
+ (lP, lC) => this.g._withBytes(
2652
+ seed,
2653
+ (sP, sL) => this.g._withBytes(
2654
+ rng,
2655
+ (rP, rL) => this.g._buffer(
2656
+ (o) => this.ex().gp_encrypt_for_recipients(
2657
+ this.h,
2658
+ cP,
2659
+ cL,
2660
+ lP,
2661
+ lC,
2662
+ permissions,
2663
+ aes256 ? 1 : 0,
2664
+ encMeta ? 1 : 0,
2665
+ sP,
2666
+ sL,
2667
+ rP,
2668
+ rL,
2669
+ o
2670
+ )
2671
+ )
2672
+ )
2673
+ )
2674
+ )
2675
+ );
2676
+ if (out.length === 0) {
2677
+ throw new Error("encryptForRecipients failed (invalid recipient certificate?)");
2678
+ }
2679
+ return out;
2680
+ }
1766
2681
  /** Self-signed digital signature. `random` ≥ 256 bytes from crypto.getRandomValues. */
1767
2682
  sign(fields, random, keyBits = 2048) {
1768
2683
  const rPtr = this.g._toWasm(random);
@@ -1773,6 +2688,43 @@ var GigaPdfDoc = class {
1773
2688
  this.g._free(rPtr, random.length);
1774
2689
  return out;
1775
2690
  }
2691
+ /**
2692
+ * **Certify** the document (DocMDP) — like {@link sign} but also declares which
2693
+ * later changes are allowed: `docmdpLevel` is `1` (no changes), `2` (form-fill
2694
+ * + sign) or `3` (also annotate). `fields` is the same tab-separated string as
2695
+ * {@link sign} (`name⇥reason⇥date⇥notBefore⇥notAfter`).
2696
+ */
2697
+ certify(fields, random, docmdpLevel, keyBits = 2048) {
2698
+ const rPtr = this.g._toWasm(random);
2699
+ const out = this.g._withStr(
2700
+ fields,
2701
+ (fP, fL) => this.g._buffer(
2702
+ (o) => this.ex().gp_sign_certify(this.h, fP, fL, rPtr, random.length, keyBits, docmdpLevel, o)
2703
+ )
2704
+ );
2705
+ this.g._free(rPtr, random.length);
2706
+ return out;
2707
+ }
2708
+ /**
2709
+ * List every signature on the document (each `/Sig` field's `/V`) with its
2710
+ * metadata and `/ByteRange`. For cryptographic validity call
2711
+ * {@link verifySignatures}.
2712
+ */
2713
+ signatures() {
2714
+ return this.g._json((o) => this.ex().gp_signatures_json(this.h, o));
2715
+ }
2716
+ /**
2717
+ * Cryptographically verify every signature against `pdf` — the **original
2718
+ * bytes** this document was opened from. Each report carries `byteRangeOk`,
2719
+ * `digestOk` (content integrity), `signatureOk` (the RSA signature),
2720
+ * `coversWholeDocument`, the signer CN, and the algorithm.
2721
+ */
2722
+ verifySignatures(pdf) {
2723
+ return this.g._withBytes(
2724
+ pdf,
2725
+ (p, l) => this.g._json((o) => this.ex().gp_verify_signatures(this.h, p, l, o))
2726
+ );
2727
+ }
1776
2728
  /**
1777
2729
  * Sign with a PKCS#12 (`.p12`/`.pfx`) identity — a CA-issued / eIDAS
1778
2730
  * certificate and its RSA key, imported natively (no external crypto). `opts`
@@ -2040,13 +2992,49 @@ var GigaPdfDoc = class {
2040
2992
  (p, l) => this.g._str((o) => this.ex().gp_get_metadata(this.h, p, l, o))
2041
2993
  );
2042
2994
  }
2043
- /** Set an Info-dictionary entry (e.g. "Title", "Author"). */
2995
+ /**
2996
+ * Set a **single** Info-dictionary entry (e.g. `"Title"`, `"Author"`). This
2997
+ * touches only `/Info`; use {@link setInfo} to update the typed fields and keep
2998
+ * the XMP `/Metadata` packet in sync.
2999
+ */
2044
3000
  setMetadata(key, value) {
2045
3001
  return this.g._withStr(
2046
3002
  key,
2047
3003
  (kP, kL) => this.g._withStr(value, (vP, vL) => this.ex().gp_set_metadata(this.h, kP, kL, vP, vL))
2048
3004
  ) === 0;
2049
3005
  }
3006
+ /**
3007
+ * The document's XMP metadata packet (catalog `/Metadata`, ISO 32000-1 §14.3.2)
3008
+ * as raw bytes, or `null` when the document carries no XMP.
3009
+ */
3010
+ getXmp() {
3011
+ const bytes = this.g._buffer((o) => this.ex().gp_get_xmp(this.h, o));
3012
+ return bytes.length === 0 ? null : bytes;
3013
+ }
3014
+ /**
3015
+ * Replace (or create) the document's XMP metadata stream (catalog `/Metadata`,
3016
+ * stored uncompressed). Accepts a UTF-8 string or raw bytes. Returns `true` on
3017
+ * success.
3018
+ */
3019
+ setXmp(xmp) {
3020
+ const bytes = typeof xmp === "string" ? new TextEncoder().encode(xmp) : xmp;
3021
+ return this.g._withBytes(bytes, (p, l) => this.ex().gp_set_xmp(this.h, p, l)) === 0;
3022
+ }
3023
+ /**
3024
+ * Set the standard document-information fields, writing **both** the `/Info`
3025
+ * dictionary and a synced XMP `/Metadata` packet so the two never drift. This is
3026
+ * a **partial** update — only the fields you provide are changed; omit a field
3027
+ * to leave it untouched. Returns `true` on success.
3028
+ *
3029
+ * @example
3030
+ * doc.setInfo({ title: "Annual Report", author: "Ada Lovelace", keywords: "finance, 2026" });
3031
+ */
3032
+ setInfo(fields) {
3033
+ return this.g._withStr(
3034
+ JSON.stringify(fields),
3035
+ (p, l) => this.ex().gp_set_info_json(this.h, p, l)
3036
+ ) === 0;
3037
+ }
2050
3038
  // annotations (Acrobat-style markup)
2051
3039
  annotations(page) {
2052
3040
  return this.g._json((o) => this.ex().gp_annotations_json(this.h, page, o));
@@ -2161,6 +3149,73 @@ var GigaPdfDoc = class {
2161
3149
  (p, l) => this.ex().gp_add_stamp(this.h, page, x0, y0, x1, y1, p, l, RGB(rgb))
2162
3150
  ) === 0;
2163
3151
  }
3152
+ /**
3153
+ * Add a `/Circle` (ellipse) annotation inscribed in `[x0,y0,x1,y1]`. `stroke`
3154
+ * (border) and `fill` (interior) are packed `0xRRGGBB` numbers, or `null` to
3155
+ * omit. Returns `true` on success.
3156
+ */
3157
+ addCircleAnnotation(page, x0, y0, x1, y1, stroke = 0, fill = null, lineWidth = 1) {
3158
+ return this.ex().gp_add_circle_annot(
3159
+ this.h,
3160
+ page,
3161
+ x0,
3162
+ y0,
3163
+ x1,
3164
+ y1,
3165
+ RGB(stroke ?? 0),
3166
+ stroke === null ? 0 : 1,
3167
+ RGB(fill ?? 0),
3168
+ fill === null ? 0 : 1,
3169
+ lineWidth
3170
+ ) === 0;
3171
+ }
3172
+ /**
3173
+ * Add a `/Polygon` annotation — a closed shape through `points` (a flat
3174
+ * `[x0, y0, x1, y1, …]` array, PDF user space), with optional `stroke`/`fill`
3175
+ * (`0xRRGGBB` or `null`). Returns `true` on success.
3176
+ */
3177
+ addPolygonAnnotation(page, points, stroke = 0, fill = null, lineWidth = 1) {
3178
+ return this.g._withF64(
3179
+ points,
3180
+ (p, c) => this.ex().gp_add_polygon_annot(
3181
+ this.h,
3182
+ page,
3183
+ p,
3184
+ c,
3185
+ RGB(stroke ?? 0),
3186
+ stroke === null ? 0 : 1,
3187
+ RGB(fill ?? 0),
3188
+ fill === null ? 0 : 1,
3189
+ lineWidth
3190
+ )
3191
+ ) === 0;
3192
+ }
3193
+ /**
3194
+ * Add a `/PolyLine` annotation — an open path through `points` (a flat
3195
+ * `[x0, y0, x1, y1, …]` array). `rgb` is packed `0xRRGGBB`.
3196
+ */
3197
+ addPolylineAnnotation(page, points, rgb = 0, lineWidth = 1) {
3198
+ return this.g._withF64(
3199
+ points,
3200
+ (p, c) => this.ex().gp_add_polyline_annot(this.h, page, p, c, RGB(rgb), lineWidth)
3201
+ ) === 0;
3202
+ }
3203
+ /**
3204
+ * Add a `/Caret` annotation — a small upward wedge in `[x0,y0,x1,y1]` marking
3205
+ * an insertion point. `rgb` is packed `0xRRGGBB`.
3206
+ */
3207
+ addCaretAnnotation(page, x0, y0, x1, y1, rgb = 0) {
3208
+ return this.ex().gp_add_caret_annot(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;
3209
+ }
3210
+ /**
3211
+ * Regenerate the appearance stream (`/AP /N`) of the 0-based `index`
3212
+ * annotation on `page` from its stored geometry, after editing its colour,
3213
+ * border or geometry. Returns `true` on success, `false` for a bad index or a
3214
+ * subtype whose appearance can't be reconstructed (FreeText/Stamp/Text/Link).
3215
+ */
3216
+ regenerateAppearance(page, index) {
3217
+ return this.ex().gp_regenerate_appearance(this.h, page, index) === 0;
3218
+ }
2164
3219
  flattenAnnotations(page) {
2165
3220
  return this.ex().gp_flatten_annotations(this.h, page);
2166
3221
  }
@@ -2229,6 +3284,150 @@ var GigaPdfDoc = class {
2229
3284
  data: this.g._fromBase64(dataBase64)
2230
3285
  }));
2231
3286
  }
3287
+ /**
3288
+ * Embed `bytes` as a document-level file attachment named `name`
3289
+ * (`/Names /EmbeddedFiles`, ISO 32000-1 §7.11.4). Re-using a `name` **replaces**
3290
+ * that attachment; the bytes are stored FlateDecode-compressed. Returns `true`
3291
+ * on success (`false` e.g. for an empty name).
3292
+ */
3293
+ addAttachment(name, bytes, opts = {}) {
3294
+ return this.g._withStr(
3295
+ name,
3296
+ (np, nl) => this.g._withBytes(
3297
+ bytes,
3298
+ (bp, bl) => this.g._withOptStr(
3299
+ opts.mime ?? "",
3300
+ (mp, ml) => this.g._withOptStr(
3301
+ opts.description ?? "",
3302
+ (dp, dl) => this.ex().gp_add_attachment(this.h, np, nl, bp, bl, mp, ml, dp, dl)
3303
+ )
3304
+ )
3305
+ )
3306
+ ) === 0;
3307
+ }
3308
+ /**
3309
+ * Embed `bytes` as an **associated file** (`/AF`, PDF/A-3) named `name` with the
3310
+ * given {@link AfRelationship} — the mechanism Factur-X / ZUGFeRD / Order-X use
3311
+ * to carry their invoice XML (`"alternative"`). The file is also a normal
3312
+ * attachment, is linked from the catalog `/AF` array, and its filespec carries
3313
+ * `/AFRelationship`. Returns `true` on success.
3314
+ */
3315
+ addAssociatedFile(name, bytes, relationship, opts = {}) {
3316
+ const rel = AF_RELATIONSHIP_CODE[relationship] ?? AF_RELATIONSHIP_CODE.unspecified;
3317
+ return this.g._withStr(
3318
+ name,
3319
+ (np, nl) => this.g._withBytes(
3320
+ bytes,
3321
+ (bp, bl) => this.g._withOptStr(
3322
+ opts.mime ?? "",
3323
+ (mp, ml) => this.g._withOptStr(
3324
+ opts.description ?? "",
3325
+ (dp, dl) => this.ex().gp_add_associated_file(this.h, np, nl, bp, bl, mp, ml, dp, dl, rel)
3326
+ )
3327
+ )
3328
+ )
3329
+ ) === 0;
3330
+ }
3331
+ /**
3332
+ * Remove the attachment named `name` (from `/Names /EmbeddedFiles` and, if
3333
+ * present, the catalog `/AF` array). Returns `true` if one was removed, `false`
3334
+ * if no attachment had that name.
3335
+ */
3336
+ removeAttachment(name) {
3337
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_attachment(this.h, p, l)) === 1;
3338
+ }
3339
+ /**
3340
+ * Mark this document as an embedded-file **portfolio** and configure how its
3341
+ * attachments are presented, by writing the catalog `/Collection`
3342
+ * (ISO 32000-1 §7.11.6, §12.3.5). The files must already be embedded (add them
3343
+ * first with {@link addAttachment} / {@link addAssociatedFile}); this only adds
3344
+ * the presentation layer: the initial {@link CollectionConfig.view view}, the
3345
+ * {@link CollectionConfig.schema schema} columns, the
3346
+ * {@link CollectionConfig.sort sort} order, the
3347
+ * {@link CollectionConfig.defaultFile default file}, and per-file
3348
+ * {@link CollectionConfig.items column values} (each written as a `/CI` on the
3349
+ * matching file's filespec). An empty/omitted schema still produces a valid
3350
+ * `/Collection`. Calling again **replaces** the previous configuration. Returns
3351
+ * `true` on success (`false` on a malformed config or write error).
3352
+ */
3353
+ setCollection(config) {
3354
+ return this.g._withStr(
3355
+ JSON.stringify(config),
3356
+ (p, l) => this.ex().gp_set_collection_json(this.h, p, l)
3357
+ ) === 0;
3358
+ }
3359
+ /**
3360
+ * Read this document's portfolio configuration back from the catalog
3361
+ * `/Collection` — the reader counterpart of {@link setCollection}. Returns
3362
+ * `null` when the document is not a portfolio. The recovered
3363
+ * {@link CollectionConfig} carries the `view`, the `schema` columns (sorted by
3364
+ * order), the `sort`, the `defaultFile`, and each embedded file's `/CI` column
3365
+ * `values`.
3366
+ */
3367
+ collection() {
3368
+ return this.g._json((o) => this.ex().gp_collection_json(this.h, o));
3369
+ }
3370
+ /**
3371
+ * Install a **document-level JavaScript** under the catalog `/Names /JavaScript`
3372
+ * name tree (ISO 32000-1 §7.7.3.4 + §12.6.4.16): a named JavaScript action
3373
+ * (`<< /S /JavaScript /JS … >>`) keyed by `name`. On open, a conforming viewer
3374
+ * runs every document-level script in **name (lexical) order** — this is where
3375
+ * form-calculation / validation helper libraries live (e.g. `AFNumber_Format`).
3376
+ * Re-using a `name` **replaces** that script; long sources are stored as a
3377
+ * FlateDecode stream, and sibling `/Names` subtrees (`/EmbeddedFiles`,
3378
+ * `/Dests`, …) are preserved. Returns `true` on success (`false` e.g. for an
3379
+ * empty name).
3380
+ */
3381
+ addDocumentJavascript(name, script) {
3382
+ return this.g._withStr(
3383
+ name,
3384
+ (np, nl) => this.g._withStr(
3385
+ script,
3386
+ (sp, sl) => this.ex().gp_add_document_javascript(this.h, np, nl, sp, sl)
3387
+ )
3388
+ ) === 0;
3389
+ }
3390
+ /**
3391
+ * Every document-level JavaScript as `{ name, script }` pairs, in name
3392
+ * (lexical) order — the read side of {@link addDocumentJavascript} (decodes
3393
+ * both a literal `/JS` string and a `/JS` stream).
3394
+ */
3395
+ documentJavascripts() {
3396
+ return this.g._json((o) => this.ex().gp_document_javascripts_json(this.h, o));
3397
+ }
3398
+ /**
3399
+ * Remove the document-level JavaScript named `name` from `/Names /JavaScript`.
3400
+ * Returns `true` if one was removed, `false` if none had that name.
3401
+ */
3402
+ removeDocumentJavascript(name) {
3403
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_document_javascript(this.h, p, l)) === 1;
3404
+ }
3405
+ /**
3406
+ * Add a page-anchored **FileAttachment** annotation over `rect` on the 1-based
3407
+ * `page`, pointing at the already-embedded attachment `name` (add it first with
3408
+ * {@link addAttachment}). `icon` is the visual marker (default `"PushPin"`).
3409
+ * Returns `true` on success (`false` if no such attachment exists).
3410
+ */
3411
+ addFileAttachmentAnnot(page, rect, name, icon = "PushPin") {
3412
+ return this.g._withStr(
3413
+ name,
3414
+ (np, nl) => this.g._withOptStr(
3415
+ icon,
3416
+ (ip, il) => this.ex().gp_add_file_attachment_annot(
3417
+ this.h,
3418
+ page,
3419
+ rect.x,
3420
+ rect.y,
3421
+ rect.x + rect.w,
3422
+ rect.y + rect.h,
3423
+ np,
3424
+ nl,
3425
+ ip,
3426
+ il
3427
+ )
3428
+ )
3429
+ ) === 0;
3430
+ }
2232
3431
  /**
2233
3432
  * Add an internal hyperlink over a rectangle that jumps to the named
2234
3433
  * destination `name` (define it with {@link addNamedDest}). Unlike
@@ -2258,6 +3457,24 @@ var GigaPdfDoc = class {
2258
3457
  removeLayer(id) {
2259
3458
  return this.ex().gp_remove_layer(this.h, id) === 0;
2260
3459
  }
3460
+ /**
3461
+ * Begin an optional-content marked-content sequence on `page` for the layer
3462
+ * `ocg` (its id, from {@link addLayer}). Registers the OCG under the page's
3463
+ * `/Resources /Properties` and appends `/OC /OCn BDC` to the content stream;
3464
+ * every drawing call after it ({@link addText}, {@link addRectangle},
3465
+ * {@link addImage}, …) is gated on that layer's visibility until the matching
3466
+ * {@link endOptionalContent} appends `EMC`. Calls nest. Returns the `OCn`
3467
+ * property name (empty string on error).
3468
+ */
3469
+ beginOptionalContent(page, ocg) {
3470
+ return this.g._str(
3471
+ (o) => this.ex().gp_begin_optional_content(this.h, page, ocg, o)
3472
+ );
3473
+ }
3474
+ /** End the innermost optional-content sequence on `page` (`EMC`). */
3475
+ endOptionalContent(page) {
3476
+ return this.ex().gp_end_optional_content(this.h, page) === 0;
3477
+ }
2261
3478
  // outline (bookmarks)
2262
3479
  outline() {
2263
3480
  return this.g._json((o) => this.ex().gp_outline_json(this.h, o));
@@ -2267,6 +3484,79 @@ var GigaPdfDoc = class {
2267
3484
  const text = entries.map((e) => `${e.level} ${e.page ?? 0} ${e.title}`).join("\n");
2268
3485
  return this.g._withStr(text, (p, l) => this.ex().gp_set_outline(this.h, p, l)) === 0;
2269
3486
  }
3487
+ /**
3488
+ * Add a `/Link` annotation over `rect` (`{ x, y, w, h }`) carrying any
3489
+ * {@link Action} — the full action & destination model (GoTo with every fit
3490
+ * mode, GoToR, URI, Named navigation, Launch, JavaScript, SubmitForm,
3491
+ * ResetForm). Returns `true` on success (`false` for a malformed action).
3492
+ *
3493
+ * @example
3494
+ * doc.addLink(1, { x: 72, y: 700, w: 120, h: 16 },
3495
+ * { type: "goto", dest: { fit: "xyz", page: 4, top: 720, zoom: 1.5 } });
3496
+ */
3497
+ addLink(page, rect, action) {
3498
+ return this.g._withStr(
3499
+ JSON.stringify(action),
3500
+ (p, l) => this.ex().gp_add_link(this.h, page, rect.x, rect.y, rect.x + rect.w, rect.y + rect.h, p, l)
3501
+ ) === 0;
3502
+ }
3503
+ /**
3504
+ * Set the document `/OpenAction` — the {@link Action} performed when the file
3505
+ * is opened. Returns `true` on success.
3506
+ */
3507
+ setOpenAction(action) {
3508
+ return this.g._withStr(
3509
+ JSON.stringify(action),
3510
+ (p, l) => this.ex().gp_set_open_action(this.h, p, l)
3511
+ ) === 0;
3512
+ }
3513
+ /**
3514
+ * Remove the `linkIndex`-th `/Link` annotation on `page` (links counted in
3515
+ * order, ignoring non-link annotations). Returns `true` if one was removed.
3516
+ */
3517
+ removeLink(page, linkIndex) {
3518
+ return this.ex().gp_remove_link(this.h, page, linkIndex) === 1;
3519
+ }
3520
+ /**
3521
+ * Replace the outline with {@link Bookmark}s that may carry actions (a `goto`
3522
+ * action becomes a `/Dest`, any other action an `/A`). An empty array clears
3523
+ * the outline. Returns `true` on success.
3524
+ */
3525
+ setBookmarks(bookmarks) {
3526
+ const text = bookmarks.map((b) => `${b.level} ${b.title} ${b.action ? JSON.stringify(b.action) : ""}`).join("\n");
3527
+ return this.g._withOptStr(text, (p, l) => this.ex().gp_set_bookmarks(this.h, p, l)) === 0;
3528
+ }
3529
+ // catalog reading / UX hints (ViewerPreferences, PageLayout, PageMode)
3530
+ /**
3531
+ * Write the catalog `/ViewerPreferences` (ISO 32000-1 §12.2). Each omitted
3532
+ * field is left unchanged; a boolean sets the key. After applying, an empty
3533
+ * dictionary is removed. Returns `false` on an invalid `direction`.
3534
+ */
3535
+ setViewerPreferences(prefs) {
3536
+ const tri = (v) => v === void 0 ? -1 : v ? 1 : 0;
3537
+ return this.g._withStr(
3538
+ prefs.direction ?? "",
3539
+ (dP, dL) => this.ex().gp_set_viewer_preferences(
3540
+ this.h,
3541
+ tri(prefs.hideToolbar),
3542
+ tri(prefs.hideMenubar),
3543
+ tri(prefs.hideWindowUI),
3544
+ tri(prefs.fitWindow),
3545
+ tri(prefs.centerWindow),
3546
+ tri(prefs.displayDocTitle),
3547
+ dP,
3548
+ dL
3549
+ )
3550
+ ) === 0;
3551
+ }
3552
+ /** Set the catalog `/PageLayout`. `null` removes the key. Returns `false` on an unknown name. */
3553
+ setPageLayout(layout) {
3554
+ return this.g._withStr(layout ?? "", (p, l) => this.ex().gp_set_page_layout(this.h, p, l)) === 0;
3555
+ }
3556
+ /** Set the catalog `/PageMode`. `null` removes the key. Returns `false` on an unknown name. */
3557
+ setPageMode(mode) {
3558
+ return this.g._withStr(mode ?? "", (p, l) => this.ex().gp_set_page_mode(this.h, p, l)) === 0;
3559
+ }
2270
3560
  // interactive forms (AcroForm)
2271
3561
  fields() {
2272
3562
  return this.g._json((o) => this.ex().gp_fields_json(this.h, o));
@@ -2428,11 +3718,80 @@ var GigaPdfDoc = class {
2428
3718
  )
2429
3719
  ) === 0;
2430
3720
  }
3721
+ /**
3722
+ * Create a **visible signature field** (`/FT /Sig`) over `rect` — an empty
3723
+ * widget the signing pipeline can later target — and flag the AcroForm
3724
+ * `/SigFlags`. Returns `true` on success.
3725
+ */
3726
+ addSignatureField(page, name, rect, opts = {}) {
3727
+ const st = styleArgs(opts.style);
3728
+ return this.g._withStr(
3729
+ name,
3730
+ (nP, nL) => this.ex().gp_add_signature_field(
3731
+ this.h,
3732
+ page,
3733
+ nP,
3734
+ nL,
3735
+ rect[0],
3736
+ rect[1],
3737
+ rect[2],
3738
+ rect[3],
3739
+ ...st
3740
+ )
3741
+ ) === 0;
3742
+ }
3743
+ /**
3744
+ * Attach field-level JavaScript to a field's `/AA` for the given `trigger`
3745
+ * (`"keystroke"` filters input, `"format"` formats display, `"validate"`
3746
+ * checks on change, `"calculate"` recomputes — ordered by
3747
+ * {@link setCalculationOrder}). Returns `true` if set, `false` if no field has
3748
+ * that name.
3749
+ */
3750
+ setFieldScript(name, trigger, js) {
3751
+ return this.g._withStr(
3752
+ name,
3753
+ (nP, nL) => this.g._withStr(
3754
+ trigger,
3755
+ (tP, tL) => this.g._withStr(
3756
+ js,
3757
+ (jP, jL) => this.ex().gp_set_field_script(this.h, nP, nL, tP, tL, jP, jL)
3758
+ )
3759
+ )
3760
+ ) === 1;
3761
+ }
3762
+ /**
3763
+ * Set the AcroForm calculation order (`/CO`) — the sequence in which fields
3764
+ * with a `calculate` script recompute. Unknown names are skipped.
3765
+ */
3766
+ setCalculationOrder(names) {
3767
+ return this.g._withOptStr(
3768
+ names.join("\n"),
3769
+ (p, l) => this.ex().gp_set_calculation_order(this.h, p, l)
3770
+ ) === 0;
3771
+ }
3772
+ /**
3773
+ * Delete a form field by name (removed from `/Fields`, `/CO` and every page's
3774
+ * annotations). Returns `true` if a field was removed.
3775
+ */
3776
+ removeField(name) {
3777
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_field(this.h, p, l)) === 1;
3778
+ }
3779
+ /**
3780
+ * Rebuild a field's appearance from its current value/style — call after
3781
+ * changing a field's value programmatically. Returns `true` if regenerated
3782
+ * (`false` for an unknown name or a kind that can't be regenerated alone, e.g.
3783
+ * a radio parent with kids).
3784
+ */
3785
+ regenerateFieldAppearance(name) {
3786
+ return this.g._withStr(name, (p, l) => this.ex().gp_regenerate_field_appearance(this.h, p, l)) === 1;
3787
+ }
2431
3788
  };
2432
3789
  // Annotate the CommonJS export names for ESM import in node:
2433
3790
  0 && (module.exports = {
2434
3791
  GigaPdfDoc,
2435
3792
  GigaPdfEngine,
3793
+ PAGE_BOX_KINDS,
3794
+ PAGE_TRANSITION_STYLES,
2436
3795
  defaultCrlGet,
2437
3796
  defaultOcspPost,
2438
3797
  defaultTsaPost