@evotecit/officeimo 0.1.0 → 0.1.1
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/README.md +13 -10
- package/bundles/officeimo-canopyx.js +813 -358
- package/bundles/officeimo-canopyx.mjs +700 -246
- package/bundles/officeimo-csv.js +29 -19
- package/bundles/officeimo-csv.mjs +17 -7
- package/bundles/officeimo-datatables.js +806 -360
- package/bundles/officeimo-datatables.mjs +694 -249
- package/bundles/officeimo-execution.js +35 -25
- package/bundles/officeimo-execution.mjs +17 -7
- package/bundles/officeimo-pdf.js +734 -289
- package/bundles/officeimo-pdf.mjs +685 -241
- package/bundles/officeimo-xlsx.js +88 -77
- package/bundles/officeimo-xlsx.mjs +22 -11
- package/bundles/officeimo.js +790 -344
- package/bundles/officeimo.mjs +680 -235
- package/dist/core/index.d.ts +2 -0
- package/dist/core/iteration.js +2 -2
- package/dist/core/sinks.js +2 -1
- package/dist/integrations/canopyx/source.js +13 -7
- package/dist/integrations/datatables/snapshot.js +3 -3
- package/dist/internal/rows.js +13 -4
- package/dist/pdf/document-grouped.js +72 -22
- package/dist/pdf/font-resources.js +2 -1
- package/dist/pdf/inline-text.js +50 -9
- package/dist/pdf/objects.js +188 -11
- package/dist/pdf/pages.js +25 -26
- package/dist/pdf/paragraph-layout.d.ts +2 -0
- package/dist/pdf/paragraph-layout.js +9 -4
- package/dist/pdf/session.js +1 -1
- package/dist/pdf/settings.d.ts +2 -0
- package/dist/pdf/settings.js +27 -2
- package/dist/pdf/structure.js +80 -28
- package/dist/pdf/table-band-flow.js +26 -11
- package/dist/pdf/table-band-plan.js +1 -3
- package/dist/pdf/table-layout.d.ts +4 -0
- package/dist/pdf/table-layout.js +22 -10
- package/dist/pdf/table-structure.js +28 -12
- package/dist/pdf/text.js +5 -0
- package/dist/pdf/types.d.ts +4 -2
- package/dist/pdf/xref.d.ts +1 -0
- package/dist/pdf/xref.js +30 -0
- package/dist/xlsx/values.js +3 -2
- package/dist/zip/entry.js +1 -1
- package/dist/zip/index.js +1 -1
- package/package.json +1 -1
package/dist/pdf/objects.js
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
import { checkAbort, withAbort, pause, taskYieldDue } from "../core/iteration.js";
|
|
2
2
|
import { OfficeIMOError } from "../core/errors.js";
|
|
3
|
+
import { pdfXrefChunks, pdfXrefEntryBytes } from "./xref.js";
|
|
4
|
+
const compactObjectCount = 256, compactObjectBytes = 32768;
|
|
5
|
+
const compactIndexChunkEntries = 4096;
|
|
6
|
+
/** Lazy Uint16 chunks store compact membership; untouched zero slots denote ordinary objects. */
|
|
7
|
+
class PdfCompactIndices {
|
|
8
|
+
count;
|
|
9
|
+
chunks = [];
|
|
10
|
+
constructor(count) {
|
|
11
|
+
this.count = count;
|
|
12
|
+
}
|
|
13
|
+
get length() { return this.count; }
|
|
14
|
+
reserve() { this.count++; }
|
|
15
|
+
set(id, member) {
|
|
16
|
+
const chunk = this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
|
|
17
|
+
// The current batch cap permits indices 0..255; adding one preserves index 255 as 256.
|
|
18
|
+
chunk[id % compactIndexChunkEntries] = member + 1;
|
|
19
|
+
}
|
|
20
|
+
at(id) {
|
|
21
|
+
const encoded = this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
|
|
22
|
+
return encoded ? encoded - 1 : undefined;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
3
25
|
export function pdfNumber(value) {
|
|
4
26
|
if (!Number.isFinite(value) || Math.abs(value) > 1e9)
|
|
5
27
|
throw new RangeError("PDF coordinates and metrics must be finite and bounded.");
|
|
@@ -16,25 +38,33 @@ export function unicodeHex(text) {
|
|
|
16
38
|
}
|
|
17
39
|
return hex;
|
|
18
40
|
}
|
|
19
|
-
/** @internal Forward-only PDF objects.
|
|
41
|
+
/** @internal Forward-only PDF objects. Completed objects retain only their xref location. */
|
|
20
42
|
export class PdfObjects {
|
|
21
43
|
sink;
|
|
22
44
|
signal;
|
|
23
45
|
maxBytes;
|
|
46
|
+
compressObjects;
|
|
24
47
|
offsets = [0];
|
|
48
|
+
// A defined index changes the corresponding full-width offset into an object-stream number.
|
|
49
|
+
// Membership chunks are allocated only when a compact member needs their ID range.
|
|
50
|
+
compactIndices;
|
|
51
|
+
compactBatch;
|
|
52
|
+
compactArena;
|
|
53
|
+
compactUnavailable = false;
|
|
25
54
|
encoder = new TextEncoder();
|
|
26
55
|
buffer = new Uint8Array(32768);
|
|
27
56
|
buffered = 0;
|
|
28
57
|
bytes = 0;
|
|
29
|
-
constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
|
|
58
|
+
constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER, compressObjects = false) {
|
|
30
59
|
this.sink = sink;
|
|
31
60
|
this.signal = signal;
|
|
32
61
|
this.maxBytes = maxBytes;
|
|
62
|
+
this.compressObjects = compressObjects;
|
|
33
63
|
}
|
|
34
|
-
reserve() { this.offsets.push(undefined); return this.offsets.length - 1; }
|
|
64
|
+
reserve() { this.offsets.push(undefined); this.compactIndices?.reserve(); return this.offsets.length - 1; }
|
|
35
65
|
async raw(bytes) {
|
|
36
66
|
checkAbort(this.signal);
|
|
37
|
-
if (this.bytes + bytes.length > this.maxBytes)
|
|
67
|
+
if (!Number.isSafeInteger(this.bytes + bytes.length) || this.bytes + bytes.length > this.maxBytes)
|
|
38
68
|
throw new OfficeIMOError("RESOURCE_LIMIT", "maxOutputBytes exceeded.");
|
|
39
69
|
this.bytes += bytes.length;
|
|
40
70
|
for (let offset = 0; offset < bytes.length;) {
|
|
@@ -43,21 +73,139 @@ export class PdfObjects {
|
|
|
43
73
|
offset += n;
|
|
44
74
|
this.buffered += n;
|
|
45
75
|
if (this.buffered === this.buffer.length)
|
|
46
|
-
await this.
|
|
76
|
+
await this.flushBytes();
|
|
47
77
|
}
|
|
48
78
|
}
|
|
49
79
|
async text(text) { await this.raw(this.encoder.encode(text)); }
|
|
50
80
|
async flush() {
|
|
81
|
+
await this.flushCompact();
|
|
82
|
+
await this.flushBytes();
|
|
83
|
+
}
|
|
84
|
+
/** Publish completed page bytes without forcing a partial structure container to end. */
|
|
85
|
+
async flushBytes() {
|
|
51
86
|
if (this.buffered) {
|
|
52
87
|
const bytes = this.buffer.subarray(0, this.buffered);
|
|
53
88
|
await withAbort(Promise.resolve(this.sink.write(bytes)), this.signal);
|
|
54
|
-
this
|
|
89
|
+
// The sink borrows this view until acceptance; failed or cancelled writes must not reuse it.
|
|
55
90
|
this.buffered = 0;
|
|
56
91
|
}
|
|
57
92
|
if (taskYieldDue())
|
|
58
93
|
await pause();
|
|
59
94
|
checkAbort(this.signal);
|
|
60
95
|
}
|
|
96
|
+
/** @internal Append only when an existing compact batch can accept a member without async work. */
|
|
97
|
+
tryCompactObject(id, body) {
|
|
98
|
+
checkAbort(this.signal);
|
|
99
|
+
this.validateObject(id);
|
|
100
|
+
const batch = this.compactBatch;
|
|
101
|
+
if (!batch || !this.compressObjects || this.compactUnavailable || typeof CompressionStream !== "function" ||
|
|
102
|
+
body.length > compactObjectBytes || batch.ids.length + 1 >= compactObjectCount)
|
|
103
|
+
return false;
|
|
104
|
+
const indexBytes = String(id).length + String(batch.bodyBytes).length + 2;
|
|
105
|
+
const written = this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2);
|
|
106
|
+
if (written === undefined)
|
|
107
|
+
return false;
|
|
108
|
+
this.storeCompactBody(batch, id, written);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
/** Small logical structure values share one bounded object-stream container. Other callers keep
|
|
112
|
+
* ordinary objects; unavailable deflate preserves the classic representation before packing starts. */
|
|
113
|
+
async compactObject(id, body) {
|
|
114
|
+
checkAbort(this.signal);
|
|
115
|
+
this.validateObject(id);
|
|
116
|
+
if (!this.compressObjects || this.compactUnavailable || body.length > compactObjectBytes)
|
|
117
|
+
return this.object(id, body);
|
|
118
|
+
if (typeof CompressionStream !== "function") {
|
|
119
|
+
if (this.compactIndices)
|
|
120
|
+
throw new Error("PDF object compression became unavailable.");
|
|
121
|
+
this.compactUnavailable = true;
|
|
122
|
+
return this.object(id, body);
|
|
123
|
+
}
|
|
124
|
+
const firstIndexBytes = String(id).length + 4;
|
|
125
|
+
let batch = this.compactBatch;
|
|
126
|
+
const indexBytes = String(id).length + String(batch?.bodyBytes ?? 0).length + 2;
|
|
127
|
+
let written = batch && batch.ids.length < compactObjectCount ? this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2) : undefined;
|
|
128
|
+
if (batch && written === undefined) {
|
|
129
|
+
// Partial encodings only touch the uncommitted suffix. Flush the committed prefix and retry
|
|
130
|
+
// the whole string so a multibyte scalar is never split between containers.
|
|
131
|
+
await this.flushCompact();
|
|
132
|
+
batch = undefined;
|
|
133
|
+
checkAbort(this.signal);
|
|
134
|
+
}
|
|
135
|
+
if (!batch) {
|
|
136
|
+
written = this.encodeCompactBody(body, 0, compactObjectBytes - firstIndexBytes - 1);
|
|
137
|
+
if (written === undefined)
|
|
138
|
+
return this.object(id, body);
|
|
139
|
+
let compressor;
|
|
140
|
+
// Probe before selecting the compact representation. Later batches need no idle native
|
|
141
|
+
// codec while they accumulate, including while ordinary page streams are compressed.
|
|
142
|
+
if (!this.compactIndices) {
|
|
143
|
+
try {
|
|
144
|
+
compressor = new CompressionStream("deflate");
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
this.compactUnavailable = true;
|
|
148
|
+
return this.object(id, body);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
batch = { id: this.reserve(), compressor, ids: [], bodyOffsets: [], bodyBytes: 0, indexBytes: 1 };
|
|
152
|
+
this.compactIndices ??= new PdfCompactIndices(this.offsets.length);
|
|
153
|
+
this.compactBatch = batch;
|
|
154
|
+
}
|
|
155
|
+
this.storeCompactBody(batch, id, written);
|
|
156
|
+
if (batch.ids.length === compactObjectCount)
|
|
157
|
+
await this.flushCompact();
|
|
158
|
+
}
|
|
159
|
+
storeCompactBody(batch, id, written) {
|
|
160
|
+
this.offsets[id] = batch.id;
|
|
161
|
+
this.compactIndices.set(id, batch.ids.length);
|
|
162
|
+
batch.indexBytes += String(id).length + String(batch.bodyBytes).length + 2;
|
|
163
|
+
batch.ids.push(id);
|
|
164
|
+
batch.bodyOffsets.push(batch.bodyBytes);
|
|
165
|
+
this.compactArena[batch.bodyBytes + written] = 10;
|
|
166
|
+
batch.bodyBytes += written + 1;
|
|
167
|
+
}
|
|
168
|
+
/** An incomplete encoding leaves only scratch bytes beyond the committed batch prefix. */
|
|
169
|
+
encodeCompactBody(body, offset, available) {
|
|
170
|
+
if (available < 0)
|
|
171
|
+
return undefined;
|
|
172
|
+
const destination = (this.compactArena ??= new Uint8Array(compactObjectBytes)).subarray(offset, offset + available);
|
|
173
|
+
if (typeof this.encoder.encodeInto === "function") {
|
|
174
|
+
const result = this.encoder.encodeInto(body, destination);
|
|
175
|
+
return result.read === body.length ? result.written : undefined;
|
|
176
|
+
}
|
|
177
|
+
// Preserve TextEncoder implementations that only expose encode().
|
|
178
|
+
const bytes = this.encoder.encode(body);
|
|
179
|
+
if (bytes.length > available)
|
|
180
|
+
return undefined;
|
|
181
|
+
destination.set(bytes);
|
|
182
|
+
return bytes.length;
|
|
183
|
+
}
|
|
184
|
+
async flushCompact() {
|
|
185
|
+
const batch = this.compactBatch;
|
|
186
|
+
if (!batch)
|
|
187
|
+
return;
|
|
188
|
+
this.compactBatch = undefined;
|
|
189
|
+
let index = "";
|
|
190
|
+
for (let member = 0; member < batch.ids.length; member++)
|
|
191
|
+
index += batch.ids[member] + " " + batch.bodyOffsets[member] + " ";
|
|
192
|
+
const header = this.encoder.encode(index + "\n"), count = batch.ids.length;
|
|
193
|
+
// Keep the index separate from the arena. Reuse waits for the compressed read or all raw
|
|
194
|
+
// writes below, so later members cannot overwrite a borrowed batch body.
|
|
195
|
+
const body = this.compactArena.subarray(0, batch.bodyBytes);
|
|
196
|
+
batch.ids.length = 0;
|
|
197
|
+
batch.bodyOffsets.length = 0;
|
|
198
|
+
if (batch.compressor) {
|
|
199
|
+
await this.compressedStream(batch.id, body, "/Type /ObjStm /N " + count + " /First " + header.length, batch.compressor, header);
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
this.start(batch.id);
|
|
203
|
+
await this.text(batch.id + " 0 obj\n<< /Length " + (header.length + body.length) + " /Type /ObjStm /N " + count + " /First " + header.length + " >>\nstream\n");
|
|
204
|
+
await this.raw(header);
|
|
205
|
+
await this.raw(body);
|
|
206
|
+
await this.text("\nendstream\nendobj\n");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
61
209
|
async object(id, body) {
|
|
62
210
|
this.start(id);
|
|
63
211
|
if (typeof body === "string") {
|
|
@@ -81,9 +229,12 @@ export class PdfObjects {
|
|
|
81
229
|
}
|
|
82
230
|
await this.text(chunk + "\nendobj\n");
|
|
83
231
|
}
|
|
84
|
-
|
|
85
|
-
if (!Number.
|
|
232
|
+
validateObject(id) {
|
|
233
|
+
if (!Number.isSafeInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
|
|
86
234
|
throw new Error("Invalid PDF object state.");
|
|
235
|
+
}
|
|
236
|
+
start(id) {
|
|
237
|
+
this.validateObject(id);
|
|
87
238
|
this.offsets[id] = this.bytes;
|
|
88
239
|
}
|
|
89
240
|
async stream(id, source, dictionary = "", compression = true, owned = false) {
|
|
@@ -104,7 +255,15 @@ export class PdfObjects {
|
|
|
104
255
|
}
|
|
105
256
|
// Verified internal producers can transfer immutable ownership; other byte sources retain the defensive snapshot.
|
|
106
257
|
const sourceBytes = typeof source === "string" || owned ? bytes : new Uint8Array(bytes);
|
|
107
|
-
|
|
258
|
+
await this.compressedStream(id, sourceBytes, dictionary, compressor);
|
|
259
|
+
}
|
|
260
|
+
async compressedStream(id, sourceBytes, dictionary, compressor, prefix) {
|
|
261
|
+
const input = new ReadableStream({ start(controller) {
|
|
262
|
+
if (prefix)
|
|
263
|
+
controller.enqueue(prefix);
|
|
264
|
+
controller.enqueue(sourceBytes);
|
|
265
|
+
controller.close();
|
|
266
|
+
} });
|
|
108
267
|
const reader = input.pipeThrough(compressor).getReader(), lengthId = this.reserve();
|
|
109
268
|
let length = 0, complete = false;
|
|
110
269
|
try {
|
|
@@ -129,10 +288,14 @@ export class PdfObjects {
|
|
|
129
288
|
}
|
|
130
289
|
}
|
|
131
290
|
async finish(root, info) {
|
|
132
|
-
|
|
133
|
-
|
|
291
|
+
await this.flushCompact();
|
|
292
|
+
for (let id = 1; id < this.offsets.length; id++)
|
|
293
|
+
if (this.offsets[id] === undefined)
|
|
294
|
+
throw new Error("PDF contains unwritten objects.");
|
|
134
295
|
if (this.bytes > 9999999999)
|
|
135
296
|
throw new OfficeIMOError("RESOURCE_LIMIT", "PDF exceeds classic cross-reference offset capacity.");
|
|
297
|
+
if (this.compactIndices)
|
|
298
|
+
return this.finishCompact(root, info);
|
|
136
299
|
const start = this.bytes;
|
|
137
300
|
await this.text("xref\n0 " + this.offsets.length + "\n0000000000 65535 f \n");
|
|
138
301
|
for (let i = 1; i < this.offsets.length; i++)
|
|
@@ -140,4 +303,18 @@ export class PdfObjects {
|
|
|
140
303
|
await this.text("trailer\n<< /Size " + this.offsets.length + " /Root " + root + " 0 R /Info " + info + " 0 R >>\nstartxref\n" + start + "\n%%EOF\n");
|
|
141
304
|
await this.flush();
|
|
142
305
|
}
|
|
306
|
+
/** Xref payloads have a known length and are emitted in bounded chunks, without another copy
|
|
307
|
+
* of the document's random-access location arrays or a whole-xref compression buffer. */
|
|
308
|
+
async finishCompact(root, info) {
|
|
309
|
+
const id = this.reserve(), start = this.bytes, length = this.offsets.length * pdfXrefEntryBytes;
|
|
310
|
+
if (!Number.isSafeInteger(length))
|
|
311
|
+
throw new OfficeIMOError("RESOURCE_LIMIT", "PDF cross-reference stream is too large.");
|
|
312
|
+
this.start(id);
|
|
313
|
+
await this.text(id + " 0 obj\n<< /Type /XRef /Size " + this.offsets.length + " /W [1 8 2] /Root " + root + " 0 R /Info " + info +
|
|
314
|
+
" 0 R /Length " + length + " >>\nstream\n");
|
|
315
|
+
for (const chunk of pdfXrefChunks(this.offsets, this.compactIndices))
|
|
316
|
+
await this.raw(chunk);
|
|
317
|
+
await this.text("\nendstream\nendobj\nstartxref\n" + start + "\n%%EOF\n");
|
|
318
|
+
await this.flushBytes();
|
|
319
|
+
}
|
|
143
320
|
}
|
package/dist/pdf/pages.js
CHANGED
|
@@ -4,7 +4,7 @@ import { pdfNumber } from "./objects.js";
|
|
|
4
4
|
import { color } from "./settings.js";
|
|
5
5
|
import { PdfTableBandFlow } from "./table-band-flow.js";
|
|
6
6
|
import { PdfTableStructure } from "./table-structure.js";
|
|
7
|
-
import { wrapText, wrapTextCooperatively, synchronousText } from "./text.js";
|
|
7
|
+
import { wrapText, wrapTextCooperatively, synchronousText, pdfBudgetText } from "./text.js";
|
|
8
8
|
import { linkAnnotation } from "./annotations.js";
|
|
9
9
|
import { unicodeHex } from "./objects.js";
|
|
10
10
|
import { captureSection, captureBookmark } from "./section-types.js";
|
|
@@ -145,8 +145,9 @@ export class PdfPages {
|
|
|
145
145
|
const lineActualText = !this.structure && line.actualText !== undefined && line.actualText.length > 0;
|
|
146
146
|
if (lineActualText)
|
|
147
147
|
this.add("/Span << /ActualText <FEFF" + unicodeHex(line.actualText) + "> >> BDC\n");
|
|
148
|
-
|
|
148
|
+
let marks;
|
|
149
149
|
if (line.actualText !== undefined && this.structure && element !== undefined) {
|
|
150
|
+
marks = new Map();
|
|
150
151
|
// Allocate MCIDs/Link children in logical order, then paint the independently positioned visual order.
|
|
151
152
|
for (const segment of [...line.segments].sort((a, b) => (a.logicalStart ?? 0) - (b.logicalStart ?? 0))) {
|
|
152
153
|
const owner = segment.link ? this.structure.link(element, segment.link) : element;
|
|
@@ -154,7 +155,7 @@ export class PdfPages {
|
|
|
154
155
|
}
|
|
155
156
|
}
|
|
156
157
|
for (const segment of line.segments) {
|
|
157
|
-
const registered = marks
|
|
158
|
+
const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
|
|
158
159
|
if (segment.glyphs) {
|
|
159
160
|
const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
|
|
160
161
|
let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
|
|
@@ -188,7 +189,7 @@ export class PdfPages {
|
|
|
188
189
|
decoration(text, x, y, width) {
|
|
189
190
|
if (!text)
|
|
190
191
|
return;
|
|
191
|
-
this.settings.budget.cell(text);
|
|
192
|
+
this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
|
|
192
193
|
const font = this.fonts.select(), lines = wrapText(text, font, this.settings.fontSize, width, this.settings.limits.maxCellCharacters, 1, false);
|
|
193
194
|
this.text(lines[0].text, font, this.settings.fontSize, x, y);
|
|
194
195
|
}
|
|
@@ -249,9 +250,7 @@ export class PdfPages {
|
|
|
249
250
|
}
|
|
250
251
|
const headers = preparedHeadings ?? (tableHeadings && this.layout ? this.activeHeadings ??= await this.layout.headers() : []), headerHeight = headers.reduce((n, h) => n + h.height, 0), continuation = tableHeadings && this.layout ? this.continuationCaption : undefined;
|
|
251
252
|
if (continuation?.lines.length) {
|
|
252
|
-
if (this.continuationCaptionPaints++
|
|
253
|
-
this.settings.budget.cell(continuation.text.text);
|
|
254
|
-
else
|
|
253
|
+
if (this.continuationCaptionPaints++ === 0)
|
|
255
254
|
this.tableCaptionOwner = this.captionAnnotations(continuation, this.tableCaptionOwner);
|
|
256
255
|
await this.paragraphs([continuation], headerHeight + lineHeight + this.settings.padding * 2, true, { artifact: true, ...(this.tableCaptionOwner === undefined ? {} : { annotationParent: this.tableCaptionOwner }) });
|
|
257
256
|
}
|
|
@@ -369,7 +368,7 @@ export class PdfPages {
|
|
|
369
368
|
async paragraph(text, style = {}, size = this.settings.fontSize, paginate = true, headingLevel) {
|
|
370
369
|
await this.ensureStarted();
|
|
371
370
|
const { margins, page, limits } = this.settings, font = this.fonts.select(style.bold, style.italic), lineHeight = font.lineHeight(size);
|
|
372
|
-
this.settings.budget.cell(text);
|
|
371
|
+
this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
|
|
373
372
|
const lines = await wrapTextCooperatively(text, font, size, page.width - margins.left - margins.right, limits.maxCellCharacters, limits.maxRowLines, true, this.settings.options.signal);
|
|
374
373
|
if (lineHeight > page.height - margins.top - margins.bottom)
|
|
375
374
|
throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");
|
|
@@ -412,6 +411,8 @@ export class PdfPages {
|
|
|
412
411
|
if (keepTogether && visible.length)
|
|
413
412
|
await this.reserveSpace(visible.reduce((height, paragraph) => height + paragraph.height, 0) + reservations.at(-1), "Kept PDF paragraph group");
|
|
414
413
|
for (const [index, paragraph] of visible.entries()) {
|
|
414
|
+
if (paragraph.budgetOnPaint)
|
|
415
|
+
this.settings.budget.cell(pdfBudgetText(paragraph.text.text, this.settings.budget));
|
|
415
416
|
if (paragraph.keepTogether || paragraph.keepWithNext)
|
|
416
417
|
await this.reserveSpace(paragraph.height + reservations[index], "Kept PDF paragraph chain");
|
|
417
418
|
const { margins, page } = this.settings;
|
|
@@ -464,10 +465,11 @@ export class PdfPages {
|
|
|
464
465
|
/** The generated summary label is a row heading; no localized text/style inference is used. */
|
|
465
466
|
summary(row) { this.summaryRows.add(row); }
|
|
466
467
|
/** Begin an independent table on the current page, retaining its headings on continuation pages.
|
|
467
|
-
* Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
|
|
468
|
-
|
|
468
|
+
* Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
|
|
469
|
+
* An already-painted opening path only suppresses its artifact caption on that existing page. */
|
|
470
|
+
async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false, openingContextAlreadyPainted = false) {
|
|
469
471
|
if (layout.bands)
|
|
470
|
-
return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact);
|
|
472
|
+
return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact, openingContextAlreadyPainted);
|
|
471
473
|
await this.ensureStarted();
|
|
472
474
|
this.layout = layout;
|
|
473
475
|
this.paintedHeaderCells = new WeakSet();
|
|
@@ -481,7 +483,7 @@ export class PdfPages {
|
|
|
481
483
|
// Its own headings remain available when it moves or splits onto a fresh page.
|
|
482
484
|
const initialHeadings = headingsOnNewPageOnly && this.bodyAdded && !this.structure ? [] : headings;
|
|
483
485
|
const height = initialHeadings.reduce((n, row) => n + row.height, 0);
|
|
484
|
-
if (caption) {
|
|
486
|
+
if (caption && !(captionArtifact && openingContextAlreadyPainted)) {
|
|
485
487
|
await this.reserveSpace(caption.height + height + minimumDataHeight, "Kept PDF table caption and first data fragment");
|
|
486
488
|
this.tableCaptionOwner = captionArtifact ? this.captionAnnotations(caption)
|
|
487
489
|
: caption.lines.length ? this.structure?.element("Caption", this.tableElement) : undefined;
|
|
@@ -503,7 +505,7 @@ export class PdfPages {
|
|
|
503
505
|
this.dataTop = this.y;
|
|
504
506
|
}
|
|
505
507
|
/** Bind the bounded logical-window owner to the existing physical page painter. */
|
|
506
|
-
async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact) {
|
|
508
|
+
async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact, openingContextAlreadyPainted) {
|
|
507
509
|
await this.ensureStarted();
|
|
508
510
|
const logicalHeadings = preparedHeadings ?? await layout.headers(), headings = await layout.bandRows(logicalHeadings, true);
|
|
509
511
|
const headerHeight = headings[0].reduce((sum, row) => sum + row.height, 0), { page, margins, padding } = this.settings;
|
|
@@ -512,13 +514,15 @@ export class PdfPages {
|
|
|
512
514
|
const continuationCapacity = page.height - margins.top - margins.bottom - headerHeight - (continuation?.height ?? 0);
|
|
513
515
|
if (continuationCapacity + .001 < layout.lineHeight + padding * 2)
|
|
514
516
|
throw new RangeError("PDF band headings and continuation context leave no room for a data line.");
|
|
515
|
-
|
|
517
|
+
let openingContextPainted = captionArtifact && openingContextAlreadyPainted;
|
|
518
|
+
if (this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0) + .001 < minimum) {
|
|
516
519
|
await this.pageBreak();
|
|
517
|
-
|
|
518
|
-
|
|
520
|
+
openingContextPainted = false;
|
|
521
|
+
}
|
|
522
|
+
const firstCapacity = this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0);
|
|
519
523
|
if (firstCapacity + .001 < minimum)
|
|
520
524
|
throw new RangeError("PDF band caption and headings leave no room for a data line.");
|
|
521
|
-
let
|
|
525
|
+
let continuationPaints = 0;
|
|
522
526
|
this.tableElement = this.structure?.element("Table", this.groupParent);
|
|
523
527
|
this.paintedHeaderCells = new WeakSet();
|
|
524
528
|
let captionElement = this.structure && caption?.lines.length ? captionArtifact ? this.captionAnnotations(caption)
|
|
@@ -532,21 +536,16 @@ export class PdfPages {
|
|
|
532
536
|
this.bandFlow = new PdfTableBandFlow(layout, headings, { firstCapacity, firstFullCapacity, continuationCapacity,
|
|
533
537
|
prepareRow: async (row) => { await this.tableStructure?.prepareHeaders(); await this.rowElements(row); },
|
|
534
538
|
completeRow: async (row) => { await this.tableStructure?.completeRow(row.source ?? row); },
|
|
535
|
-
moveFirstToFreshPage: async () => { await this.pageBreak();
|
|
539
|
+
moveFirstToFreshPage: async () => { await this.pageBreak(); openingContextPainted = false; },
|
|
536
540
|
paint: async (band, headers, rows, currentCaption, firstWindow, firstBand) => {
|
|
537
541
|
if (!(firstWindow && firstBand))
|
|
538
542
|
await this.pageBreak();
|
|
539
|
-
if (firstWindow && !firstBand)
|
|
540
|
-
this.y -= initialOffset;
|
|
541
543
|
const frame = layout.bands[band];
|
|
542
544
|
this.layout = { lefts: frame.lefts, lineHeight: layout.lineHeight, headers: async () => headers };
|
|
543
545
|
this.bandCellBudget = true;
|
|
544
546
|
try {
|
|
545
|
-
if (currentCaption?.lines.length) {
|
|
546
|
-
|
|
547
|
-
if (paints > 0)
|
|
548
|
-
this.settings.budget.cell(currentCaption.text.text);
|
|
549
|
-
if (!firstWindow && paints === 0)
|
|
547
|
+
if (currentCaption?.lines.length && !(firstWindow && firstBand && openingContextPainted)) {
|
|
548
|
+
if (!firstWindow && continuationPaints++ === 0)
|
|
550
549
|
captionElement = this.captionAnnotations(currentCaption, captionElement);
|
|
551
550
|
const annotationParent = captionElement;
|
|
552
551
|
await this.paragraphs([currentCaption], headerHeight + minimum, true, firstWindow && firstBand && !captionArtifact ? { role: "Caption", keepOpen: true, ...(captionElement === undefined ? {} : { owner: captionElement }) }
|
|
@@ -650,7 +649,7 @@ export class PdfPages {
|
|
|
650
649
|
this.annotations = [];
|
|
651
650
|
this.commandBytes = 0;
|
|
652
651
|
this.current = 0;
|
|
653
|
-
await this.objects.
|
|
652
|
+
await this.objects.flushBytes();
|
|
654
653
|
}
|
|
655
654
|
async finish() {
|
|
656
655
|
if (this.bandFlow) {
|
|
@@ -11,6 +11,8 @@ export interface PdfCapturedParagraph {
|
|
|
11
11
|
readonly keepWithNext: boolean;
|
|
12
12
|
readonly spaceBefore: number;
|
|
13
13
|
readonly spaceAfter: number;
|
|
14
|
+
/** Captions are bounded definitions; charge only their actual physical occurrences. */
|
|
15
|
+
readonly budgetOnPaint?: boolean;
|
|
14
16
|
}
|
|
15
17
|
export interface PdfPreparedParagraph extends PdfCapturedParagraph {
|
|
16
18
|
readonly lines: readonly PdfInlineLine[];
|
|
@@ -4,8 +4,9 @@ import { positive } from "./settings.js";
|
|
|
4
4
|
import { resolveParagraphStyle } from "./paragraph-styles.js";
|
|
5
5
|
import { captureBookmark } from "./section-types.js";
|
|
6
6
|
import { captureFields } from "../internal/capture.js";
|
|
7
|
+
import { pdfBudgetText } from "./text.js";
|
|
7
8
|
/** @internal Copy public paragraph input before any cooperative layout or source enumeration. */
|
|
8
|
-
export function captureParagraph(block, settings, fonts) {
|
|
9
|
+
export function captureParagraph(block, settings, fonts, budgetOnPaint = false) {
|
|
9
10
|
if (!block || block.kind !== "paragraph")
|
|
10
11
|
throw new TypeError("PDF paragraph groups accept paragraph blocks only.");
|
|
11
12
|
const { text, headingLevel, presentation: inputStyle, fontSize, keepTogether, keepWithNext, spaceBefore, spaceAfter, style: styleName, bookmark: inputBookmark } = block;
|
|
@@ -18,7 +19,8 @@ export function captureParagraph(block, settings, fonts) {
|
|
|
18
19
|
}, settings.paragraphStyles);
|
|
19
20
|
const style = resolved.presentation ?? Object.freeze({}), size = positive(resolved.fontSize ?? settings.fontSize, "Paragraph font size", 144);
|
|
20
21
|
const bookmark = captureBookmark(inputBookmark, settings);
|
|
21
|
-
return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false), style, size,
|
|
22
|
+
return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false, !budgetOnPaint), style, size,
|
|
23
|
+
...(budgetOnPaint ? { budgetOnPaint: true } : {}),
|
|
22
24
|
...(headingLevel === undefined ? {} : { headingLevel }), ...(bookmark === undefined ? {} : { bookmark }),
|
|
23
25
|
keepTogether: resolved.keepTogether ?? false, keepWithNext: resolved.keepWithNext ?? false,
|
|
24
26
|
spaceBefore: resolved.spaceBefore ?? 0, spaceAfter: resolved.spaceAfter ?? 8 });
|
|
@@ -29,13 +31,16 @@ export function captureCaption(caption, settings, fonts) {
|
|
|
29
31
|
Object.keys(caption).some(key => !["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"].includes(key)))
|
|
30
32
|
throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");
|
|
31
33
|
return captureParagraph({ ...captureFields(caption, ["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"]),
|
|
32
|
-
kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts);
|
|
34
|
+
kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts, true);
|
|
33
35
|
}
|
|
34
36
|
/** @internal Layout is bounded by the same per-cell text and wrapped-line limits as table cells. */
|
|
35
37
|
export async function prepareParagraph(captured, settings, fonts, width = settings.page.width - settings.margins.left - settings.margins.right) {
|
|
36
38
|
if (!captured.text.text)
|
|
37
39
|
return { ...captured, lines: [], height: 0, firstHeight: 0 };
|
|
38
|
-
|
|
40
|
+
if (!captured.budgetOnPaint) {
|
|
41
|
+
const budgetText = pdfBudgetText(captured.text.text, settings.budget);
|
|
42
|
+
settings.budget.cell(budgetText, budgetText.length);
|
|
43
|
+
}
|
|
39
44
|
const lines = await wrapPdfText(captured.text, fonts, captured.size, positive(width, "Paragraph width"), settings);
|
|
40
45
|
return { ...captured, lines, height: captured.spaceBefore + lines.reduce((height, line) => height + line.lineHeight, 0) + captured.spaceAfter,
|
|
41
46
|
firstHeight: captured.spaceBefore + lines[0].lineHeight };
|
package/dist/pdf/session.js
CHANGED
|
@@ -19,7 +19,7 @@ export class PdfWriteSession {
|
|
|
19
19
|
info;
|
|
20
20
|
constructor(sink, settings, table = false) {
|
|
21
21
|
this.settings = settings;
|
|
22
|
-
this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes);
|
|
22
|
+
this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes, settings.options.compression !== false);
|
|
23
23
|
this.root = this.objects.reserve();
|
|
24
24
|
this.parent = this.objects.reserve();
|
|
25
25
|
this.resources = this.objects.reserve();
|
package/dist/pdf/settings.d.ts
CHANGED
|
@@ -11,5 +11,7 @@ export interface PdfSettings {
|
|
|
11
11
|
readonly padding: number;
|
|
12
12
|
readonly limits: Required<Pick<PdfLimits, "maxPages" | "maxColumns" | "maxTableBands" | "maxTableWindowRows" | "maxCellCharacters" | "maxTextRuns" | "maxGroupBlocks" | "maxRowLines" | "maxFontBytes" | "maxPageBytes" | "maxHyperlinks" | "maxImageBytes" | "maxImagePixels" | "maxVectorCommands" | "maxDrawingElements" | "maxStructureElements" | "maxMarkedContentReferences" | "maxListItems" | "maxParagraphStyles" | "maxSections" | "maxBookmarks">> & Pick<PdfLimits, "maxImageWorkingBytes">;
|
|
13
13
|
readonly budget: ExportBudget;
|
|
14
|
+
/** Captured identities resolved once to selected table positions, shared by layout and band planning. */
|
|
15
|
+
readonly repeatedColumns: readonly number[];
|
|
14
16
|
}
|
|
15
17
|
export declare function settings(input: PdfOptions & Pick<PdfDocumentOptions, "paragraphStyles">, document?: boolean): PdfSettings;
|
package/dist/pdf/settings.js
CHANGED
|
@@ -62,10 +62,34 @@ export function captureWideTable(input) {
|
|
|
62
62
|
if (repeatColumns !== undefined && !Array.isArray(repeatColumns))
|
|
63
63
|
throw new TypeError("repeatColumns must be an array.");
|
|
64
64
|
const repeats = repeatColumns === undefined ? [] : [...repeatColumns];
|
|
65
|
-
if (repeats.some(
|
|
66
|
-
throw new RangeError("repeatColumns must contain
|
|
65
|
+
if (repeats.some(value => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !value.length))
|
|
66
|
+
throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");
|
|
67
|
+
if (repeats.every(value => typeof value === "number") && repeats.some((value, index) => index > 0 && value <= repeats[index - 1]))
|
|
68
|
+
throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");
|
|
67
69
|
return Object.freeze({ mode, ...(minimumColumnWidth === undefined ? {} : { minimumColumnWidth }), repeatColumns: Object.freeze(repeats) });
|
|
68
70
|
}
|
|
71
|
+
/** Resolve identities against this table's captured selection, without consulting a grid or opening its rows. */
|
|
72
|
+
function repeatedColumns(policy, columns) {
|
|
73
|
+
if (typeof policy !== "object")
|
|
74
|
+
return Object.freeze([]);
|
|
75
|
+
const selected = new Set();
|
|
76
|
+
for (const selector of policy.repeatColumns ?? []) {
|
|
77
|
+
let position;
|
|
78
|
+
if (typeof selector === "number")
|
|
79
|
+
position = selector;
|
|
80
|
+
else {
|
|
81
|
+
position = columns.findIndex(column => column.key === selector);
|
|
82
|
+
if (position < 0 || columns.some((column, index) => index !== position && column.key === selector))
|
|
83
|
+
throw new TypeError("repeatColumns requires an unambiguous selected column key: " + selector);
|
|
84
|
+
}
|
|
85
|
+
if (position >= columns.length)
|
|
86
|
+
throw new RangeError("repeatColumns index exceeds the declared columns.");
|
|
87
|
+
if (selected.has(position))
|
|
88
|
+
throw new TypeError("repeatColumns selects the same column more than once.");
|
|
89
|
+
selected.add(position);
|
|
90
|
+
}
|
|
91
|
+
return Object.freeze([...selected].sort((left, right) => left - right));
|
|
92
|
+
}
|
|
69
93
|
export function settings(input, document = false) {
|
|
70
94
|
const configuration = { ...capturePdfOptions(input) };
|
|
71
95
|
configuration.booleanText = captureBooleanText(configuration.booleanText);
|
|
@@ -167,5 +191,6 @@ export function settings(input, document = false) {
|
|
|
167
191
|
}
|
|
168
192
|
const maxImageWorkingBytes = options.limits?.maxImageWorkingBytes;
|
|
169
193
|
return { options: { ...options, paragraphStyles }, paragraphStyles, page, margins, fontSize, padding,
|
|
194
|
+
repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
|
|
170
195
|
limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
|
|
171
196
|
}
|