@evotecit/officeimo 0.1.1 → 0.1.3

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.
Files changed (43) hide show
  1. package/README.md +43 -49
  2. package/bundles/officeimo-canopyx.js +1047 -193
  3. package/bundles/officeimo-canopyx.mjs +958 -111
  4. package/bundles/officeimo-csv.js +18 -15
  5. package/bundles/officeimo-csv.mjs +16 -13
  6. package/bundles/officeimo-datatables.js +249 -153
  7. package/bundles/officeimo-datatables.mjs +169 -73
  8. package/bundles/officeimo-pdf.js +151 -67
  9. package/bundles/officeimo-pdf.mjs +127 -43
  10. package/bundles/officeimo-xlsx.js +78 -69
  11. package/bundles/officeimo-xlsx.mjs +26 -17
  12. package/bundles/officeimo.js +249 -153
  13. package/bundles/officeimo.mjs +169 -73
  14. package/dist/csv/index.js +16 -13
  15. package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
  16. package/dist/integrations/canopyx/diagnostics.js +17 -0
  17. package/dist/integrations/canopyx/grouping.d.ts +6 -0
  18. package/dist/integrations/canopyx/grouping.js +188 -0
  19. package/dist/integrations/canopyx/index.d.ts +2 -2
  20. package/dist/integrations/canopyx/index.js +72 -15
  21. package/dist/integrations/canopyx/metadata.d.ts +4 -0
  22. package/dist/integrations/canopyx/metadata.js +51 -0
  23. package/dist/integrations/canopyx/presentation.d.ts +8 -0
  24. package/dist/integrations/canopyx/presentation.js +40 -0
  25. package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
  26. package/dist/integrations/canopyx/rule-predicates.js +110 -0
  27. package/dist/integrations/canopyx/rules.d.ts +6 -0
  28. package/dist/integrations/canopyx/rules.js +176 -0
  29. package/dist/integrations/canopyx/source.js +24 -22
  30. package/dist/integrations/canopyx/types.d.ts +89 -8
  31. package/dist/integrations/canopyx/workbook.d.ts +6 -0
  32. package/dist/integrations/canopyx/workbook.js +52 -0
  33. package/dist/opc/index.js +14 -9
  34. package/dist/pdf/font-resources.js +33 -14
  35. package/dist/pdf/pages.js +63 -16
  36. package/dist/pdf/table-band-flow.js +7 -2
  37. package/dist/pdf/table-band-plan.js +9 -1
  38. package/dist/pdf/table-layout.js +6 -2
  39. package/dist/pdf/table-structure.js +9 -8
  40. package/dist/xlsx/workbook.js +7 -4
  41. package/dist/xlsx/worksheet.js +2 -1
  42. package/dist/xml/index.js +3 -3
  43. package/package.json +1 -1
@@ -1111,29 +1111,32 @@ const { captureCsvOptions } = _m19;
1111
1111
 
1112
1112
 
1113
1113
 
1114
- function csvField(value, delimiter, protect, quote, booleanText, nullValue) {
1115
- if (value == null && nullValue !== undefined)
1116
- value = nullValue;
1114
+ function csvField(value, delimiter, protect, quote, booleanText) {
1115
+ const kind = typeof value;
1117
1116
  let text;
1118
1117
  if (value == null)
1119
1118
  text = "";
1119
+ else if (kind === "string")
1120
+ text = value;
1121
+ else if (kind === "number") {
1122
+ text = Number.isFinite(value) ? String(value) : "";
1123
+ // Numeric text has no CSV delimiter, quote or line break to escape.
1124
+ return quote === "all" ? '"' + text + '"' : text;
1125
+ }
1126
+ else if (kind === "boolean")
1127
+ text = booleanText[value ? "true" : "false"];
1120
1128
  else if (isDate(value))
1121
1129
  text = Number.isFinite(value.getTime()) ? value.toISOString() : "";
1122
- else if (typeof value === "boolean")
1123
- text = booleanText[value ? "true" : "false"];
1124
- else if (typeof value === "number")
1125
- text = Number.isFinite(value) ? String(value) : "";
1126
- else if (typeof value === "string")
1127
- text = value;
1128
1130
  else {
1129
1131
  if (typeof value.then === "function")
1130
1132
  void Promise.resolve(value).catch(() => { });
1131
1133
  throw new TypeError("CSV cells and formatter results must be synchronous strings, numbers, booleans, Dates or null.");
1132
1134
  }
1133
- if (protect && (typeof value === "string" || typeof value === "boolean") && /^ *[=+\-@\t\r\n]/.test(text))
1135
+ // Only ASCII spaces, controls and markers through @ can begin the protected prefix.
1136
+ if (protect && (kind === "string" || kind === "boolean") && text.charCodeAt(0) <= 64 && /^ *[=+\-@\t\r\n]/.test(text))
1134
1137
  text = "'" + text;
1135
- return quote === "all" || (quote === "strings" && typeof value === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
1136
- ? '"' + text.replace(/"/g, '""') + '"' : text;
1138
+ return quote === "all" || (quote === "strings" && kind === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
1139
+ ? '"' + (text.includes('"') ? text.replace(/"/g, '""') : text) + '"' : text;
1137
1140
  }
1138
1141
  async function writeCsvTo(rows, destination, configuration) {
1139
1142
  const options = captureCsvOptions(configuration);
@@ -1185,7 +1188,7 @@ async function write(rows, sink, options) {
1185
1188
  value = options.nullValue;
1186
1189
  budget.cell(typeof value === "boolean" ? booleanText[value ? "true" : "false"] : value);
1187
1190
  checkAbort(signal);
1188
- text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText, options.nullValue);
1191
+ text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText);
1189
1192
  if (text.length >= buffer.chunkSize || (i & 127) === 127 && taskYieldDue()) {
1190
1193
  if (buffer.append(text))
1191
1194
  return buffer.flush().then(() => record(values, header, i + 1, snapshot));
@@ -1289,6 +1292,8 @@ const { OfficeIMOError } = _m2;
1289
1292
  const { ChunkedTextSink } = _m3;
1290
1293
 
1291
1294
  const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
1295
+ const xmlEscapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1296
+ "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1292
1297
  /** XML 1.0 characters; Unicode mode retains valid surrogate pairs. */
1293
1298
  function cleanXml(value, policy = "strip") {
1294
1299
  if (policy !== "strip" && policy !== "reject")
@@ -1300,9 +1305,7 @@ function cleanXml(value, policy = "strip") {
1300
1305
  }
1301
1306
  /** Escape data, including whitespace that XML parsers otherwise normalize. */
1302
1307
  function escapeXml(value, policy = "strip") {
1303
- const escapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;",
1304
- "\r": "&#13;", "\n": "&#10;", "\t": "&#9;" };
1305
- return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => escapes[c]);
1308
+ return cleanXml(value, policy).replace(/[&<>"'\r\n\t]/g, c => xmlEscapes[c]);
1306
1309
  }
1307
1310
  /** Encode an OOXML ST_Xstring attribute without interpreting literal escape tokens as characters. */
1308
1311
  function escapeOoxmlAttribute(value, policy = "strip") {
@@ -1900,8 +1903,11 @@ class OpcPackage {
1900
1903
  return uri;
1901
1904
  }
1902
1905
  addPart(part) {
1903
- const uri = this.reserve(part.uri, part.contentType);
1904
- this.parts.set(uri.toLowerCase(), { ...part, uri, data: part.data instanceof Uint8Array ? new Uint8Array(part.data) : part.data });
1906
+ const { uri: requestedUri, contentType, data } = part;
1907
+ // Structural accessors and byte ownership are captured before reserving metadata.
1908
+ const capturedData = data instanceof Uint8Array ? new Uint8Array(data) : data;
1909
+ const uri = this.reserve(requestedUri, contentType);
1910
+ this.parts.set(uri.toLowerCase(), { uri, contentType, data: capturedData });
1905
1911
  }
1906
1912
  /** @internal */
1907
1913
  addPrepared(uri, type, prepared) {
@@ -1926,17 +1932,19 @@ class OpcPackage {
1926
1932
  checkAbort(this.options.signal);
1927
1933
  this.open();
1928
1934
  source = source === "/" ? source : partUri(source);
1929
- if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(relationship.id))
1935
+ const { id, type, target: requestedTarget, external } = relationship;
1936
+ this.open();
1937
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(id))
1930
1938
  throw new TypeError("Relationship id must be an XML ID.");
1931
- if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(relationship.type))
1939
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(type))
1932
1940
  throw new TypeError("Relationship type must be an absolute URI.");
1933
- const target = relationship.external ? relationship.target : partUri(relationship.target);
1934
- if (relationship.external && (!target || /[\u0000-\u0020]/.test(target)))
1941
+ const target = external ? requestedTarget : partUri(requestedTarget);
1942
+ if (external && (!target || /[\u0000-\u0020]/.test(target)))
1935
1943
  throw new TypeError("Invalid external relationship target.");
1936
1944
  const key = source.toLowerCase(), list = this.relationships.get(key) ?? new Map();
1937
- if (list.has(relationship.id))
1938
- throw new TypeError("Duplicate relationship id: " + relationship.id);
1939
- list.set(relationship.id, { ...relationship, target });
1945
+ if (list.has(id))
1946
+ throw new TypeError("Duplicate relationship id: " + id);
1947
+ list.set(id, { id, type, target, ...(external === undefined ? {} : { external }) });
1940
1948
  this.relationships.set(key, list);
1941
1949
  }
1942
1950
  setProperties(core = {}, app = {}) {
@@ -3747,7 +3755,8 @@ class Worksheet {
3747
3755
  });
3748
3756
  const originalCharacters = typeof value === "string" ? value.length : 0;
3749
3757
  let reservedCharacters = this.preserved || header || footer ? originalCharacters : undefined;
3750
- if (type === "string" && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3758
+ // Cleaning removes characters; ordinary strings cannot cross Excel's limit.
3759
+ if (type === "string" && originalCharacters > 32767 && cleanXml(value, this.book.settings.invalidCharacterPolicy).length > 32767) {
3751
3760
  const cell = col.letter + row;
3752
3761
  if (link || this.linkedCells.has(cell))
3753
3762
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
@@ -4967,12 +4976,15 @@ class Workbook {
4967
4976
  });
4968
4977
  }
4969
4978
  addPart(part) {
4979
+ this.assertOpen();
4980
+ const { uri, contentType, data, relationship } = part;
4981
+ const capturedRelationship = relationship && { id: relationship.id, type: relationship.type, source: relationship.source };
4970
4982
  this.assertOpen();
4971
4983
  // Reserve now so collisions and invalid names fail at the call site.
4972
- this.package.addPart(part);
4973
- if (part.relationship) {
4974
- const { source, ...rel } = part.relationship;
4975
- this.package.addRelationship(source ?? "/xl/workbook.xml", { ...rel, target: part.uri });
4984
+ this.package.addPart({ uri, contentType, data });
4985
+ if (capturedRelationship) {
4986
+ const { source, id, type } = capturedRelationship;
4987
+ this.package.addRelationship(source ?? "/xl/workbook.xml", { id, type, target: uri });
4976
4988
  }
4977
4989
  }
4978
4990
  /** Complete the archive and return counts. Does not close or dispose a caller-owned sink. */
@@ -7132,7 +7144,8 @@ const { pdfNumber, unicodeHex } = _m59;
7132
7144
 
7133
7145
  const { checkAbort, pause, taskYieldDue } = _m4;
7134
7146
 
7135
- const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7147
+ const hexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7148
+ function cidHex(cid) { return hexBytes[cid >>> 8] + hexBytes[cid & 255]; }
7136
7149
  class PdfFontResource {
7137
7150
  index;
7138
7151
  bold;
@@ -7163,12 +7176,16 @@ class PdfFontResource {
7163
7176
  width(scalar) {
7164
7177
  if (this.shared)
7165
7178
  return this.shared.width(scalar);
7166
- const existing = this.mappings.get(scalar);
7167
- if (existing)
7168
- return existing.width;
7169
- const standard = this.standardWidths.get(scalar);
7170
- if (standard !== undefined)
7171
- return standard;
7179
+ if (this.program) {
7180
+ const existing = this.mappings.get(scalar);
7181
+ if (existing)
7182
+ return existing.width;
7183
+ }
7184
+ else {
7185
+ const standard = this.standardWidths.get(scalar);
7186
+ if (standard !== undefined)
7187
+ return standard;
7188
+ }
7172
7189
  const resolved = resolveScalar(scalar, this.program, this.bold);
7173
7190
  if (!resolved.supported) {
7174
7191
  if (resolved.code === "unpaired-surrogate")
@@ -7181,7 +7198,8 @@ class PdfFontResource {
7181
7198
  }
7182
7199
  if (this.mappings.size >= 65535)
7183
7200
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct Unicode scalars.");
7184
- const mapping = { cid: this.mappings.size + 1, glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7201
+ const cid = this.mappings.size + 1;
7202
+ const mapping = { cid, hex: cidHex(cid), glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7185
7203
  this.mappings.set(scalar, mapping);
7186
7204
  return mapping.width;
7187
7205
  }
@@ -7194,8 +7212,20 @@ class PdfFontResource {
7194
7212
  let hex = "";
7195
7213
  for (const char of text) {
7196
7214
  const cp = char.codePointAt(0);
7197
- this.width(cp);
7198
- hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
7215
+ if (this.program) {
7216
+ let mapping = this.mappings.get(cp);
7217
+ // Layout normally registered the scalar already; validate only a newly painted scalar.
7218
+ if (!mapping) {
7219
+ this.width(cp);
7220
+ mapping = this.mappings.get(cp);
7221
+ }
7222
+ hex += mapping.hex;
7223
+ }
7224
+ else {
7225
+ if (!this.standardWidths.has(cp))
7226
+ this.width(cp);
7227
+ hex += hexBytes[standardCode(cp)];
7228
+ }
7199
7229
  }
7200
7230
  return "<" + hex + ">";
7201
7231
  }
@@ -7210,10 +7240,11 @@ class PdfFontResource {
7210
7240
  if (!mapping) {
7211
7241
  if (this.mappings.size >= 65535)
7212
7242
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct CID mappings.");
7213
- mapping = { cid: this.mappings.size + 1, glyph, width: this.program.widths[glyph], text };
7243
+ const cid = this.mappings.size + 1;
7244
+ mapping = { cid, hex: cidHex(cid), glyph, width: this.program.widths[glyph], text };
7214
7245
  this.mappings.set(key, mapping);
7215
7246
  }
7216
- return "<" + mapping.cid.toString(16).padStart(4, "0") + ">";
7247
+ return "<" + mapping.hex + ">";
7217
7248
  }
7218
7249
  async write(objects, compression) {
7219
7250
  checkAbort(this.signal);
@@ -7262,7 +7293,7 @@ class PdfFontResource {
7262
7293
  const batch = mapped.slice(i, i + 100);
7263
7294
  cmap += batch.length + " beginbfchar\n";
7264
7295
  for (const [, m] of batch)
7265
- cmap += "<" + m.cid.toString(16).padStart(4, "0") + "> <" + unicodeHex(m.text) + ">\n";
7296
+ cmap += "<" + m.hex + "> <" + unicodeHex(m.text) + ">\n";
7266
7297
  cmap += "endbfchar\n";
7267
7298
  if (taskYieldDue())
7268
7299
  await pause();
@@ -7313,7 +7344,7 @@ class PdfFontResources {
7313
7344
  if (!found)
7314
7345
  this.explicitSelections.set(explicit, selections);
7315
7346
  }
7316
- const key = String(bold) + String(italic), existing = selections.get(key);
7347
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7317
7348
  if (existing)
7318
7349
  return existing;
7319
7350
  const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
@@ -7899,6 +7930,14 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
7899
7930
  for (const row of rows) {
7900
7931
  const cells = [];
7901
7932
  for (const cell of row.cells) {
7933
+ // Ordinary data and leaf headings keep their captured width and lines in every band.
7934
+ // Look up their physical position without allocating another per-row column index.
7935
+ if (cell.span === 1) {
7936
+ const first = band.columns.indexOf(cell.first);
7937
+ if (first >= 0)
7938
+ cells.push({ ...cell, source: cell.source ?? cell, first });
7939
+ continue;
7940
+ }
7902
7941
  for (let first = 0; first < band.columns.length;) {
7903
7942
  const source = band.columns[first];
7904
7943
  if (source < cell.first || source >= cell.first + cell.span) {
@@ -7909,7 +7948,7 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
7909
7948
  while (end < band.columns.length && band.columns[end] === band.columns[end - 1] + 1 && band.columns[end] < cell.first + cell.span)
7910
7949
  end++;
7911
7950
  const width = band.columns.slice(first, end).reduce((sum, index) => sum + widths[index], 0);
7912
- const lines = cell.span === 1 ? cell.lines : await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
7951
+ const lines = await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
7913
7952
  cells.push({ ...cell, source: cell.source ?? cell, first, span: end - first, width, lines,
7914
7953
  lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), cell.font.lineHeight(settings.fontSize)) });
7915
7954
  first = end;
@@ -8061,8 +8100,12 @@ class PdfTableLayout {
8061
8100
  lines };
8062
8101
  }
8063
8102
  row(cells) {
8064
- const lines = Math.max(1, ...cells.map(c => c.lines.length));
8065
- const lineHeight = Math.max(this.lineHeight, ...cells.map(c => c.lineHeight));
8103
+ let lines = 1, lineHeight = this.lineHeight;
8104
+ for (let index = 0; index < cells.length; index++) {
8105
+ const cell = cells[index];
8106
+ lines = Math.max(lines, cell.lines.length);
8107
+ lineHeight = Math.max(lineHeight, cell.lineHeight);
8108
+ }
8066
8109
  return { cells, lines, lineHeight, height: lines * lineHeight + this.settings.padding * 2 };
8067
8110
  }
8068
8111
  async headers() {
@@ -8215,7 +8258,7 @@ class PdfTableBandFlow {
8215
8258
  await this.flush();
8216
8259
  }
8217
8260
  async row(row, allowFirstFragment = false) {
8218
- const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
8261
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = minimumLines * row.lineHeight + padding * 2;
8219
8262
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
8220
8263
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
8221
8264
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -8249,9 +8292,14 @@ class PdfTableBandFlow {
8249
8292
  let remaining = false;
8250
8293
  const cells = rows[0].cells.map(cell => {
8251
8294
  const source = this.layout.bands[index].columns[cell.first];
8252
- const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
8295
+ const repeated = this.layout.repeatedColumn(source), reusable = cell.span === 1 && (cell.source?.span ?? 1) === 1 && (cell.rowSpan ?? 1) === 1 &&
8296
+ cell.height === undefined && first === 0 && (repeated || lines >= cell.lines.length);
8297
+ const visible = repeated || reusable ? cell.lines : cell.lines.slice(first, first + lines);
8253
8298
  if (!repeated && (visible.length > 0 || cell.link !== undefined))
8254
8299
  remaining = true;
8300
+ // A complete first fragment already owns these lines and their maximum font metrics.
8301
+ if (reusable)
8302
+ return cell;
8255
8303
  const { height: _height, ...plain } = cell;
8256
8304
  return { ...plain, lines: visible,
8257
8305
  lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
@@ -8359,30 +8407,31 @@ class PdfTableStructure {
8359
8407
  return row.cells.map(cell => this.cells.get(cell));
8360
8408
  const rowId = this.structure.element("TR", parent);
8361
8409
  this.rows.set(row, rowId);
8362
- const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
8363
8410
  // Allocate in source order, then resolve every row header before associating even earlier data cells.
8364
8411
  // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
8365
8412
  const ids = row.cells.map((cell, index) => {
8366
- const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
8413
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8414
+ const id = this.structure.element(header ? "TH" : "TD", rowId);
8367
8415
  this.cells.set(cell, id);
8368
8416
  return id;
8369
8417
  });
8370
- const rowHeaders = [];
8418
+ let rowHeaders;
8371
8419
  for (let index = 0; index < ids.length; index++)
8372
- if (headers[index])
8373
- rowHeaders.push(await this.structure.identifier(ids[index]));
8420
+ if (rowHeaderIndex === undefined ? row.cells[index].rowHeader === true : index === rowHeaderIndex)
8421
+ (rowHeaders ??= []).push(await this.structure.identifier(ids[index]));
8374
8422
  for (let index = 0; index < row.cells.length; index++) {
8375
8423
  const cell = row.cells[index];
8376
- if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8424
+ if (!rowHeaders && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8377
8425
  const attributes = this.ordinaryAttributes[cell.first] ??=
8378
8426
  await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
8379
8427
  this.structure.setAttributes(ids[index], attributes);
8380
8428
  continue;
8381
8429
  }
8382
8430
  const associations = this.associations(cell);
8383
- if (!headers[index])
8431
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8432
+ if (!header && rowHeaders)
8384
8433
  associations.push(...rowHeaders);
8385
- this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
8434
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, header ? "Row" : undefined));
8386
8435
  }
8387
8436
  return ids;
8388
8437
  }
@@ -8566,7 +8615,8 @@ class PdfPages {
8566
8615
  outlines;
8567
8616
  references = [];
8568
8617
  current = 0;
8569
- commands = [];
8618
+ commands = "";
8619
+ commandParts = [];
8570
8620
  commandBytes = 0;
8571
8621
  annotations = [];
8572
8622
  hyperlinks = 0;
@@ -8584,6 +8634,12 @@ class PdfPages {
8584
8634
  pendingBookmarks = [];
8585
8635
  pageNumberWidth = 0;
8586
8636
  colors = new Map();
8637
+ textFont;
8638
+ textSize = 0;
8639
+ textColor = "";
8640
+ textPrefix = "";
8641
+ rectangleLefts;
8642
+ rectangleColumns = [];
8587
8643
  externalObjects = new Map();
8588
8644
  bandFlow;
8589
8645
  bandCellBudget = false;
@@ -8650,7 +8706,7 @@ class PdfPages {
8650
8706
  }
8651
8707
  add(command) {
8652
8708
  this.retainPageBytes(command.length);
8653
- this.commands.push(command);
8709
+ this.commands += command;
8654
8710
  }
8655
8711
  retainPageBytes(length) {
8656
8712
  this.commandBytes += length;
@@ -8670,9 +8726,17 @@ class PdfPages {
8670
8726
  return this.structure ? "/Artifact << /Type /" + type + " >> BDC\n" + command + "EMC\n" : command;
8671
8727
  }
8672
8728
  text(text, font, size, x, baseline, foreground = "111827", element) {
8673
- const n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8674
- const command = "q " + this.rgb(foreground) + " rg " + this.rgb(foreground) + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8675
- (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 " + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8729
+ const n = pdfNumber;
8730
+ if (font !== this.textFont || size !== this.textSize || foreground !== this.textColor) {
8731
+ const shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(foreground);
8732
+ // Keep one prefix, independent of report size. Resource identity includes synthetic styling.
8733
+ this.textPrefix = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8734
+ (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 ";
8735
+ this.textFont = font;
8736
+ this.textSize = size;
8737
+ this.textColor = foreground;
8738
+ }
8739
+ const command = this.textPrefix + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8676
8740
  this.add(this.structure && element !== undefined ? this.structure.mark(element) + command + "EMC\n" : this.artifact(command, "Pagination"));
8677
8741
  }
8678
8742
  link(link, x, bottom, width, height, element) {
@@ -8702,8 +8766,8 @@ class PdfPages {
8702
8766
  for (const segment of line.segments) {
8703
8767
  const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8704
8768
  if (segment.glyphs) {
8705
- const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8706
- let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8769
+ const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(segment.color ?? "111827");
8770
+ let cursor = x, command = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8707
8771
  (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ");
8708
8772
  for (const glyph of segment.glyphs) {
8709
8773
  command += "1 0 " + n(shear) + " 1 " + n(cursor + (glyph.xOffset + shear * glyph.yOffset) * size / 1000) + " " + n(baseline + glyph.yOffset * size / 1000) + " Tm " + font.encodeGlyph(glyph.id, glyph.logicalText) + " Tj\n";
@@ -8751,7 +8815,8 @@ class PdfPages {
8751
8815
  this.current = this.objects.reserve();
8752
8816
  this.references.push(this.current);
8753
8817
  }
8754
- this.commands = [];
8818
+ this.commands = "";
8819
+ this.commandParts = [];
8755
8820
  this.annotations = [];
8756
8821
  this.commandBytes = 0;
8757
8822
  this.bodyAdded = false;
@@ -8816,7 +8881,7 @@ class PdfPages {
8816
8881
  // Charge physical repeats without recapturing callbacks or making them semantic duplicates.
8817
8882
  for (const cell of header.cells)
8818
8883
  if (!this.bandCellBudget && this.paintedHeaderBudgetCells.has(cell.source ?? cell))
8819
- this.settings.budget.cell(cell.lines.map(line => line.text).join(""));
8884
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" : cell.lines.map(line => line.text).join(""));
8820
8885
  const elements = this.tableStructure ? header.cells.map(cell => this.tableStructure.owner(cell.source ?? cell)) : undefined;
8821
8886
  const repeated = header.cells.map(cell => this.paintedHeaderCells.has(cell.source ?? cell));
8822
8887
  this.draw(header, 0, header.lines, elements, repeated);
@@ -8834,14 +8899,32 @@ class PdfPages {
8834
8899
  if (!this.layout)
8835
8900
  throw new Error("A table layout is required before drawing rows.");
8836
8901
  this.bodyAdded = true;
8837
- const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
8902
+ const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2, lefts = this.layout.lefts;
8903
+ // One geometry token per active physical column; table/band changes release the old tokens.
8904
+ if (this.rectangleLefts !== lefts) {
8905
+ this.rectangleLefts = lefts;
8906
+ this.rectangleColumns = [];
8907
+ }
8908
+ let rectangleHeight, rectangleBottom = "", rectangleHeightText = "";
8838
8909
  for (const [index, cell] of row.cells.entries()) {
8839
8910
  if (this.bandCellBudget)
8840
- this.settings.budget.cell((cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8841
- const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
8911
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
8912
+ (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8913
+ const x = lefts[cell.first], cellHeight = cell.height ?? height;
8914
+ if (cellHeight !== rectangleHeight) {
8915
+ rectangleBottom = n(this.y - cellHeight);
8916
+ rectangleHeightText = n(cellHeight);
8917
+ rectangleHeight = cellHeight;
8918
+ }
8919
+ let horizontal = this.rectangleColumns[cell.first];
8920
+ if (!horizontal || horizontal.x !== x || horizontal.width !== cell.width) {
8921
+ horizontal = { x, width: cell.width, left: n(x), widthText: n(cell.width) };
8922
+ this.rectangleColumns[cell.first] = horizontal;
8923
+ }
8924
+ const rectangle = horizontal.left + " " + rectangleBottom + " " + horizontal.widthText + " " + rectangleHeightText;
8842
8925
  if (cell.style.background)
8843
- this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re f Q\n"));
8844
- this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re S Q\n"));
8926
+ this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + rectangle + " re f Q\n"));
8927
+ this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + rectangle + " re S Q\n"));
8845
8928
  const element = elements?.[index], artifact = cell.semanticArtifact || repeated[index], owner = cell.link && this.structure && element !== undefined ? this.structure.link(element, cell.link) : element;
8846
8929
  for (let line = firstLine; line < Math.min(cell.lines.length, cell.height ? cell.lines.length : firstLine + lineCount); line++) {
8847
8930
  const text = cell.lines[line], left = cell.style.alignment === "right" ? cell.width - padding - text.width : cell.style.alignment === "center" ? (cell.width - text.width) / 2 : padding;
@@ -8851,6 +8934,7 @@ class PdfPages {
8851
8934
  this.link(cell.link, x, this.y - cellHeight, cell.width, cellHeight, owner);
8852
8935
  }
8853
8936
  this.y -= row.structured ? row.height : height;
8937
+ this.sealCommands();
8854
8938
  }
8855
8939
  async block(rows) {
8856
8940
  if (this.bandFlow)
@@ -9176,9 +9260,22 @@ class PdfPages {
9176
9260
  marker: { line: item.marker, gap: item.markerGap, ...(label === undefined ? {} : { owner: label }) } });
9177
9261
  await this.structure?.complete(li);
9178
9262
  }
9263
+ sealCommands() {
9264
+ if (this.commands) {
9265
+ this.commandParts.push(this.commands);
9266
+ this.commands = "";
9267
+ }
9268
+ }
9269
+ takeCommands() {
9270
+ this.sealCommands();
9271
+ const content = this.commandParts.join("");
9272
+ // Encoding and awaited delivery own the page value; the next page starts independently.
9273
+ this.commandParts = [];
9274
+ return content;
9275
+ }
9179
9276
  async finishPage() {
9180
9277
  const contents = this.objects.reserve(), { page, options } = this.settings;
9181
- await this.objects.stream(contents, this.commands.join(""), "", options.compression !== false);
9278
+ await this.objects.stream(contents, this.takeCommands(), "", options.compression !== false);
9182
9279
  const annotations = [];
9183
9280
  for (const annotation of this.annotations) {
9184
9281
  annotations.push(annotation.id);
@@ -9190,7 +9287,6 @@ class PdfPages {
9190
9287
  (annotations.length ? " /Annots [" + annotations.map(id => id + " 0 R").join(" ") + "]" : "") + " >>");
9191
9288
  if (this.structure)
9192
9289
  await this.structure.finishPage();
9193
- this.commands = [];
9194
9290
  this.annotations = [];
9195
9291
  this.commandBytes = 0;
9196
9292
  this.current = 0;