@qrcommunication/gigapdf-lib 0.72.0 → 0.104.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.js CHANGED
@@ -1,5 +1,8 @@
1
1
  // src/index.ts
2
2
  import { loadDefaultWasmBytes } from "./node-fs.js";
3
+ function pdfVersionCode(v) {
4
+ return v === "2.0" ? 1 : 0;
5
+ }
3
6
  var enc = new TextEncoder();
4
7
  var dec = new TextDecoder();
5
8
  var ALL_PERMISSIONS = {
@@ -216,6 +219,23 @@ var GigaPdfEngine = class _GigaPdfEngine {
216
219
  this._free(pwPtr, b.length);
217
220
  return handle === 0 ? null : new GigaPdfDoc(this, handle);
218
221
  }
222
+ /**
223
+ * Open a **public-key (certificate) encrypted** PDF (`/Filter /Adobe.PubSec`,
224
+ * ISO 32000-1 §7.6.5) with a recipient's DER `certificate` + PKCS#1 RSA
225
+ * `privateKey`. `null` if this key is not a recipient. Counterpart of
226
+ * {@link GigaPdfDoc.encryptForRecipients}.
227
+ */
228
+ openWithPrivateKey(pdf, certificate, privateKey) {
229
+ const cP = this._toWasm(certificate);
230
+ const kP = this._toWasm(privateKey);
231
+ const handle = this._withBytes(
232
+ pdf,
233
+ (p, l) => this.ex.gp_open_with_private_key(p, l, cP, certificate.length, kP, privateKey.length)
234
+ );
235
+ this._free(cP, certificate.length);
236
+ this._free(kP, privateKey.length);
237
+ return handle === 0 ? null : new GigaPdfDoc(this, handle);
238
+ }
219
239
  /**
220
240
  * Inspect a PDF's encryption **without decrypting it** (no password needed):
221
241
  * whether it has an `/Encrypt` dictionary, plus its `/P` permission bitmask
@@ -344,19 +364,34 @@ var GigaPdfEngine = class _GigaPdfEngine {
344
364
  );
345
365
  }
346
366
  /**
347
- * Merge several PDFs into one by appending their pages in order. Returns an
348
- * empty document for an empty list, or the single input unchanged for a list
349
- * of one. Each subsequent PDF is appended onto the first via
367
+ * Merge several PDFs into one by appending their pages in order. Each input is
368
+ * either raw bytes (every page) or a {@link MergePart} `{ pdf, pages? }` that
369
+ * selects 1-based page numbers (ISO 32000-1 §7.7.3) — so the two forms can be
370
+ * mixed (e.g. `[whole, { pdf: b, pages: [1, 3] }]`). Returns an empty document
371
+ * for an empty list, or — when the only input is a whole PDF (no `pages`) —
372
+ * that input unchanged. Each subsequent part is appended onto the first via
350
373
  * {@link GigaPdfDoc.appendPages}; the merged bytes are returned and the working
351
374
  * document is closed.
352
375
  */
353
- mergePdfs(pdfs) {
354
- if (pdfs.length === 0) return new Uint8Array(0);
355
- if (pdfs.length === 1) return pdfs[0];
356
- const base = this.open(pdfs[0]);
376
+ mergePdfs(parts) {
377
+ if (parts.length === 0) return new Uint8Array(0);
378
+ const part = (p) => p instanceof Uint8Array ? { pdf: p } : p;
379
+ const first = part(parts[0]);
380
+ if (parts.length === 1 && first.pages === void 0) return first.pdf;
381
+ let seed = first.pdf;
382
+ if (first.pages !== void 0) {
383
+ const head = this.open(first.pdf);
384
+ try {
385
+ seed = head.extractPages(first.pages);
386
+ } finally {
387
+ head.close();
388
+ }
389
+ }
390
+ const base = this.open(seed);
357
391
  try {
358
- for (let i = 1; i < pdfs.length; i++) {
359
- base.appendPages(pdfs[i]);
392
+ for (let i = 1; i < parts.length; i++) {
393
+ const p = part(parts[i]);
394
+ base.appendPages(p.pdf, p.pages);
360
395
  }
361
396
  return base.save();
362
397
  } finally {
@@ -927,7 +962,48 @@ function frameBlobs(blobs) {
927
962
  }
928
963
  return out;
929
964
  }
965
+ var AF_RELATIONSHIP_CODE = {
966
+ source: 0,
967
+ data: 1,
968
+ alternative: 2,
969
+ supplement: 3,
970
+ unspecified: 4
971
+ };
972
+ var PAGE_BOX_KINDS = ["media", "crop", "bleed", "trim", "art"];
973
+ var PAGE_LABEL_STYLE_TOKEN = {
974
+ decimal: "D",
975
+ romanLower: "r",
976
+ romanUpper: "R",
977
+ alphaLower: "a",
978
+ alphaUpper: "A",
979
+ none: "-"
980
+ };
981
+ var PAGE_TRANSITION_STYLES = [
982
+ "split",
983
+ "blinds",
984
+ "box",
985
+ "wipe",
986
+ "dissolve",
987
+ "glitter",
988
+ "fly",
989
+ "push",
990
+ "cover",
991
+ "uncover",
992
+ "fade",
993
+ "replace"
994
+ ];
930
995
  var RGB = (rgb) => rgb & 16777215;
996
+ function cryptoRandom(n) {
997
+ const c = globalThis.crypto;
998
+ if (!c?.getRandomValues) {
999
+ throw new Error(
1000
+ "this operation needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit seed"
1001
+ );
1002
+ }
1003
+ const out = new Uint8Array(n);
1004
+ c.getRandomValues(out);
1005
+ return out;
1006
+ }
931
1007
  function styleArgs(s = {}) {
932
1008
  const hasBorder = s.border === null ? 0 : 1;
933
1009
  const borderRgb = s.border == null ? 0 : s.border;
@@ -965,6 +1041,47 @@ var GigaPdfDoc = class {
965
1041
  saveCompressed() {
966
1042
  return this.g._buffer((o) => this.ex().gp_save_compressed(this.h, o));
967
1043
  }
1044
+ /**
1045
+ * Serialize with PDF 1.5+ **object streams** + a **cross-reference stream**
1046
+ * (ISO 32000-1 §7.5.7 / §7.5.8) — the most compact output. `objectStreams`
1047
+ * (default `true`) packs non-stream objects into compressed `/ObjStm`s (needs
1048
+ * the xref stream); `xrefStreams` (default `true`) writes a `/XRef` stream.
1049
+ * `version` selects the `%PDF-x.y` header banner (default `"1.7"`).
1050
+ * Uncompressed streams are Flate-compressed first, like {@link saveCompressed}.
1051
+ * Linearization (Fast Web View) is not performed.
1052
+ */
1053
+ saveOptimized(opts = {}) {
1054
+ const obj = opts.objectStreams ?? true;
1055
+ const xref = opts.xrefStreams ?? true;
1056
+ const ver = pdfVersionCode(opts.version);
1057
+ return this.g._buffer(
1058
+ (o) => this.ex().gp_save_optimized(this.h, obj ? 1 : 0, xref ? 1 : 0, ver, o)
1059
+ );
1060
+ }
1061
+ /**
1062
+ * Serialize as a **linearized** ("Fast Web View") PDF (ISO 32000-1 Annex F).
1063
+ *
1064
+ * The first page and only the objects needed to render it — together with a
1065
+ * `/Linearized` parameter dictionary and a primary hint stream — are written at
1066
+ * the **front** of the file, so a web viewer can display page 1 before the rest
1067
+ * of the document has downloaded (progressive rendering / byte-range serving).
1068
+ * The remaining pages follow, then a main cross-reference table; the first-page
1069
+ * cross-reference section chains to it via `/Prev`. Streams are Flate-compressed
1070
+ * first (like {@link saveCompressed}) and embedded fonts are subset.
1071
+ *
1072
+ * Falls back to the plain {@link save} output if the document cannot be
1073
+ * linearized (no catalog / page tree / zero pages). `version` selects the
1074
+ * `%PDF-x.y` header banner (default `"1.7"`).
1075
+ */
1076
+ toLinearized(version = "1.7") {
1077
+ return this.g._buffer(
1078
+ (o) => this.ex().gp_to_linearized(this.h, pdfVersionCode(version), o)
1079
+ );
1080
+ }
1081
+ /** Alias of {@link toLinearized} — serialize as a linearized (Fast Web View) PDF. */
1082
+ saveLinearized(version = "1.7") {
1083
+ return this.toLinearized(version);
1084
+ }
968
1085
  // text intelligence
969
1086
  textRuns(page) {
970
1087
  return this.g._json((o) => this.ex().gp_text_runs_json(this.h, page, o));
@@ -1211,6 +1328,212 @@ var GigaPdfDoc = class {
1211
1328
  opacity
1212
1329
  ) === 0;
1213
1330
  }
1331
+ /**
1332
+ * Paint a **linear** or **radial** gradient over `rect` on `page` (ISO 32000-1
1333
+ * §8.7.4 shading + §8.7.3 pattern). `coords` is `[x0,y0,x1,y1]` for `"linear"`
1334
+ * or `[x0,y0,r0,x1,y1,r1]` for `"radial"`; `stops` is ≥ 2 colour stops
1335
+ * (`offset` 0…1, `rgb` packed `0xRRGGBB`). `extend` (default `[true,true]`)
1336
+ * sets `/Extend`; `opacity` (default `1`) is the fill alpha.
1337
+ *
1338
+ * @example
1339
+ * doc.addGradient(1, {
1340
+ * kind: "linear", coords: [50, 50, 250, 50],
1341
+ * stops: [{ offset: 0, rgb: 0xff0000 }, { offset: 1, rgb: 0x0000ff }],
1342
+ * rect: { x: 50, y: 40, w: 200, h: 60 },
1343
+ * });
1344
+ */
1345
+ addGradient(page, spec) {
1346
+ const kind = spec.kind === "radial" ? 1 : 0;
1347
+ const offsets = spec.stops.map((s) => s.offset);
1348
+ const colors = spec.stops.map((s) => RGB(s.rgb));
1349
+ const [es, ee] = spec.extend ?? [true, true];
1350
+ const opacity = spec.opacity ?? 1;
1351
+ const r = spec.rect;
1352
+ return this.g._withF64(
1353
+ spec.coords,
1354
+ (cp, cc) => this.g._withF64(
1355
+ offsets,
1356
+ (op, _oc) => this.g._withU32(
1357
+ colors,
1358
+ (clp, _clc) => this.ex().gp_add_gradient(
1359
+ this.h,
1360
+ page,
1361
+ kind,
1362
+ cp,
1363
+ cc,
1364
+ op,
1365
+ clp,
1366
+ offsets.length,
1367
+ r.x,
1368
+ r.y,
1369
+ r.w,
1370
+ r.h,
1371
+ es ? 1 : 0,
1372
+ ee ? 1 : 0,
1373
+ opacity
1374
+ )
1375
+ )
1376
+ )
1377
+ ) === 0;
1378
+ }
1379
+ /**
1380
+ * Encode a {@link Color} into the ABI's `(kind, comps, name, profile)` buffers
1381
+ * and invoke `fn` with the resulting pointers. Internal.
1382
+ */
1383
+ _color(color, fn) {
1384
+ let kind;
1385
+ let comps;
1386
+ let name = "";
1387
+ let profile = null;
1388
+ switch (color.space) {
1389
+ case "cmyk":
1390
+ kind = 1;
1391
+ comps = [color.c, color.m, color.y, color.k];
1392
+ break;
1393
+ case "gray":
1394
+ kind = 2;
1395
+ comps = [color.gray];
1396
+ break;
1397
+ case "separation":
1398
+ kind = 3;
1399
+ comps = [color.tint, ...color.cmyk];
1400
+ name = color.name;
1401
+ break;
1402
+ case "icc":
1403
+ kind = 4;
1404
+ comps = color.components;
1405
+ profile = color.profile;
1406
+ break;
1407
+ default: {
1408
+ const c = RGB(color.rgb);
1409
+ kind = 0;
1410
+ comps = [(c >> 16 & 255) / 255, (c >> 8 & 255) / 255, (c & 255) / 255];
1411
+ }
1412
+ }
1413
+ return this.g._withF64(
1414
+ comps,
1415
+ (cp, cc) => this.g._withOptStr(
1416
+ name,
1417
+ (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)
1418
+ )
1419
+ );
1420
+ }
1421
+ /**
1422
+ * Fill a rectangle with `color` in **any** colour space — the press-ready
1423
+ * counterpart of {@link addRectangle} (CMYK, spot `Separation`, gray, ICC).
1424
+ *
1425
+ * @example
1426
+ * doc.addFilledRectangle(1, { x: 40, y: 700, w: 200, h: 40 },
1427
+ * { space: "cmyk", c: 0.1, m: 0.8, y: 0.9, k: 0 });
1428
+ */
1429
+ addFilledRectangle(page, rect, color, opacity = 1) {
1430
+ return this._color(
1431
+ color,
1432
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_filled_rectangle(
1433
+ this.h,
1434
+ page,
1435
+ rect.x,
1436
+ rect.y,
1437
+ rect.w,
1438
+ rect.h,
1439
+ kind,
1440
+ cp,
1441
+ cc,
1442
+ np,
1443
+ nl,
1444
+ pp,
1445
+ pl,
1446
+ opacity
1447
+ )
1448
+ ) === 0;
1449
+ }
1450
+ /**
1451
+ * Fill a polygon through flat `[x0,y0,x1,y1,…]` `points` (≥ 3 vertices) with
1452
+ * `color` in any colour space. The path is closed automatically.
1453
+ */
1454
+ addFilledPolygon(page, points, color, opacity = 1) {
1455
+ return this.g._withF64(
1456
+ points,
1457
+ (ptsPtr, ptsCount) => this._color(
1458
+ color,
1459
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_filled_polygon(
1460
+ this.h,
1461
+ page,
1462
+ ptsPtr,
1463
+ ptsCount,
1464
+ kind,
1465
+ cp,
1466
+ cc,
1467
+ np,
1468
+ nl,
1469
+ pp,
1470
+ pl,
1471
+ opacity
1472
+ )
1473
+ )
1474
+ ) === 0;
1475
+ }
1476
+ /**
1477
+ * Draw a base-14 text run in **any** colour space — the press-ready
1478
+ * counterpart of {@link addTextStandard}. `font` is a base-14 family
1479
+ * (`Helvetica`, `Times-Roman`, `Courier`, …).
1480
+ */
1481
+ addTextColor(page, x, y, size, text, font, color, opts = {}) {
1482
+ const { opacity = 1, rotation = 0, underline = false, strikethrough = false } = opts;
1483
+ return this.g._withStr(
1484
+ text,
1485
+ (tp, tl) => this.g._withStr(
1486
+ font,
1487
+ (fp, fl) => this._color(
1488
+ color,
1489
+ (kind, cp, cc, np, nl, pp, pl) => this.ex().gp_add_text_color(
1490
+ this.h,
1491
+ page,
1492
+ x,
1493
+ y,
1494
+ size,
1495
+ tp,
1496
+ tl,
1497
+ fp,
1498
+ fl,
1499
+ kind,
1500
+ cp,
1501
+ cc,
1502
+ np,
1503
+ nl,
1504
+ pp,
1505
+ pl,
1506
+ opacity,
1507
+ rotation,
1508
+ underline ? 1 : 0,
1509
+ strikethrough ? 1 : 0
1510
+ )
1511
+ )
1512
+ )
1513
+ ) === 0;
1514
+ }
1515
+ /**
1516
+ * Turn **overprint** on/off for content drawn **after** this call (`/op` fill,
1517
+ * `/OP` stroke, `/OPM` mode — `0` independent colorants, `1` non-erasing).
1518
+ * Essential for prepress black-overprint / trapping.
1519
+ */
1520
+ setOverprint(page, fill, stroke, mode = 1) {
1521
+ return this.ex().gp_set_overprint(this.h, page, fill ? 1 : 0, stroke ? 1 : 0, mode) === 0;
1522
+ }
1523
+ /**
1524
+ * Add a document-level **OutputIntent** embedding the ICC `profile` (its `/N`
1525
+ * is read from the profile), with `condition` as the output-condition
1526
+ * identifier (e.g. `"Coated FOGRA39"`). Decoupled from the PDF/A path.
1527
+ */
1528
+ addOutputIntent(profile, condition) {
1529
+ return this.g._withBytes(
1530
+ profile,
1531
+ (pp, pl) => this.g._withStr(
1532
+ condition,
1533
+ (cp, cl) => this.ex().gp_add_output_intent(this.h, pp, pl, cp, cl)
1534
+ )
1535
+ ) === 0;
1536
+ }
1214
1537
  /**
1215
1538
  * Draw a polyline/polygon through flat `[x0,y0,x1,y1,…]` points. `close` joins
1216
1539
  * the last vertex back to the first. `0xRRGGBB` colours, or `null` to omit.
@@ -1267,6 +1590,27 @@ var GigaPdfDoc = class {
1267
1590
  (p, l) => this.ex().gp_add_image(this.h, page, p, l, x, y, w, h, opacity)
1268
1591
  ) === 0;
1269
1592
  }
1593
+ /**
1594
+ * Replace the pixels of an **existing image XObject in place** — swap a logo or
1595
+ * photo while every reference to it stays intact (ISO 32000-1 §8.9). `index` is
1596
+ * the **unified element index** of an image on `page`, exactly the `index`
1597
+ * reported by {@link imageElements} (and accepted by {@link removeElement} /
1598
+ * {@link transformElement}); `data` is a fresh PNG or JPEG.
1599
+ *
1600
+ * Unlike a delete-then-re-add, the image keeps its object number, **every `/Do`
1601
+ * placement, and its position / scale / rotation / clip matrix** — only the
1602
+ * stream bytes and the image dictionary (`/Width`, `/Height`, `/ColorSpace`,
1603
+ * `/BitsPerComponent`, `/Filter`) are rewritten. The new raster is re-encoded
1604
+ * through the same path as {@link addImage} (PNG alpha → a fresh `/SMask`; JPEG
1605
+ * → `/DCTDecode` passthrough). It need not match the old pixel size — it is
1606
+ * drawn into the same box (transform the element first to re-fit it).
1607
+ *
1608
+ * Returns `false` if `page`/`index` doesn't resolve to a top-level image, or the
1609
+ * bytes aren't a decodable PNG/JPEG.
1610
+ */
1611
+ replaceImage(page, index, data) {
1612
+ return this.g._withBytes(data, (p, l) => this.ex().gp_replace_image(this.h, page, index, p, l)) === 0;
1613
+ }
1270
1614
  /**
1271
1615
  * Stamp an **image watermark** across pages from raw image bytes. Accepts the
1272
1616
  * same five formats the engine decodes — **PNG, JPEG, WebP, GIF, AVIF**. The
@@ -1363,8 +1707,25 @@ var GigaPdfDoc = class {
1363
1707
  movePage(from, to) {
1364
1708
  return this.ex().gp_move_page(this.h, from, to) === 0;
1365
1709
  }
1366
- appendPages(otherPdf) {
1367
- return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;
1710
+ /**
1711
+ * Append pages of another PDF onto this document. With no `pages`, every page
1712
+ * is appended (powers *merge*). With `pages` — 1-based page numbers, in the
1713
+ * order given — only that selection is brought in (ISO 32000-1 §7.7.3), each
1714
+ * page keeping its content, resources, annotations and box geometry. Numbers
1715
+ * out of range are skipped; an empty/all-out-of-range selection returns
1716
+ * `false`.
1717
+ */
1718
+ appendPages(otherPdf, pages) {
1719
+ if (pages === void 0) {
1720
+ return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;
1721
+ }
1722
+ return this.g._withBytes(
1723
+ otherPdf,
1724
+ (bp, bl) => this.g._withU32(
1725
+ pages,
1726
+ (pp, pc) => this.ex().gp_append_pages_subset(this.h, bp, bl, pp, pc)
1727
+ )
1728
+ ) === 0;
1368
1729
  }
1369
1730
  /**
1370
1731
  * Add an invisible (text render mode 3) standard-Helvetica text layer to
@@ -1407,10 +1768,71 @@ var GigaPdfDoc = class {
1407
1768
  (p, c) => this.g._buffer((o) => this.ex().gp_extract_pages(this.h, p, c, o))
1408
1769
  );
1409
1770
  }
1410
- /** Resize a page's MediaBox to `width`×`height` points. */
1771
+ /**
1772
+ * Resize a page's `/MediaBox` to `width`×`height` points — **box geometry
1773
+ * only**. The drawn content keeps its own coordinates (it is *not* rescaled to
1774
+ * the new box, so it may clip or float). To scale the page content along with
1775
+ * the box (keeping annotations aligned) use {@link scalePageContent} or
1776
+ * {@link scalePageTo}; for large-format authoring see {@link setUserUnit}.
1777
+ */
1411
1778
  resizePage(page, width, height) {
1412
1779
  return this.ex().gp_resize_page(this.h, page, width, height) === 0;
1413
1780
  }
1781
+ /**
1782
+ * Scale a page's **content** uniformly by `factor` about the page origin (ISO
1783
+ * 32000-1 §8.3.4) — a true zoom of the whole page, not just the box. Three
1784
+ * things move together: (1) the content stream is wrapped in
1785
+ * `q <factor 0 0 factor 0 0> cm … Q`; (2) `/MediaBox` and `/CropBox` (resolved
1786
+ * through inheritance) plus any locally declared `/BleedBox`/`/TrimBox`/
1787
+ * `/ArtBox` are scaled about the origin; (3) every annotation `/Rect` is scaled,
1788
+ * so widget/stamp appearances — mapped from their `/BBox` into the `/Rect` per
1789
+ * §12.5.5 — rescale to stay aligned automatically. `factor` must be finite and
1790
+ * positive. `false` on engine error (bad page number / non-positive factor).
1791
+ */
1792
+ scalePageContent(page, factor) {
1793
+ return this.ex().gp_scale_page_content(this.h, page, factor) === 0;
1794
+ }
1795
+ /**
1796
+ * Anisotropic {@link scalePageContent}: scale a page's content by `sx`
1797
+ * horizontally and `sy` vertically about the origin, scaling the boxes and
1798
+ * annotation `/Rect`s by the same factors. Both must be finite and positive.
1799
+ * `false` on engine error.
1800
+ */
1801
+ scalePageContentXY(page, sx, sy) {
1802
+ return this.ex().gp_scale_page_content_xy(this.h, page, sx, sy) === 0;
1803
+ }
1804
+ /**
1805
+ * Scale a page's content to **fit within** `width`×`height` points (shrink- or
1806
+ * grow-to-fit), preserving aspect ratio — equivalent to {@link scalePageContent}
1807
+ * with `min(width / currentWidth, height / currentHeight)` over the page's
1808
+ * displayed size (`/MediaBox` with `/Rotate` applied). Returns the uniform
1809
+ * factor applied, or `null` on engine error (bad page number, non-positive
1810
+ * target, or zero-area page).
1811
+ */
1812
+ scalePageTo(page, width, height) {
1813
+ const factor = this.ex().gp_scale_page_to(this.h, page, width, height);
1814
+ return factor < 0 ? null : factor;
1815
+ }
1816
+ /**
1817
+ * Set a page's `/UserUnit` (ISO 32000-1 §14.11.2) for **large-format
1818
+ * authoring**: one default user-space unit becomes `unit`⁄72 inch, so the same
1819
+ * coordinates render larger (e.g. `2.0` doubles the physical size, lifting the
1820
+ * ~200-inch coordinate ceiling). `1.0` is the default and removes the key. This
1821
+ * is distinct from {@link scalePageContent}: it rescales the coordinate system
1822
+ * (a viewer-level zoom of the medium), not the content or boxes. `unit` must be
1823
+ * finite and positive. `false` on engine error.
1824
+ */
1825
+ setUserUnit(page, unit) {
1826
+ return this.ex().gp_set_user_unit(this.h, page, unit) === 0;
1827
+ }
1828
+ /**
1829
+ * A page's `/UserUnit` (ISO 32000-1 §14.11.2), defaulting to `1.0` when absent.
1830
+ * Returns `null` on engine error (bad page number).
1831
+ */
1832
+ pageUserUnit(page) {
1833
+ const unit = this.ex().gp_page_user_unit(this.h, page);
1834
+ return unit < 0 ? null : unit;
1835
+ }
1414
1836
  /** Insert a blank page after the 1-based `after` page (0 = front); returns its id. */
1415
1837
  addPage(width, height, after = 0) {
1416
1838
  return this.ex().gp_add_page(this.h, width, height, after);
@@ -1419,6 +1841,56 @@ var GigaPdfDoc = class {
1419
1841
  copyPage(page) {
1420
1842
  return this.ex().gp_copy_page(this.h, page);
1421
1843
  }
1844
+ /**
1845
+ * N-up imposition (ISO 32000-1 §8.10): draw the **content** of the 1-based
1846
+ * `source` page, scaled and translated, onto the 1-based `target` page — the
1847
+ * basis for 2-up/4-up, booklets, contact sheets and page-on-page stamping. The
1848
+ * source page becomes a Form XObject (its content + `/Resources`, so its fonts
1849
+ * and images come along) and is drawn with `q <cm> /Fmn Do Q` appended to the
1850
+ * target. `(x, y)` is where the visible page's lower-left corner lands and
1851
+ * `(scaleX, scaleY)` scale the page **as displayed** (its `/MediaBox` origin
1852
+ * and `/Rotate` are absorbed into the matrix). Wrapped in `q`/`Q`, so it never
1853
+ * disturbs existing target content and is **composable** — call it repeatedly
1854
+ * (different sources and/or cells) to build an N-up sheet. `source` and
1855
+ * `target` may be the same page. `false` on engine error (bad page number).
1856
+ */
1857
+ placePage(target, source, x, y, scaleX, scaleY) {
1858
+ return this.ex().gp_place_page(this.h, target, source, x, y, scaleX, scaleY) === 0;
1859
+ }
1860
+ /**
1861
+ * Place `source` onto `target` (both 1-based) using an explicit content-stream
1862
+ * matrix `[a, b, c, d, e, f]` — the low-level primitive behind
1863
+ * {@link placePage} for full control of the affine (shear, arbitrary rotation,
1864
+ * reflection). The matrix maps the source page's form space (its user space,
1865
+ * including the `/MediaBox` origin) to the target; unlike {@link placePage} no
1866
+ * origin/rotation normalisation is applied, so identity draws the source 1:1
1867
+ * at the target origin. `false` on engine error.
1868
+ */
1869
+ placePageMatrix(target, source, matrix) {
1870
+ const [a, b, c, d, e, f] = matrix;
1871
+ return this.ex().gp_place_page_matrix(this.h, target, source, a, b, c, d, e, f) === 0;
1872
+ }
1873
+ /**
1874
+ * Impose **all** existing pages `cols × rows` per sheet onto freshly added
1875
+ * sheets (2-up, 4-up, booklet thumbnails, contact sheets). Pages go
1876
+ * left-to-right, top-to-bottom; each is scaled uniformly to fit its cell
1877
+ * (aspect preserved) and centred. The new sheets are appended after the last
1878
+ * original page and the **originals are removed**, leaving only the imposed
1879
+ * sheets. Returns the number of sheets produced (negative on error: `cols`/
1880
+ * `rows` 0, or an empty document). `sheetWidth`/`sheetHeight` default to A4
1881
+ * portrait; `margin`/`gutter` to 14 pt.
1882
+ */
1883
+ nUp(cols, rows, opts = {}) {
1884
+ return this.ex().gp_n_up(
1885
+ this.h,
1886
+ cols,
1887
+ rows,
1888
+ opts.sheetWidth ?? 595.28,
1889
+ opts.sheetHeight ?? 841.89,
1890
+ opts.margin ?? 14,
1891
+ opts.gutter ?? 14
1892
+ );
1893
+ }
1422
1894
  /** A page's size (points) and `/Rotate` (0/90/180/270). */
1423
1895
  pageInfo(page) {
1424
1896
  return this.g._json((o) => this.ex().gp_page_info_json(this.h, page, o));
@@ -1438,6 +1910,118 @@ var GigaPdfDoc = class {
1438
1910
  setPageMargins(page, m) {
1439
1911
  return this.ex().gp_set_page_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;
1440
1912
  }
1913
+ /**
1914
+ * All five page boundary boxes (`media`/`crop`/`bleed`/`trim`/`art`) for the
1915
+ * 1-based `page`, each as `[x0, y0, x1, y1]` in points, with ISO 32000-1
1916
+ * inheritance and defaults applied. See {@link PageBoxes} for the exact
1917
+ * default chain and the `declared` flags.
1918
+ */
1919
+ getPageBoxes(page) {
1920
+ return this.g._json((o) => this.ex().gp_page_boxes_json(this.h, page, o));
1921
+ }
1922
+ /**
1923
+ * Set one of a page's boundary boxes. `kind` is one of {@link PAGE_BOX_KINDS}
1924
+ * and `box` is given as `{ x, y, w, h }` (origin + size, points); it is written
1925
+ * as `[x, y, x+w, y+h]`, normalised so reversed sizes are accepted. Sibling
1926
+ * boxes are preserved. Returns `true` on success, `false` for an unknown kind,
1927
+ * a degenerate box (zero/negative area), or a bad page number.
1928
+ *
1929
+ * Setting `"trim"`/`"bleed"` is the prerequisite for PDF/X and commercial-print
1930
+ * (imposition, bleed, finished-size) pipelines.
1931
+ */
1932
+ setPageBox(page, kind, box) {
1933
+ const k = PAGE_BOX_KINDS.indexOf(kind);
1934
+ if (k < 0) return false;
1935
+ return this.ex().gp_set_page_box(this.h, page, k, box.x, box.y, box.x + box.w, box.y + box.h) === 0;
1936
+ }
1937
+ /**
1938
+ * The document's page-label ranges (`/PageLabels`, ISO 32000-1 §12.4.2), sorted
1939
+ * by `startPage` (1-based). Empty when the document declares no page labels.
1940
+ */
1941
+ getPageLabels() {
1942
+ return this.g._json((o) => this.ex().gp_page_labels_json(this.h, o));
1943
+ }
1944
+ /**
1945
+ * Replace the document's page labels. Pass an **empty** array to remove all
1946
+ * labels. Ranges are sorted by `startPage` and collapsed to one entry per page
1947
+ * (last wins). Returns `true` on success.
1948
+ *
1949
+ * @example
1950
+ * // Front matter in lowercase roman, body in decimal, appendix "A-1, A-2…".
1951
+ * doc.setPageLabels([
1952
+ * { startPage: 1, style: "romanLower", prefix: "", startNumber: 1 },
1953
+ * { startPage: 5, style: "decimal", prefix: "", startNumber: 1 },
1954
+ * { startPage: 20, style: "decimal", prefix: "A-", startNumber: 1 },
1955
+ * ]);
1956
+ */
1957
+ setPageLabels(ranges) {
1958
+ const text = ranges.map(
1959
+ (r) => `${r.startPage} ${PAGE_LABEL_STYLE_TOKEN[r.style] ?? "-"} ${r.startNumber ?? 1} ${r.prefix ?? ""}`
1960
+ ).join("\n");
1961
+ return this.g._withOptStr(text, (p, l) => this.ex().gp_set_page_labels(this.h, p, l)) === 0;
1962
+ }
1963
+ /**
1964
+ * The viewer-visible label string for the 1-based `page` (e.g. `"iv"`, `"A-3"`),
1965
+ * resolving the applicable `/PageLabels` range; the decimal page number when no
1966
+ * range applies (including a document with no page labels).
1967
+ */
1968
+ pageLabel(page) {
1969
+ return this.g._str((o) => this.ex().gp_page_label(this.h, page, o));
1970
+ }
1971
+ /**
1972
+ * Author a presentation transition + auto-advance on `page` (1-based),
1973
+ * ISO 32000-1 §12.4.4. Writes the page's `/Trans` dictionary from
1974
+ * {@link PageTransition.style} plus only the optional sub-keys that apply to
1975
+ * that style (`dimension`/`motion` for `split`, `direction`/`scale`/
1976
+ * `flyAreaOpaque` for `fly`, …) — inapplicable fields are dropped.
1977
+ * {@link PageTransition.displayDuration} becomes the page's `/Dur`
1978
+ * (auto-advance); omitting it removes any existing `/Dur`. Re-calling replaces
1979
+ * the prior transition in full (idempotent). Returns `true` on success,
1980
+ * `false` for an unknown style, a negative/non-finite `duration`/`scale`/
1981
+ * `displayDuration`, or a bad page number.
1982
+ *
1983
+ * @example
1984
+ * // Kiosk slideshow: every page wipes in over 0.5 s, auto-advancing after 5 s.
1985
+ * for (let p = 1; p <= doc.pageCount(); p++) {
1986
+ * doc.setPageTransition(p, { style: "wipe", duration: 0.5, displayDuration: 5 });
1987
+ * }
1988
+ */
1989
+ setPageTransition(page, trans) {
1990
+ const style = PAGE_TRANSITION_STYLES.indexOf(trans.style);
1991
+ if (style < 0) return false;
1992
+ const dimension = trans.dimension === "horizontal" ? 0 : trans.dimension === "vertical" ? 1 : -1;
1993
+ const motion = trans.motion === "inward" ? 0 : trans.motion === "outward" ? 1 : -1;
1994
+ const direction = trans.direction === void 0 ? -2 : trans.direction === "none" ? -1 : trans.direction;
1995
+ const flyB = trans.flyAreaOpaque === void 0 ? -1 : trans.flyAreaOpaque ? 1 : 0;
1996
+ return this.ex().gp_set_page_transition(
1997
+ this.h,
1998
+ page,
1999
+ style,
2000
+ trans.duration ?? Number.NaN,
2001
+ dimension,
2002
+ motion,
2003
+ direction,
2004
+ trans.scale ?? Number.NaN,
2005
+ flyB,
2006
+ trans.displayDuration ?? Number.NaN
2007
+ ) === 0;
2008
+ }
2009
+ /**
2010
+ * The presentation transition declared on `page` (1-based), or `null` when the
2011
+ * page has no `/Trans` (ISO 32000-1 §12.4.4). Optional fields that do not apply
2012
+ * to the recovered style are omitted from the result.
2013
+ */
2014
+ getPageTransition(page) {
2015
+ return this.g._jsonOrNull((o) => this.ex().gp_page_transition_json(this.h, page, o));
2016
+ }
2017
+ /**
2018
+ * Remove any presentation transition from `page` (1-based) — drops the page's
2019
+ * `/Trans` dictionary and its `/Dur` auto-advance entry. A no-op if neither is
2020
+ * present. Returns `true` on success.
2021
+ */
2022
+ clearPageTransition(page) {
2023
+ return this.ex().gp_clear_page_transition(this.h, page) === 0;
2024
+ }
1441
2025
  /**
1442
2026
  * Bake a running header onto every in-range page (idempotent: re-baking
1443
2027
  * replaces the prior header). Returns `true` on success.
@@ -1679,8 +2263,73 @@ var GigaPdfDoc = class {
1679
2263
  toRtf() {
1680
2264
  return this.g._buffer((o) => this.ex().gp_to_rtf(this.h, o));
1681
2265
  }
1682
- toPdfA() {
1683
- return this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, o));
2266
+ /**
2267
+ * Re-serialize the document as **PDF/A** (archival).
2268
+ *
2269
+ * `level` selects the conformance flavour (default `"pdfa-2b"`):
2270
+ * - `"pdfa-1b"` — ISO 19005-1, based on PDF 1.4.
2271
+ * - `"pdfa-1a"` — ISO 19005-1 **Tagged PDF** (level A): 1b + a logical
2272
+ * structure tree, marked content and `/Lang`. Built from the structure the
2273
+ * engine reconstructs (paragraphs, headings, tables, lists).
2274
+ * - `"pdfa-2b"` — ISO 19005-2 (default).
2275
+ * - `"pdfa-2u"` — like 2b but requires every glyph Unicode-mapped (a
2276
+ * `/ToUnicode` CMap on each font); only validator-clean when the source
2277
+ * fonts already carry one — otherwise prefer `"pdfa-2b"`.
2278
+ * - `"pdfa-2a"` — ISO 19005-2 **Tagged PDF** (level A): 2u + a logical
2279
+ * structure tree and marked content (`/StructTreeRoot`, `/MarkInfo`).
2280
+ * - `"pdfa-3b"` — ISO 19005-3; permits embedded file attachments.
2281
+ *
2282
+ * Full conformance also requires every font embedded — this method does not
2283
+ * embed missing fonts (see the Rust `to_pdfa_level` docs). For the level-A
2284
+ * (`1a`/`2a`) flavours the tagging is rendering-neutral: it only inserts
2285
+ * balanced marked-content operators and a structure tree, never changing the
2286
+ * page appearance.
2287
+ */
2288
+ toPdfA(level = "pdfa-2b") {
2289
+ return this.g._withStr(
2290
+ level,
2291
+ (p, l) => this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, p, l, o))
2292
+ );
2293
+ }
2294
+ /**
2295
+ * Author a **tagged (accessible) PDF** — a `/StructTreeRoot` logical-structure
2296
+ * tree (`P`/`H1`–`H6`/`Table`/`L`/`Figure` …) with marked content, `/MarkInfo`,
2297
+ * `/Lang`, `/RoleMap` and `/Alt` on figures — **without** forcing PDF/A. Pass
2298
+ * `{ pdfUa: true }` to also stamp the PDF/UA-1 identifier (ISO 14289). If the
2299
+ * document has no reconstructable structure the plain PDF is returned.
2300
+ * ISO 32000-1 §14.7/§14.8.
2301
+ */
2302
+ toTagged(opts = {}) {
2303
+ return this.g._buffer((o) => this.ex().gp_to_tagged(this.h, opts.pdfUa ? 1 : 0, o));
2304
+ }
2305
+ /**
2306
+ * The number of taggable **figures** the engine reconstructs across the whole
2307
+ * document — the valid range `0..figureCount()` for {@link setFigureAlt}'s
2308
+ * `index`. Each figure is an image the geometric reconstruction surfaces; the
2309
+ * Tagged-PDF / PDF-A-level-A export emits one `/Figure` structure element per
2310
+ * figure, in this same order.
2311
+ */
2312
+ figureCount() {
2313
+ return this.ex().gp_figure_count(this.h);
2314
+ }
2315
+ /**
2316
+ * Attach **author-supplied alternate text** (`/Alt`) to a figure so assistive
2317
+ * technology can describe the image (WCAG / PDF/UA, ISO 32000-1 §14.9.3).
2318
+ *
2319
+ * `index` is the **document-global figure index** — figures are numbered
2320
+ * `0, 1, 2, …` in page order, then in page-content order within each page (the
2321
+ * Nth image of the whole document is figure `N`; {@link figureCount} bounds the
2322
+ * range). The text lands on the matching `/Figure` structure element's `/Alt`
2323
+ * when an accessible export is produced — {@link toTagged} or {@link toPdfA}
2324
+ * with `"pdfa-1a"`/`"pdfa-2a"`. Figures with no author-supplied text keep a
2325
+ * generic non-empty placeholder, so the output stays structurally valid even
2326
+ * for unlabeled figures.
2327
+ *
2328
+ * Returns `true` on success; `false` if `alt` is empty (a `/Alt` must be
2329
+ * non-empty) or the call otherwise fails.
2330
+ */
2331
+ setFigureAlt(index, alt) {
2332
+ return this.g._withStr(alt, (p, l) => this.ex().gp_set_figure_alt(this.h, index, p, l)) === 0;
1684
2333
  }
1685
2334
  // security
1686
2335
  /**
@@ -1735,6 +2384,117 @@ var GigaPdfDoc = class {
1735
2384
  )
1736
2385
  );
1737
2386
  }
2387
+ /**
2388
+ * Re-encrypt an already-opened (decrypted) document with **new** passwords,
2389
+ * discarding the prior encryption (ISO 32000-1 §7.6). Opening with the old
2390
+ * password is what authorises the change. Mirrors {@link saveEncrypted} plus
2391
+ * `encryptMetadata` (when `false`, the metadata stream is left in the clear).
2392
+ */
2393
+ changePasswords(newPassword, fileId, opts = {}) {
2394
+ const algo = opts.algorithm ?? "aes256";
2395
+ const algoCode = algo === "rc4" ? 0 : algo === "aes128" ? 1 : 2;
2396
+ const permissions = opts.flags !== void 0 ? this.g.permissionsToP(opts.flags) : opts.permissions ?? this.g.permissionsToP();
2397
+ let key = opts.keySeed ?? new Uint8Array(0);
2398
+ if (algoCode === 2 && key.length < 32) {
2399
+ key = cryptoRandom(32);
2400
+ }
2401
+ const encMeta = opts.encryptMetadata ?? true;
2402
+ return this.g._withStr(
2403
+ newPassword,
2404
+ (pwP, pwL) => this.g._withOptStr(
2405
+ opts.ownerPassword,
2406
+ (oP, oL) => this.g._withStr(
2407
+ fileId,
2408
+ (idP, idL) => this.g._withBytes(
2409
+ key,
2410
+ (kP, kL) => this.g._buffer(
2411
+ (o) => this.ex().gp_change_passwords(
2412
+ this.h,
2413
+ pwP,
2414
+ pwL,
2415
+ oP,
2416
+ oL,
2417
+ idP,
2418
+ idL,
2419
+ kP,
2420
+ kL,
2421
+ algoCode,
2422
+ permissions,
2423
+ encMeta ? 1 : 0,
2424
+ o
2425
+ )
2426
+ )
2427
+ )
2428
+ )
2429
+ )
2430
+ );
2431
+ }
2432
+ /**
2433
+ * Strip encryption from an already-opened (decrypted) document, returning a
2434
+ * **plaintext** PDF. The document must have been opened with a valid password.
2435
+ */
2436
+ removeEncryption() {
2437
+ return this.g._buffer((o) => this.ex().gp_remove_encryption(this.h, o));
2438
+ }
2439
+ /**
2440
+ * Encrypt the document to one or more **X.509 recipients** (public-key /
2441
+ * certificate security, ISO 32000-1 §7.6.5, `/Filter /Adobe.PubSec`): only a
2442
+ * holder of a recipient private key can open it — no shared password.
2443
+ * `certificates` are DER X.509 certs. `seed`/`rngSeed` default to Web Crypto
2444
+ * randomness. Open the result with {@link GigaPdfEngine.openWithPrivateKey}.
2445
+ */
2446
+ encryptForRecipients(certificates, opts = {}) {
2447
+ if (certificates.length === 0) {
2448
+ throw new Error("encryptForRecipients needs at least one recipient certificate");
2449
+ }
2450
+ const total = certificates.reduce((n, c) => n + c.length, 0);
2451
+ const blob = new Uint8Array(total);
2452
+ const lens = [];
2453
+ let off = 0;
2454
+ for (const c of certificates) {
2455
+ blob.set(c, off);
2456
+ off += c.length;
2457
+ lens.push(c.length);
2458
+ }
2459
+ const permissions = opts.flags !== void 0 ? this.g.permissionsToP(opts.flags) : opts.permissions ?? this.g.permissionsToP();
2460
+ const aes256 = opts.aes256 ?? true;
2461
+ const encMeta = opts.encryptMetadata ?? true;
2462
+ const seed = opts.seed ?? cryptoRandom(20);
2463
+ const rng = opts.rngSeed ?? cryptoRandom(32);
2464
+ const out = this.g._withBytes(
2465
+ blob,
2466
+ (cP, cL) => this.g._withU32(
2467
+ lens,
2468
+ (lP, lC) => this.g._withBytes(
2469
+ seed,
2470
+ (sP, sL) => this.g._withBytes(
2471
+ rng,
2472
+ (rP, rL) => this.g._buffer(
2473
+ (o) => this.ex().gp_encrypt_for_recipients(
2474
+ this.h,
2475
+ cP,
2476
+ cL,
2477
+ lP,
2478
+ lC,
2479
+ permissions,
2480
+ aes256 ? 1 : 0,
2481
+ encMeta ? 1 : 0,
2482
+ sP,
2483
+ sL,
2484
+ rP,
2485
+ rL,
2486
+ o
2487
+ )
2488
+ )
2489
+ )
2490
+ )
2491
+ )
2492
+ );
2493
+ if (out.length === 0) {
2494
+ throw new Error("encryptForRecipients failed (invalid recipient certificate?)");
2495
+ }
2496
+ return out;
2497
+ }
1738
2498
  /** Self-signed digital signature. `random` ≥ 256 bytes from crypto.getRandomValues. */
1739
2499
  sign(fields, random, keyBits = 2048) {
1740
2500
  const rPtr = this.g._toWasm(random);
@@ -1745,6 +2505,43 @@ var GigaPdfDoc = class {
1745
2505
  this.g._free(rPtr, random.length);
1746
2506
  return out;
1747
2507
  }
2508
+ /**
2509
+ * **Certify** the document (DocMDP) — like {@link sign} but also declares which
2510
+ * later changes are allowed: `docmdpLevel` is `1` (no changes), `2` (form-fill
2511
+ * + sign) or `3` (also annotate). `fields` is the same tab-separated string as
2512
+ * {@link sign} (`name⇥reason⇥date⇥notBefore⇥notAfter`).
2513
+ */
2514
+ certify(fields, random, docmdpLevel, keyBits = 2048) {
2515
+ const rPtr = this.g._toWasm(random);
2516
+ const out = this.g._withStr(
2517
+ fields,
2518
+ (fP, fL) => this.g._buffer(
2519
+ (o) => this.ex().gp_sign_certify(this.h, fP, fL, rPtr, random.length, keyBits, docmdpLevel, o)
2520
+ )
2521
+ );
2522
+ this.g._free(rPtr, random.length);
2523
+ return out;
2524
+ }
2525
+ /**
2526
+ * List every signature on the document (each `/Sig` field's `/V`) with its
2527
+ * metadata and `/ByteRange`. For cryptographic validity call
2528
+ * {@link verifySignatures}.
2529
+ */
2530
+ signatures() {
2531
+ return this.g._json((o) => this.ex().gp_signatures_json(this.h, o));
2532
+ }
2533
+ /**
2534
+ * Cryptographically verify every signature against `pdf` — the **original
2535
+ * bytes** this document was opened from. Each report carries `byteRangeOk`,
2536
+ * `digestOk` (content integrity), `signatureOk` (the RSA signature),
2537
+ * `coversWholeDocument`, the signer CN, and the algorithm.
2538
+ */
2539
+ verifySignatures(pdf) {
2540
+ return this.g._withBytes(
2541
+ pdf,
2542
+ (p, l) => this.g._json((o) => this.ex().gp_verify_signatures(this.h, p, l, o))
2543
+ );
2544
+ }
1748
2545
  /**
1749
2546
  * Sign with a PKCS#12 (`.p12`/`.pfx`) identity — a CA-issued / eIDAS
1750
2547
  * certificate and its RSA key, imported natively (no external crypto). `opts`
@@ -2012,13 +2809,49 @@ var GigaPdfDoc = class {
2012
2809
  (p, l) => this.g._str((o) => this.ex().gp_get_metadata(this.h, p, l, o))
2013
2810
  );
2014
2811
  }
2015
- /** Set an Info-dictionary entry (e.g. "Title", "Author"). */
2812
+ /**
2813
+ * Set a **single** Info-dictionary entry (e.g. `"Title"`, `"Author"`). This
2814
+ * touches only `/Info`; use {@link setInfo} to update the typed fields and keep
2815
+ * the XMP `/Metadata` packet in sync.
2816
+ */
2016
2817
  setMetadata(key, value) {
2017
2818
  return this.g._withStr(
2018
2819
  key,
2019
2820
  (kP, kL) => this.g._withStr(value, (vP, vL) => this.ex().gp_set_metadata(this.h, kP, kL, vP, vL))
2020
2821
  ) === 0;
2021
2822
  }
2823
+ /**
2824
+ * The document's XMP metadata packet (catalog `/Metadata`, ISO 32000-1 §14.3.2)
2825
+ * as raw bytes, or `null` when the document carries no XMP.
2826
+ */
2827
+ getXmp() {
2828
+ const bytes = this.g._buffer((o) => this.ex().gp_get_xmp(this.h, o));
2829
+ return bytes.length === 0 ? null : bytes;
2830
+ }
2831
+ /**
2832
+ * Replace (or create) the document's XMP metadata stream (catalog `/Metadata`,
2833
+ * stored uncompressed). Accepts a UTF-8 string or raw bytes. Returns `true` on
2834
+ * success.
2835
+ */
2836
+ setXmp(xmp) {
2837
+ const bytes = typeof xmp === "string" ? new TextEncoder().encode(xmp) : xmp;
2838
+ return this.g._withBytes(bytes, (p, l) => this.ex().gp_set_xmp(this.h, p, l)) === 0;
2839
+ }
2840
+ /**
2841
+ * Set the standard document-information fields, writing **both** the `/Info`
2842
+ * dictionary and a synced XMP `/Metadata` packet so the two never drift. This is
2843
+ * a **partial** update — only the fields you provide are changed; omit a field
2844
+ * to leave it untouched. Returns `true` on success.
2845
+ *
2846
+ * @example
2847
+ * doc.setInfo({ title: "Annual Report", author: "Ada Lovelace", keywords: "finance, 2026" });
2848
+ */
2849
+ setInfo(fields) {
2850
+ return this.g._withStr(
2851
+ JSON.stringify(fields),
2852
+ (p, l) => this.ex().gp_set_info_json(this.h, p, l)
2853
+ ) === 0;
2854
+ }
2022
2855
  // annotations (Acrobat-style markup)
2023
2856
  annotations(page) {
2024
2857
  return this.g._json((o) => this.ex().gp_annotations_json(this.h, page, o));
@@ -2133,6 +2966,73 @@ var GigaPdfDoc = class {
2133
2966
  (p, l) => this.ex().gp_add_stamp(this.h, page, x0, y0, x1, y1, p, l, RGB(rgb))
2134
2967
  ) === 0;
2135
2968
  }
2969
+ /**
2970
+ * Add a `/Circle` (ellipse) annotation inscribed in `[x0,y0,x1,y1]`. `stroke`
2971
+ * (border) and `fill` (interior) are packed `0xRRGGBB` numbers, or `null` to
2972
+ * omit. Returns `true` on success.
2973
+ */
2974
+ addCircleAnnotation(page, x0, y0, x1, y1, stroke = 0, fill = null, lineWidth = 1) {
2975
+ return this.ex().gp_add_circle_annot(
2976
+ this.h,
2977
+ page,
2978
+ x0,
2979
+ y0,
2980
+ x1,
2981
+ y1,
2982
+ RGB(stroke ?? 0),
2983
+ stroke === null ? 0 : 1,
2984
+ RGB(fill ?? 0),
2985
+ fill === null ? 0 : 1,
2986
+ lineWidth
2987
+ ) === 0;
2988
+ }
2989
+ /**
2990
+ * Add a `/Polygon` annotation — a closed shape through `points` (a flat
2991
+ * `[x0, y0, x1, y1, …]` array, PDF user space), with optional `stroke`/`fill`
2992
+ * (`0xRRGGBB` or `null`). Returns `true` on success.
2993
+ */
2994
+ addPolygonAnnotation(page, points, stroke = 0, fill = null, lineWidth = 1) {
2995
+ return this.g._withF64(
2996
+ points,
2997
+ (p, c) => this.ex().gp_add_polygon_annot(
2998
+ this.h,
2999
+ page,
3000
+ p,
3001
+ c,
3002
+ RGB(stroke ?? 0),
3003
+ stroke === null ? 0 : 1,
3004
+ RGB(fill ?? 0),
3005
+ fill === null ? 0 : 1,
3006
+ lineWidth
3007
+ )
3008
+ ) === 0;
3009
+ }
3010
+ /**
3011
+ * Add a `/PolyLine` annotation — an open path through `points` (a flat
3012
+ * `[x0, y0, x1, y1, …]` array). `rgb` is packed `0xRRGGBB`.
3013
+ */
3014
+ addPolylineAnnotation(page, points, rgb = 0, lineWidth = 1) {
3015
+ return this.g._withF64(
3016
+ points,
3017
+ (p, c) => this.ex().gp_add_polyline_annot(this.h, page, p, c, RGB(rgb), lineWidth)
3018
+ ) === 0;
3019
+ }
3020
+ /**
3021
+ * Add a `/Caret` annotation — a small upward wedge in `[x0,y0,x1,y1]` marking
3022
+ * an insertion point. `rgb` is packed `0xRRGGBB`.
3023
+ */
3024
+ addCaretAnnotation(page, x0, y0, x1, y1, rgb = 0) {
3025
+ return this.ex().gp_add_caret_annot(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;
3026
+ }
3027
+ /**
3028
+ * Regenerate the appearance stream (`/AP /N`) of the 0-based `index`
3029
+ * annotation on `page` from its stored geometry, after editing its colour,
3030
+ * border or geometry. Returns `true` on success, `false` for a bad index or a
3031
+ * subtype whose appearance can't be reconstructed (FreeText/Stamp/Text/Link).
3032
+ */
3033
+ regenerateAppearance(page, index) {
3034
+ return this.ex().gp_regenerate_appearance(this.h, page, index) === 0;
3035
+ }
2136
3036
  flattenAnnotations(page) {
2137
3037
  return this.ex().gp_flatten_annotations(this.h, page);
2138
3038
  }
@@ -2201,6 +3101,150 @@ var GigaPdfDoc = class {
2201
3101
  data: this.g._fromBase64(dataBase64)
2202
3102
  }));
2203
3103
  }
3104
+ /**
3105
+ * Embed `bytes` as a document-level file attachment named `name`
3106
+ * (`/Names /EmbeddedFiles`, ISO 32000-1 §7.11.4). Re-using a `name` **replaces**
3107
+ * that attachment; the bytes are stored FlateDecode-compressed. Returns `true`
3108
+ * on success (`false` e.g. for an empty name).
3109
+ */
3110
+ addAttachment(name, bytes, opts = {}) {
3111
+ return this.g._withStr(
3112
+ name,
3113
+ (np, nl) => this.g._withBytes(
3114
+ bytes,
3115
+ (bp, bl) => this.g._withOptStr(
3116
+ opts.mime ?? "",
3117
+ (mp, ml) => this.g._withOptStr(
3118
+ opts.description ?? "",
3119
+ (dp, dl) => this.ex().gp_add_attachment(this.h, np, nl, bp, bl, mp, ml, dp, dl)
3120
+ )
3121
+ )
3122
+ )
3123
+ ) === 0;
3124
+ }
3125
+ /**
3126
+ * Embed `bytes` as an **associated file** (`/AF`, PDF/A-3) named `name` with the
3127
+ * given {@link AfRelationship} — the mechanism Factur-X / ZUGFeRD / Order-X use
3128
+ * to carry their invoice XML (`"alternative"`). The file is also a normal
3129
+ * attachment, is linked from the catalog `/AF` array, and its filespec carries
3130
+ * `/AFRelationship`. Returns `true` on success.
3131
+ */
3132
+ addAssociatedFile(name, bytes, relationship, opts = {}) {
3133
+ const rel = AF_RELATIONSHIP_CODE[relationship] ?? AF_RELATIONSHIP_CODE.unspecified;
3134
+ return this.g._withStr(
3135
+ name,
3136
+ (np, nl) => this.g._withBytes(
3137
+ bytes,
3138
+ (bp, bl) => this.g._withOptStr(
3139
+ opts.mime ?? "",
3140
+ (mp, ml) => this.g._withOptStr(
3141
+ opts.description ?? "",
3142
+ (dp, dl) => this.ex().gp_add_associated_file(this.h, np, nl, bp, bl, mp, ml, dp, dl, rel)
3143
+ )
3144
+ )
3145
+ )
3146
+ ) === 0;
3147
+ }
3148
+ /**
3149
+ * Remove the attachment named `name` (from `/Names /EmbeddedFiles` and, if
3150
+ * present, the catalog `/AF` array). Returns `true` if one was removed, `false`
3151
+ * if no attachment had that name.
3152
+ */
3153
+ removeAttachment(name) {
3154
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_attachment(this.h, p, l)) === 1;
3155
+ }
3156
+ /**
3157
+ * Mark this document as an embedded-file **portfolio** and configure how its
3158
+ * attachments are presented, by writing the catalog `/Collection`
3159
+ * (ISO 32000-1 §7.11.6, §12.3.5). The files must already be embedded (add them
3160
+ * first with {@link addAttachment} / {@link addAssociatedFile}); this only adds
3161
+ * the presentation layer: the initial {@link CollectionConfig.view view}, the
3162
+ * {@link CollectionConfig.schema schema} columns, the
3163
+ * {@link CollectionConfig.sort sort} order, the
3164
+ * {@link CollectionConfig.defaultFile default file}, and per-file
3165
+ * {@link CollectionConfig.items column values} (each written as a `/CI` on the
3166
+ * matching file's filespec). An empty/omitted schema still produces a valid
3167
+ * `/Collection`. Calling again **replaces** the previous configuration. Returns
3168
+ * `true` on success (`false` on a malformed config or write error).
3169
+ */
3170
+ setCollection(config) {
3171
+ return this.g._withStr(
3172
+ JSON.stringify(config),
3173
+ (p, l) => this.ex().gp_set_collection_json(this.h, p, l)
3174
+ ) === 0;
3175
+ }
3176
+ /**
3177
+ * Read this document's portfolio configuration back from the catalog
3178
+ * `/Collection` — the reader counterpart of {@link setCollection}. Returns
3179
+ * `null` when the document is not a portfolio. The recovered
3180
+ * {@link CollectionConfig} carries the `view`, the `schema` columns (sorted by
3181
+ * order), the `sort`, the `defaultFile`, and each embedded file's `/CI` column
3182
+ * `values`.
3183
+ */
3184
+ collection() {
3185
+ return this.g._json((o) => this.ex().gp_collection_json(this.h, o));
3186
+ }
3187
+ /**
3188
+ * Install a **document-level JavaScript** under the catalog `/Names /JavaScript`
3189
+ * name tree (ISO 32000-1 §7.7.3.4 + §12.6.4.16): a named JavaScript action
3190
+ * (`<< /S /JavaScript /JS … >>`) keyed by `name`. On open, a conforming viewer
3191
+ * runs every document-level script in **name (lexical) order** — this is where
3192
+ * form-calculation / validation helper libraries live (e.g. `AFNumber_Format`).
3193
+ * Re-using a `name` **replaces** that script; long sources are stored as a
3194
+ * FlateDecode stream, and sibling `/Names` subtrees (`/EmbeddedFiles`,
3195
+ * `/Dests`, …) are preserved. Returns `true` on success (`false` e.g. for an
3196
+ * empty name).
3197
+ */
3198
+ addDocumentJavascript(name, script) {
3199
+ return this.g._withStr(
3200
+ name,
3201
+ (np, nl) => this.g._withStr(
3202
+ script,
3203
+ (sp, sl) => this.ex().gp_add_document_javascript(this.h, np, nl, sp, sl)
3204
+ )
3205
+ ) === 0;
3206
+ }
3207
+ /**
3208
+ * Every document-level JavaScript as `{ name, script }` pairs, in name
3209
+ * (lexical) order — the read side of {@link addDocumentJavascript} (decodes
3210
+ * both a literal `/JS` string and a `/JS` stream).
3211
+ */
3212
+ documentJavascripts() {
3213
+ return this.g._json((o) => this.ex().gp_document_javascripts_json(this.h, o));
3214
+ }
3215
+ /**
3216
+ * Remove the document-level JavaScript named `name` from `/Names /JavaScript`.
3217
+ * Returns `true` if one was removed, `false` if none had that name.
3218
+ */
3219
+ removeDocumentJavascript(name) {
3220
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_document_javascript(this.h, p, l)) === 1;
3221
+ }
3222
+ /**
3223
+ * Add a page-anchored **FileAttachment** annotation over `rect` on the 1-based
3224
+ * `page`, pointing at the already-embedded attachment `name` (add it first with
3225
+ * {@link addAttachment}). `icon` is the visual marker (default `"PushPin"`).
3226
+ * Returns `true` on success (`false` if no such attachment exists).
3227
+ */
3228
+ addFileAttachmentAnnot(page, rect, name, icon = "PushPin") {
3229
+ return this.g._withStr(
3230
+ name,
3231
+ (np, nl) => this.g._withOptStr(
3232
+ icon,
3233
+ (ip, il) => this.ex().gp_add_file_attachment_annot(
3234
+ this.h,
3235
+ page,
3236
+ rect.x,
3237
+ rect.y,
3238
+ rect.x + rect.w,
3239
+ rect.y + rect.h,
3240
+ np,
3241
+ nl,
3242
+ ip,
3243
+ il
3244
+ )
3245
+ )
3246
+ ) === 0;
3247
+ }
2204
3248
  /**
2205
3249
  * Add an internal hyperlink over a rectangle that jumps to the named
2206
3250
  * destination `name` (define it with {@link addNamedDest}). Unlike
@@ -2230,6 +3274,24 @@ var GigaPdfDoc = class {
2230
3274
  removeLayer(id) {
2231
3275
  return this.ex().gp_remove_layer(this.h, id) === 0;
2232
3276
  }
3277
+ /**
3278
+ * Begin an optional-content marked-content sequence on `page` for the layer
3279
+ * `ocg` (its id, from {@link addLayer}). Registers the OCG under the page's
3280
+ * `/Resources /Properties` and appends `/OC /OCn BDC` to the content stream;
3281
+ * every drawing call after it ({@link addText}, {@link addRectangle},
3282
+ * {@link addImage}, …) is gated on that layer's visibility until the matching
3283
+ * {@link endOptionalContent} appends `EMC`. Calls nest. Returns the `OCn`
3284
+ * property name (empty string on error).
3285
+ */
3286
+ beginOptionalContent(page, ocg) {
3287
+ return this.g._str(
3288
+ (o) => this.ex().gp_begin_optional_content(this.h, page, ocg, o)
3289
+ );
3290
+ }
3291
+ /** End the innermost optional-content sequence on `page` (`EMC`). */
3292
+ endOptionalContent(page) {
3293
+ return this.ex().gp_end_optional_content(this.h, page) === 0;
3294
+ }
2233
3295
  // outline (bookmarks)
2234
3296
  outline() {
2235
3297
  return this.g._json((o) => this.ex().gp_outline_json(this.h, o));
@@ -2239,6 +3301,79 @@ var GigaPdfDoc = class {
2239
3301
  const text = entries.map((e) => `${e.level} ${e.page ?? 0} ${e.title}`).join("\n");
2240
3302
  return this.g._withStr(text, (p, l) => this.ex().gp_set_outline(this.h, p, l)) === 0;
2241
3303
  }
3304
+ /**
3305
+ * Add a `/Link` annotation over `rect` (`{ x, y, w, h }`) carrying any
3306
+ * {@link Action} — the full action & destination model (GoTo with every fit
3307
+ * mode, GoToR, URI, Named navigation, Launch, JavaScript, SubmitForm,
3308
+ * ResetForm). Returns `true` on success (`false` for a malformed action).
3309
+ *
3310
+ * @example
3311
+ * doc.addLink(1, { x: 72, y: 700, w: 120, h: 16 },
3312
+ * { type: "goto", dest: { fit: "xyz", page: 4, top: 720, zoom: 1.5 } });
3313
+ */
3314
+ addLink(page, rect, action) {
3315
+ return this.g._withStr(
3316
+ JSON.stringify(action),
3317
+ (p, l) => this.ex().gp_add_link(this.h, page, rect.x, rect.y, rect.x + rect.w, rect.y + rect.h, p, l)
3318
+ ) === 0;
3319
+ }
3320
+ /**
3321
+ * Set the document `/OpenAction` — the {@link Action} performed when the file
3322
+ * is opened. Returns `true` on success.
3323
+ */
3324
+ setOpenAction(action) {
3325
+ return this.g._withStr(
3326
+ JSON.stringify(action),
3327
+ (p, l) => this.ex().gp_set_open_action(this.h, p, l)
3328
+ ) === 0;
3329
+ }
3330
+ /**
3331
+ * Remove the `linkIndex`-th `/Link` annotation on `page` (links counted in
3332
+ * order, ignoring non-link annotations). Returns `true` if one was removed.
3333
+ */
3334
+ removeLink(page, linkIndex) {
3335
+ return this.ex().gp_remove_link(this.h, page, linkIndex) === 1;
3336
+ }
3337
+ /**
3338
+ * Replace the outline with {@link Bookmark}s that may carry actions (a `goto`
3339
+ * action becomes a `/Dest`, any other action an `/A`). An empty array clears
3340
+ * the outline. Returns `true` on success.
3341
+ */
3342
+ setBookmarks(bookmarks) {
3343
+ const text = bookmarks.map((b) => `${b.level} ${b.title} ${b.action ? JSON.stringify(b.action) : ""}`).join("\n");
3344
+ return this.g._withOptStr(text, (p, l) => this.ex().gp_set_bookmarks(this.h, p, l)) === 0;
3345
+ }
3346
+ // catalog reading / UX hints (ViewerPreferences, PageLayout, PageMode)
3347
+ /**
3348
+ * Write the catalog `/ViewerPreferences` (ISO 32000-1 §12.2). Each omitted
3349
+ * field is left unchanged; a boolean sets the key. After applying, an empty
3350
+ * dictionary is removed. Returns `false` on an invalid `direction`.
3351
+ */
3352
+ setViewerPreferences(prefs) {
3353
+ const tri = (v) => v === void 0 ? -1 : v ? 1 : 0;
3354
+ return this.g._withStr(
3355
+ prefs.direction ?? "",
3356
+ (dP, dL) => this.ex().gp_set_viewer_preferences(
3357
+ this.h,
3358
+ tri(prefs.hideToolbar),
3359
+ tri(prefs.hideMenubar),
3360
+ tri(prefs.hideWindowUI),
3361
+ tri(prefs.fitWindow),
3362
+ tri(prefs.centerWindow),
3363
+ tri(prefs.displayDocTitle),
3364
+ dP,
3365
+ dL
3366
+ )
3367
+ ) === 0;
3368
+ }
3369
+ /** Set the catalog `/PageLayout`. `null` removes the key. Returns `false` on an unknown name. */
3370
+ setPageLayout(layout) {
3371
+ return this.g._withStr(layout ?? "", (p, l) => this.ex().gp_set_page_layout(this.h, p, l)) === 0;
3372
+ }
3373
+ /** Set the catalog `/PageMode`. `null` removes the key. Returns `false` on an unknown name. */
3374
+ setPageMode(mode) {
3375
+ return this.g._withStr(mode ?? "", (p, l) => this.ex().gp_set_page_mode(this.h, p, l)) === 0;
3376
+ }
2242
3377
  // interactive forms (AcroForm)
2243
3378
  fields() {
2244
3379
  return this.g._json((o) => this.ex().gp_fields_json(this.h, o));
@@ -2400,10 +3535,79 @@ var GigaPdfDoc = class {
2400
3535
  )
2401
3536
  ) === 0;
2402
3537
  }
3538
+ /**
3539
+ * Create a **visible signature field** (`/FT /Sig`) over `rect` — an empty
3540
+ * widget the signing pipeline can later target — and flag the AcroForm
3541
+ * `/SigFlags`. Returns `true` on success.
3542
+ */
3543
+ addSignatureField(page, name, rect, opts = {}) {
3544
+ const st = styleArgs(opts.style);
3545
+ return this.g._withStr(
3546
+ name,
3547
+ (nP, nL) => this.ex().gp_add_signature_field(
3548
+ this.h,
3549
+ page,
3550
+ nP,
3551
+ nL,
3552
+ rect[0],
3553
+ rect[1],
3554
+ rect[2],
3555
+ rect[3],
3556
+ ...st
3557
+ )
3558
+ ) === 0;
3559
+ }
3560
+ /**
3561
+ * Attach field-level JavaScript to a field's `/AA` for the given `trigger`
3562
+ * (`"keystroke"` filters input, `"format"` formats display, `"validate"`
3563
+ * checks on change, `"calculate"` recomputes — ordered by
3564
+ * {@link setCalculationOrder}). Returns `true` if set, `false` if no field has
3565
+ * that name.
3566
+ */
3567
+ setFieldScript(name, trigger, js) {
3568
+ return this.g._withStr(
3569
+ name,
3570
+ (nP, nL) => this.g._withStr(
3571
+ trigger,
3572
+ (tP, tL) => this.g._withStr(
3573
+ js,
3574
+ (jP, jL) => this.ex().gp_set_field_script(this.h, nP, nL, tP, tL, jP, jL)
3575
+ )
3576
+ )
3577
+ ) === 1;
3578
+ }
3579
+ /**
3580
+ * Set the AcroForm calculation order (`/CO`) — the sequence in which fields
3581
+ * with a `calculate` script recompute. Unknown names are skipped.
3582
+ */
3583
+ setCalculationOrder(names) {
3584
+ return this.g._withOptStr(
3585
+ names.join("\n"),
3586
+ (p, l) => this.ex().gp_set_calculation_order(this.h, p, l)
3587
+ ) === 0;
3588
+ }
3589
+ /**
3590
+ * Delete a form field by name (removed from `/Fields`, `/CO` and every page's
3591
+ * annotations). Returns `true` if a field was removed.
3592
+ */
3593
+ removeField(name) {
3594
+ return this.g._withStr(name, (p, l) => this.ex().gp_remove_field(this.h, p, l)) === 1;
3595
+ }
3596
+ /**
3597
+ * Rebuild a field's appearance from its current value/style — call after
3598
+ * changing a field's value programmatically. Returns `true` if regenerated
3599
+ * (`false` for an unknown name or a kind that can't be regenerated alone, e.g.
3600
+ * a radio parent with kids).
3601
+ */
3602
+ regenerateFieldAppearance(name) {
3603
+ return this.g._withStr(name, (p, l) => this.ex().gp_regenerate_field_appearance(this.h, p, l)) === 1;
3604
+ }
2403
3605
  };
2404
3606
  export {
2405
3607
  GigaPdfDoc,
2406
3608
  GigaPdfEngine,
3609
+ PAGE_BOX_KINDS,
3610
+ PAGE_TRANSITION_STYLES,
2407
3611
  defaultCrlGet,
2408
3612
  defaultOcspPost,
2409
3613
  defaultTsaPost