anas-pdf 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anas Anabusy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # anas-pdf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A free, open-source **pure Node.js** library for creating PDF documents.
4
+
5
+ No native dependencies. No Chromium. Just install and generate PDFs.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install anas-pdf
11
+ ```
12
+
13
+ Requires Node.js 18+.
14
+
15
+ ## Quick start
16
+
17
+ ```js
18
+ import { PDFDocument } from 'anas-pdf';
19
+
20
+ const doc = new PDFDocument({ size: 'A4', margin: 50 });
21
+
22
+ doc
23
+ .fontSize(24)
24
+ .text('Hello from anas-pdf', { align: 'center' })
25
+ .moveDown()
26
+ .fontSize(12)
27
+ .fillColor('#333333')
28
+ .text('A free open-source PDF library for Node.js.')
29
+ .moveDown()
30
+ .rect(50, 650, 200, 40)
31
+ .strokeColor('#0066cc')
32
+ .stroke();
33
+
34
+ await doc.save('hello.pdf');
35
+ ```
36
+
37
+ ## Features
38
+
39
+ - Multi-page documents (A4, Letter, Legal, custom sizes)
40
+ - Text with Helvetica, Times, and Courier (built-in PDF fonts)
41
+ - Text wrapping and left / center / right alignment
42
+ - Vector graphics: lines, rectangles, circles, fill & stroke
43
+ - PNG and JPEG image embedding
44
+ - Metadata (title, author, creator, subject)
45
+ - Output as `Buffer`, file, or writable stream
46
+
47
+ ## API overview
48
+
49
+ ### `new PDFDocument(options?)`
50
+
51
+ | Option | Description |
52
+ |--------|-------------|
53
+ | `size` | `'A4'` (default), `'Letter'`, `'Legal'`, `'A3'`, `'A5'`, or `[width, height]` in points |
54
+ | `margin` | number or `{ top, right, bottom, left }` (default `50`) |
55
+ | `info` | `{ title, author, creator, subject }` |
56
+ | `autoFirstPage` | `true` by default |
57
+
58
+ ### Drawing & text
59
+
60
+ ```js
61
+ doc.font('Helvetica-Bold')
62
+ .fontSize(16)
63
+ .fillColor('#111')
64
+ .text('Title', { align: 'center', width: 500 })
65
+ .moveDown()
66
+ .textPosition(50, 700)
67
+ .text('Body copy that wraps automatically.');
68
+
69
+ doc.moveTo(50, 100).lineTo(200, 100).stroke();
70
+ doc.rect(50, 120, 100, 60).fillColor('red').fill();
71
+ doc.circle(300, 200, 40).strokeColor('blue').lineWidth(2).stroke();
72
+ ```
73
+
74
+ ### Images
75
+
76
+ ```js
77
+ doc.image('./logo.png', 50, 700, { width: 120 });
78
+ doc.image('./photo.jpg', 50, 500, { width: 200, height: 150 });
79
+ ```
80
+
81
+ ### Output
82
+
83
+ ```js
84
+ const buf = await doc.toBuffer();
85
+ await doc.save('out.pdf');
86
+
87
+ import { createWriteStream } from 'node:fs';
88
+ doc.pipe(createWriteStream('piped.pdf'));
89
+ await doc.end();
90
+ ```
91
+
92
+ ## Examples
93
+
94
+ ```bash
95
+ npm run example
96
+ npm run example:invoice
97
+ ```
98
+
99
+ ## License
100
+
101
+ MIT — free to use, modify, and distribute.
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "anas-pdf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A free, open-source pure Node.js library for creating PDF documents",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./src/index.js",
10
+ "default": "./src/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "src",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js",
20
+ "example": "node examples/hello.js",
21
+ "example:invoice": "node examples/invoice.js"
22
+ },
23
+ "keywords": [
24
+ "pdf",
25
+ "pdf-generator",
26
+ "pdf-writer",
27
+ "document",
28
+ "nodejs",
29
+ "open-source"
30
+ ],
31
+ "author": "Anas",
32
+ "license": "MIT",
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/anas/anas-pdf.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/anas/anas-pdf/issues"
42
+ },
43
+ "homepage": "https://github.com/anas/anas-pdf#readme"
44
+ }
@@ -0,0 +1,558 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { PDFWriter } from './writer.js';
3
+ import { loadImage } from './image.js';
4
+ import { PageState } from './page.js';
5
+ import { resolveFont, wrapText, measureText } from './fonts.js';
6
+ import {
7
+ resolvePageSize,
8
+ parseColor,
9
+ escapePdfString,
10
+ pdfNumber,
11
+ rgbOps,
12
+ } from './utils.js';
13
+
14
+ /**
15
+ * Fluent PDF document builder.
16
+ */
17
+ export class PDFDocument {
18
+ /**
19
+ * @param {{
20
+ * size?: string | [number, number],
21
+ * margin?: number | { top?: number, right?: number, bottom?: number, left?: number },
22
+ * info?: { title?: string, author?: string, creator?: string, subject?: string },
23
+ * autoFirstPage?: boolean,
24
+ * }} [options]
25
+ */
26
+ constructor(options = {}) {
27
+ const [width, height] = resolvePageSize(options.size ?? 'A4');
28
+ this.pageWidth = width;
29
+ this.pageHeight = height;
30
+
31
+ const m = options.margin ?? 50;
32
+ if (typeof m === 'number') {
33
+ this.margin = { top: m, right: m, bottom: m, left: m };
34
+ } else {
35
+ this.margin = {
36
+ top: m.top ?? 50,
37
+ right: m.right ?? 50,
38
+ bottom: m.bottom ?? 50,
39
+ left: m.left ?? 50,
40
+ };
41
+ }
42
+
43
+ this.info = {
44
+ creator: 'anas-pdf',
45
+ ...(options.info ?? {}),
46
+ };
47
+
48
+ /** @type {PageState[]} */
49
+ this._pages = [];
50
+ /** @type {Map<string, { id: number, pdfName: string }>} */
51
+ this._fonts = new Map();
52
+ /** @type {Map<string, { id: number, width: number, height: number, smaskId?: number }>} */
53
+ this._images = new Map();
54
+ this._imageCounter = 0;
55
+
56
+ this._fontName = 'Helvetica';
57
+ this._fontSize = 12;
58
+ this._fillColor = [0, 0, 0];
59
+ this._strokeColor = [0, 0, 0];
60
+ this._lineWidth = 1;
61
+ this._x = this.margin.left;
62
+ this._y = this.pageHeight - this.margin.top;
63
+ this._lineGap = 0.2;
64
+ this._finalized = false;
65
+ /** @type {import('node:stream').Writable[]} */
66
+ this._pipes = [];
67
+
68
+ this._writer = new PDFWriter();
69
+
70
+ if (options.autoFirstPage !== false) {
71
+ this.addPage();
72
+ }
73
+ }
74
+
75
+ /** @returns {PageState} */
76
+ get _page() {
77
+ if (!this._pages.length) {
78
+ throw new Error('No pages in document. Call addPage() first.');
79
+ }
80
+ return this._pages[this._pages.length - 1];
81
+ }
82
+
83
+ /**
84
+ * Add a new page.
85
+ * @param {{ size?: string | [number, number] }} [options]
86
+ */
87
+ addPage(options = {}) {
88
+ if (options.size) {
89
+ const [w, h] = resolvePageSize(options.size);
90
+ this.pageWidth = w;
91
+ this.pageHeight = h;
92
+ }
93
+ const page = new PageState(this.pageWidth, this.pageHeight);
94
+ this._pages.push(page);
95
+ this._x = this.margin.left;
96
+ this._y = this.pageHeight - this.margin.top;
97
+ return this;
98
+ }
99
+
100
+ /**
101
+ * @param {string} name
102
+ */
103
+ font(name) {
104
+ resolveFont(name); // validate
105
+ this._fontName = name;
106
+ return this;
107
+ }
108
+
109
+ /**
110
+ * @param {number} size
111
+ */
112
+ fontSize(size) {
113
+ this._fontSize = Number(size);
114
+ return this;
115
+ }
116
+
117
+ /**
118
+ * @param {string | number | [number, number, number]} color
119
+ */
120
+ fillColor(color) {
121
+ this._fillColor = parseColor(color);
122
+ return this;
123
+ }
124
+
125
+ /**
126
+ * @param {string | number | [number, number, number]} color
127
+ */
128
+ strokeColor(color) {
129
+ this._strokeColor = parseColor(color);
130
+ return this;
131
+ }
132
+
133
+ /**
134
+ * Alias for fillColor (text color).
135
+ * @param {string | number | [number, number, number]} color
136
+ */
137
+ color(color) {
138
+ return this.fillColor(color);
139
+ }
140
+
141
+ /**
142
+ * @param {number} width
143
+ */
144
+ lineWidth(width) {
145
+ this._lineWidth = Number(width);
146
+ return this;
147
+ }
148
+
149
+ /**
150
+ * @param {number} x
151
+ * @param {number} y
152
+ */
153
+ moveTo(x, y) {
154
+ this._page.ops.push(`${pdfNumber(x)} ${pdfNumber(y)} m`);
155
+ this._pathOpen = true;
156
+ return this;
157
+ }
158
+
159
+ /**
160
+ * @param {number} x
161
+ * @param {number} y
162
+ */
163
+ lineTo(x, y) {
164
+ this._page.ops.push(`${pdfNumber(x)} ${pdfNumber(y)} l`);
165
+ return this;
166
+ }
167
+
168
+ /**
169
+ * @param {number} x
170
+ * @param {number} y
171
+ * @param {number} w
172
+ * @param {number} h
173
+ */
174
+ rect(x, y, w, h) {
175
+ this._page.ops.push(`${pdfNumber(x)} ${pdfNumber(y)} ${pdfNumber(w)} ${pdfNumber(h)} re`);
176
+ this._pathOpen = true;
177
+ return this;
178
+ }
179
+
180
+ /**
181
+ * Approximate circle with Bezier curves.
182
+ * @param {number} cx
183
+ * @param {number} cy
184
+ * @param {number} r
185
+ */
186
+ circle(cx, cy, r) {
187
+ const k = 0.5522847498307936;
188
+ const ox = r * k;
189
+ const oy = r * k;
190
+ const ops = this._page.ops;
191
+ ops.push(`${pdfNumber(cx - r)} ${pdfNumber(cy)} m`);
192
+ ops.push(
193
+ `${pdfNumber(cx - r)} ${pdfNumber(cy + oy)} ${pdfNumber(cx - ox)} ${pdfNumber(cy + r)} ${pdfNumber(cx)} ${pdfNumber(cy + r)} c`,
194
+ );
195
+ ops.push(
196
+ `${pdfNumber(cx + ox)} ${pdfNumber(cy + r)} ${pdfNumber(cx + r)} ${pdfNumber(cy + oy)} ${pdfNumber(cx + r)} ${pdfNumber(cy)} c`,
197
+ );
198
+ ops.push(
199
+ `${pdfNumber(cx + r)} ${pdfNumber(cy - oy)} ${pdfNumber(cx + ox)} ${pdfNumber(cy - r)} ${pdfNumber(cx)} ${pdfNumber(cy - r)} c`,
200
+ );
201
+ ops.push(
202
+ `${pdfNumber(cx - ox)} ${pdfNumber(cy - r)} ${pdfNumber(cx - r)} ${pdfNumber(cy - oy)} ${pdfNumber(cx - r)} ${pdfNumber(cy)} c`,
203
+ );
204
+ this._pathOpen = true;
205
+ return this;
206
+ }
207
+
208
+ stroke() {
209
+ this._applyStrokeStyle();
210
+ this._page.ops.push('S');
211
+ this._pathOpen = false;
212
+ return this;
213
+ }
214
+
215
+ fill() {
216
+ this._applyFillStyle();
217
+ this._page.ops.push('f');
218
+ this._pathOpen = false;
219
+ return this;
220
+ }
221
+
222
+ fillAndStroke() {
223
+ this._applyFillStyle();
224
+ this._applyStrokeStyle();
225
+ this._page.ops.push('B');
226
+ this._pathOpen = false;
227
+ return this;
228
+ }
229
+
230
+ /**
231
+ * Move the text cursor.
232
+ * @param {number} x
233
+ * @param {number} y
234
+ */
235
+ textPosition(x, y) {
236
+ this._x = x;
237
+ this._y = y;
238
+ return this;
239
+ }
240
+
241
+ /**
242
+ * Move down by n lines (relative to current font size).
243
+ * @param {number} [lines]
244
+ */
245
+ moveDown(lines = 1) {
246
+ const leading = this._fontSize * (1 + this._lineGap);
247
+ this._y -= leading * lines;
248
+ return this;
249
+ }
250
+
251
+ /**
252
+ * Move across by n character-widths of space (approx).
253
+ * @param {number} [n]
254
+ */
255
+ moveRight(n = 1) {
256
+ this._x += this._fontSize * 0.5 * n;
257
+ return this;
258
+ }
259
+
260
+ /**
261
+ * Draw text at the current cursor (or x,y if provided).
262
+ * @param {string} text
263
+ * @param {{
264
+ * x?: number,
265
+ * y?: number,
266
+ * width?: number,
267
+ * align?: 'left' | 'center' | 'right',
268
+ * lineGap?: number,
269
+ * }} [options]
270
+ */
271
+ text(text, options = {}) {
272
+ const x = options.x ?? this._x;
273
+ let y = options.y ?? this._y;
274
+ const maxWidth =
275
+ options.width ??
276
+ this.pageWidth - this.margin.right - x;
277
+ const align = options.align ?? 'left';
278
+ const lineGap = options.lineGap ?? this._lineGap;
279
+ const leading = this._fontSize * (1 + lineGap);
280
+
281
+ this._ensureFont(this._fontName);
282
+ const lines = wrapText(String(text), this._fontName, this._fontSize, Math.max(1, maxWidth));
283
+ const fontResource = this._fonts.get(this._fontName);
284
+ const ops = this._page.ops;
285
+
286
+ for (const line of lines) {
287
+ if (y < this.margin.bottom + this._fontSize) {
288
+ this.addPage();
289
+ y = this.pageHeight - this.margin.top;
290
+ }
291
+
292
+ let drawX = x;
293
+ const lineWidth = measureText(line, this._fontName, this._fontSize);
294
+ if (align === 'center') drawX = x + (maxWidth - lineWidth) / 2;
295
+ else if (align === 'right') drawX = x + maxWidth - lineWidth;
296
+
297
+ ops.push(`${rgbOps(this._fillColor)} rg`);
298
+ ops.push('BT');
299
+ ops.push(`/${fontResource.resourceName} ${pdfNumber(this._fontSize)} Tf`);
300
+ ops.push(`${pdfNumber(drawX)} ${pdfNumber(y)} Td`);
301
+ ops.push(`(${escapePdfString(line)}) Tj`);
302
+ ops.push('ET');
303
+
304
+ y -= leading;
305
+ }
306
+
307
+ this._x = x;
308
+ this._y = y;
309
+ return this;
310
+ }
311
+
312
+ /**
313
+ * Embed and draw an image.
314
+ * @param {string | Buffer} source
315
+ * @param {number} x
316
+ * @param {number} y
317
+ * @param {{ width?: number, height?: number }} [options]
318
+ */
319
+ image(source, x, y, options = {}) {
320
+ const key = this._registerImage(source);
321
+ const meta = this._images.get(key);
322
+ let w = options.width;
323
+ let h = options.height;
324
+ if (w != null && h == null) {
325
+ h = (w / meta.width) * meta.height;
326
+ } else if (h != null && w == null) {
327
+ w = (h / meta.height) * meta.width;
328
+ } else if (w == null && h == null) {
329
+ w = meta.width;
330
+ h = meta.height;
331
+ }
332
+ this._page.imageNames.add(meta.resourceName);
333
+ this._page.ops.push('q');
334
+ this._page.ops.push(
335
+ `${pdfNumber(w)} 0 0 ${pdfNumber(h)} ${pdfNumber(x)} ${pdfNumber(y)} cm`,
336
+ );
337
+ this._page.ops.push(`/${meta.resourceName} Do`);
338
+ this._page.ops.push('Q');
339
+ return this;
340
+ }
341
+
342
+ /**
343
+ * Pipe PDF bytes to a writable stream when finalized.
344
+ * @param {import('node:stream').Writable} dest
345
+ */
346
+ pipe(dest) {
347
+ this._pipes.push(dest);
348
+ return dest;
349
+ }
350
+
351
+ /**
352
+ * @returns {Promise<Buffer>}
353
+ */
354
+ async toBuffer() {
355
+ const buf = this._build();
356
+ await this._flushPipes(buf);
357
+ return buf;
358
+ }
359
+
360
+ /**
361
+ * @param {string} path
362
+ */
363
+ async save(path) {
364
+ const buf = await this.toBuffer();
365
+ await writeFile(path, buf);
366
+ return path;
367
+ }
368
+
369
+ /**
370
+ * End the document (for stream usage).
371
+ */
372
+ async end() {
373
+ const buf = await this.toBuffer();
374
+ return buf;
375
+ }
376
+
377
+ // --- internals ---
378
+
379
+ _applyFillStyle() {
380
+ this._page.ops.push(`${rgbOps(this._fillColor)} rg`);
381
+ }
382
+
383
+ _applyStrokeStyle() {
384
+ this._page.ops.push(`${pdfNumber(this._lineWidth)} w`);
385
+ this._page.ops.push(`${rgbOps(this._strokeColor)} RG`);
386
+ }
387
+
388
+ /**
389
+ * @param {string} name
390
+ */
391
+ _ensureFont(name) {
392
+ if (this._fonts.has(name)) return;
393
+ const font = resolveFont(name);
394
+ const id = this._writer.reserve();
395
+ const resourceName = `F${this._fonts.size + 1}`;
396
+ this._writer.set(
397
+ id,
398
+ `<<\n/Type /Font\n/Subtype /Type1\n/BaseFont /${font.pdfName}\n/Encoding /WinAnsiEncoding\n>>`,
399
+ );
400
+ this._fonts.set(name, { id, pdfName: font.pdfName, resourceName });
401
+ }
402
+
403
+ /**
404
+ * @param {string | Buffer} source
405
+ */
406
+ _registerImage(source) {
407
+ const cacheKey = Buffer.isBuffer(source)
408
+ ? `buf:${source.length}:${source[0]}:${source[10]}:${source[100] ?? 0}`
409
+ : `path:${source}`;
410
+
411
+ if (this._images.has(cacheKey)) return cacheKey;
412
+
413
+ const img = loadImage(source);
414
+ this._imageCounter += 1;
415
+ const resourceName = `Im${this._imageCounter}`;
416
+ const id = this._writer.reserve();
417
+
418
+ let smaskId;
419
+ if (img.smask) {
420
+ smaskId = this._writer.addStream(
421
+ {
422
+ Type: '/XObject',
423
+ Subtype: '/Image',
424
+ Width: img.width,
425
+ Height: img.height,
426
+ ColorSpace: '/DeviceGray',
427
+ BitsPerComponent: 8,
428
+ Filter: '/FlateDecode',
429
+ },
430
+ img.smask,
431
+ );
432
+ }
433
+
434
+ const dict = {
435
+ Type: '/XObject',
436
+ Subtype: '/Image',
437
+ Width: img.width,
438
+ Height: img.height,
439
+ ColorSpace: `/${img.colorSpace}`,
440
+ BitsPerComponent: img.bitsPerComponent,
441
+ };
442
+ if (img.filter) dict.Filter = `/${img.filter}`;
443
+ if (smaskId) dict.SMask = `${smaskId} 0 R`;
444
+
445
+ // Use addStream via set after building manually — writer.addStream allocates new id
446
+ const entries = Object.entries(dict)
447
+ .map(([k, v]) => `/${k} ${v}`)
448
+ .join('\n');
449
+ const data = img.data;
450
+ const header = `<<\n${entries}\n/Length ${data.length}\n>>\nstream\n`;
451
+ this._writer.set(
452
+ id,
453
+ Buffer.concat([
454
+ Buffer.from(header, 'utf8'),
455
+ data,
456
+ Buffer.from('\nendstream', 'utf8'),
457
+ ]),
458
+ );
459
+
460
+ this._images.set(cacheKey, {
461
+ id,
462
+ width: img.width,
463
+ height: img.height,
464
+ resourceName,
465
+ smaskId,
466
+ });
467
+ return cacheKey;
468
+ }
469
+
470
+ _build() {
471
+ if (this._finalized) {
472
+ throw new Error('Document already finalized');
473
+ }
474
+ if (!this._pages.length) {
475
+ this.addPage();
476
+ }
477
+
478
+ // Ensure default font exists even if no text was drawn
479
+ this._ensureFont(this._fontName);
480
+
481
+ const pageIds = [];
482
+ for (const page of this._pages) {
483
+ const contentId = this._writer.addStream({}, page.ops.join('\n') + '\n');
484
+
485
+ const fontEntries = [...this._fonts.values()]
486
+ .map((f) => `/${f.resourceName} ${f.id} 0 R`)
487
+ .join(' ');
488
+
489
+ const imageEntries = [...page.imageNames]
490
+ .map((name) => {
491
+ const meta = [...this._images.values()].find((i) => i.resourceName === name);
492
+ return meta ? `/${name} ${meta.id} 0 R` : '';
493
+ })
494
+ .filter(Boolean)
495
+ .join(' ');
496
+
497
+ let resources = `<<\n/Font << ${fontEntries} >>`;
498
+ if (imageEntries) {
499
+ resources += `\n/XObject << ${imageEntries} >>`;
500
+ }
501
+ resources += `\n>>`;
502
+
503
+ const pageId = this._writer.add(
504
+ `<<\n/Type /Page\n/Parent __PAGES__ 0 R\n/MediaBox [0 0 ${pdfNumber(page.width)} ${pdfNumber(page.height)}]\n/Contents ${contentId} 0 R\n/Resources ${resources}\n>>`,
505
+ );
506
+ pageIds.push(pageId);
507
+ }
508
+
509
+ const pagesId = this._writer.reserve();
510
+ const kids = pageIds.map((id) => `${id} 0 R`).join(' ');
511
+ this._writer.set(
512
+ pagesId,
513
+ `<<\n/Type /Pages\n/Kids [${kids}]\n/Count ${pageIds.length}\n>>`,
514
+ );
515
+
516
+ // Patch Parent refs
517
+ for (const pageId of pageIds) {
518
+ const body = this._writer.objects[pageId].toString('utf8');
519
+ this._writer.set(pageId, body.replace('__PAGES__', String(pagesId)));
520
+ }
521
+
522
+ const catalogId = this._writer.add(
523
+ `<<\n/Type /Catalog\n/Pages ${pagesId} 0 R\n>>`,
524
+ );
525
+
526
+ this._finalized = true;
527
+ return this._writer.build({ catalogId, info: this.info });
528
+ }
529
+
530
+ /**
531
+ * @param {Buffer} buf
532
+ */
533
+ async _flushPipes(buf) {
534
+ for (const dest of this._pipes) {
535
+ await writeToStream(dest, buf);
536
+ }
537
+ }
538
+ }
539
+
540
+ /**
541
+ * @param {import('node:stream').Writable} dest
542
+ * @param {Buffer} buf
543
+ */
544
+ function writeToStream(dest, buf) {
545
+ return new Promise((resolve, reject) => {
546
+ if (dest.destroyed) {
547
+ resolve();
548
+ return;
549
+ }
550
+ dest.write(buf, (err) => {
551
+ if (err) {
552
+ reject(err);
553
+ return;
554
+ }
555
+ dest.end(() => resolve());
556
+ });
557
+ });
558
+ }
package/src/fonts.js ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Standard PDF Type1 font metrics (WinAnsi-ish widths for ASCII + common chars).
3
+ * Widths are in 1000-unit glyph space.
4
+ */
5
+
6
+ const HELVETICA_WIDTHS = createUniformWidths(556, {
7
+ ' ': 278, '!': 278, '"': 355, '#': 556, '$': 556, '%': 889, '&': 667, "'": 191,
8
+ '(': 333, ')': 333, '*': 389, '+': 584, ',': 278, '-': 333, '.': 278, '/': 278,
9
+ '0': 556, '1': 556, '2': 556, '3': 556, '4': 556, '5': 556, '6': 556, '7': 556,
10
+ '8': 556, '9': 556, ':': 278, ';': 278, '<': 584, '=': 584, '>': 584, '?': 556,
11
+ '@': 1015, A: 667, B: 667, C: 722, D: 722, E: 667, F: 611, G: 778,
12
+ H: 722, I: 278, J: 500, K: 667, L: 556, M: 833, N: 722, O: 778,
13
+ P: 667, Q: 778, R: 722, S: 667, T: 611, U: 722, V: 667, W: 944,
14
+ X: 667, Y: 667, Z: 611, '[': 278, '\\': 278, ']': 278, '^': 469, _: 556,
15
+ '`': 333, a: 556, b: 556, c: 500, d: 556, e: 556, f: 278, g: 556,
16
+ h: 556, i: 222, j: 222, k: 500, l: 222, m: 833, n: 556, o: 556,
17
+ p: 556, q: 556, r: 333, s: 500, t: 278, u: 556, v: 500, w: 722,
18
+ x: 500, y: 500, z: 500, '{': 334, '|': 260, '}': 334, '~': 584,
19
+ });
20
+
21
+ const HELVETICA_BOLD_WIDTHS = createUniformWidths(611, {
22
+ ' ': 278, '!': 333, '"': 474, '#': 556, '$': 556, '%': 889, '&': 722, "'": 238,
23
+ '(': 333, ')': 333, '*': 389, '+': 584, ',': 278, '-': 333, '.': 278, '/': 278,
24
+ '0': 556, '1': 556, '2': 556, '3': 556, '4': 556, '5': 556, '6': 556, '7': 556,
25
+ '8': 556, '9': 556, ':': 333, ';': 333, '<': 584, '=': 584, '>': 584, '?': 611,
26
+ '@': 975, A: 722, B: 722, C: 722, D: 722, E: 667, F: 611, G: 778,
27
+ H: 722, I: 278, J: 556, K: 722, L: 611, M: 833, N: 722, O: 778,
28
+ P: 667, Q: 778, R: 722, S: 667, T: 611, U: 722, V: 667, W: 944,
29
+ X: 667, Y: 667, Z: 611, '[': 333, '\\': 278, ']': 333, '^': 584, _: 556,
30
+ '`': 333, a: 556, b: 611, c: 556, d: 611, e: 556, f: 333, g: 611,
31
+ h: 611, i: 278, j: 278, k: 556, l: 278, m: 889, n: 611, o: 611,
32
+ p: 611, q: 611, r: 389, s: 556, t: 333, u: 611, v: 556, w: 778,
33
+ x: 556, y: 556, z: 500, '{': 389, '|': 280, '}': 389, '~': 584,
34
+ });
35
+
36
+ const TIMES_WIDTHS = createUniformWidths(500, {
37
+ ' ': 250, '!': 333, '"': 408, '#': 500, '$': 500, '%': 833, '&': 778, "'": 180,
38
+ '(': 333, ')': 333, '*': 500, '+': 564, ',': 250, '-': 333, '.': 250, '/': 278,
39
+ '0': 500, '1': 500, '2': 500, '3': 500, '4': 500, '5': 500, '6': 500, '7': 500,
40
+ '8': 500, '9': 500, ':': 278, ';': 278, '<': 564, '=': 564, '>': 564, '?': 444,
41
+ '@': 921, A: 722, B: 667, C: 667, D: 722, E: 611, F: 556, G: 722,
42
+ H: 722, I: 333, J: 389, K: 722, L: 611, M: 889, N: 722, O: 722,
43
+ P: 556, Q: 722, R: 667, S: 556, T: 611, U: 722, V: 722, W: 944,
44
+ X: 722, Y: 722, Z: 611, '[': 333, '\\': 278, ']': 333, '^': 469, _: 500,
45
+ '`': 333, a: 444, b: 500, c: 444, d: 500, e: 444, f: 333, g: 500,
46
+ h: 500, i: 278, j: 278, k: 500, l: 278, m: 778, n: 500, o: 500,
47
+ p: 500, q: 500, r: 333, s: 389, t: 278, u: 500, v: 500, w: 722,
48
+ x: 500, y: 500, z: 444, '{': 480, '|': 200, '}': 480, '~': 541,
49
+ });
50
+
51
+ const COURIER_WIDTH = 600;
52
+
53
+ /**
54
+ * @param {number} fallback
55
+ * @param {Record<string, number>} map
56
+ */
57
+ function createUniformWidths(fallback, map) {
58
+ return { fallback, map };
59
+ }
60
+
61
+ /** @type {Record<string, { pdfName: string, widths: { fallback: number, map: Record<string, number> } }>} */
62
+ export const FONTS = {
63
+ Helvetica: { pdfName: 'Helvetica', widths: HELVETICA_WIDTHS },
64
+ 'Helvetica-Bold': { pdfName: 'Helvetica-Bold', widths: HELVETICA_BOLD_WIDTHS },
65
+ 'Helvetica-Oblique': { pdfName: 'Helvetica-Oblique', widths: HELVETICA_WIDTHS },
66
+ 'Helvetica-BoldOblique': { pdfName: 'Helvetica-BoldOblique', widths: HELVETICA_BOLD_WIDTHS },
67
+ Times: { pdfName: 'Times-Roman', widths: TIMES_WIDTHS },
68
+ 'Times-Roman': { pdfName: 'Times-Roman', widths: TIMES_WIDTHS },
69
+ 'Times-Bold': { pdfName: 'Times-Bold', widths: TIMES_WIDTHS },
70
+ 'Times-Italic': { pdfName: 'Times-Italic', widths: TIMES_WIDTHS },
71
+ 'Times-BoldItalic': { pdfName: 'Times-BoldItalic', widths: TIMES_WIDTHS },
72
+ Courier: {
73
+ pdfName: 'Courier',
74
+ widths: { fallback: COURIER_WIDTH, map: {} },
75
+ },
76
+ 'Courier-Bold': {
77
+ pdfName: 'Courier-Bold',
78
+ widths: { fallback: COURIER_WIDTH, map: {} },
79
+ },
80
+ 'Courier-Oblique': {
81
+ pdfName: 'Courier-Oblique',
82
+ widths: { fallback: COURIER_WIDTH, map: {} },
83
+ },
84
+ 'Courier-BoldOblique': {
85
+ pdfName: 'Courier-BoldOblique',
86
+ widths: { fallback: COURIER_WIDTH, map: {} },
87
+ },
88
+ };
89
+
90
+ /**
91
+ * @param {string} fontName
92
+ */
93
+ export function resolveFont(fontName) {
94
+ const font = FONTS[fontName];
95
+ if (!font) {
96
+ throw new Error(
97
+ `Unknown font "${fontName}". Available: ${Object.keys(FONTS).join(', ')}`,
98
+ );
99
+ }
100
+ return font;
101
+ }
102
+
103
+ /**
104
+ * @param {string} text
105
+ * @param {string} fontName
106
+ * @param {number} fontSize
107
+ */
108
+ export function measureText(text, fontName, fontSize) {
109
+ const { widths } = resolveFont(fontName);
110
+ let w = 0;
111
+ for (const ch of String(text)) {
112
+ w += widths.map[ch] ?? widths.fallback;
113
+ }
114
+ return (w * fontSize) / 1000;
115
+ }
116
+
117
+ /**
118
+ * Wrap text to fit within maxWidth.
119
+ * @param {string} text
120
+ * @param {string} fontName
121
+ * @param {number} fontSize
122
+ * @param {number} maxWidth
123
+ * @returns {string[]}
124
+ */
125
+ export function wrapText(text, fontName, fontSize, maxWidth) {
126
+ const paragraphs = String(text).split(/\r?\n/);
127
+ const lines = [];
128
+
129
+ for (const paragraph of paragraphs) {
130
+ if (paragraph.length === 0) {
131
+ lines.push('');
132
+ continue;
133
+ }
134
+ const words = paragraph.split(/\s+/);
135
+ let current = '';
136
+ for (const word of words) {
137
+ const candidate = current ? `${current} ${word}` : word;
138
+ if (measureText(candidate, fontName, fontSize) <= maxWidth) {
139
+ current = candidate;
140
+ } else {
141
+ if (current) lines.push(current);
142
+ if (measureText(word, fontName, fontSize) <= maxWidth) {
143
+ current = word;
144
+ } else {
145
+ // Hard-break oversized words
146
+ let chunk = '';
147
+ for (const ch of word) {
148
+ const next = chunk + ch;
149
+ if (measureText(next, fontName, fontSize) <= maxWidth) {
150
+ chunk = next;
151
+ } else {
152
+ if (chunk) lines.push(chunk);
153
+ chunk = ch;
154
+ }
155
+ }
156
+ current = chunk;
157
+ }
158
+ }
159
+ }
160
+ if (current) lines.push(current);
161
+ }
162
+
163
+ return lines.length ? lines : [''];
164
+ }
package/src/image.js ADDED
@@ -0,0 +1,237 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { inflateSync, deflateSync } from 'node:zlib';
3
+
4
+ /**
5
+ * Load an image from a file path or Buffer.
6
+ * @param {string | Buffer} source
7
+ * @returns {{
8
+ * width: number,
9
+ * height: number,
10
+ * colorSpace: string,
11
+ * bitsPerComponent: number,
12
+ * filter?: string,
13
+ * decodeParms?: string,
14
+ * data: Buffer,
15
+ * smask?: Buffer,
16
+ * }}
17
+ */
18
+ export function loadImage(source) {
19
+ const buf = Buffer.isBuffer(source) ? source : readFileSync(source);
20
+
21
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
22
+ return parseJpeg(buf);
23
+ }
24
+ if (
25
+ buf[0] === 0x89 &&
26
+ buf[1] === 0x50 &&
27
+ buf[2] === 0x4e &&
28
+ buf[3] === 0x47
29
+ ) {
30
+ return parsePng(buf);
31
+ }
32
+ throw new Error('Unsupported image format. Use PNG or JPEG.');
33
+ }
34
+
35
+ /**
36
+ * @param {Buffer} buf
37
+ */
38
+ function parseJpeg(buf) {
39
+ let offset = 2;
40
+ let width = 0;
41
+ let height = 0;
42
+ let colorSpace = 'DeviceRGB';
43
+
44
+ while (offset < buf.length) {
45
+ if (buf[offset] !== 0xff) {
46
+ offset += 1;
47
+ continue;
48
+ }
49
+ const marker = buf[offset + 1];
50
+ // SOF0 / SOF2
51
+ if (marker === 0xc0 || marker === 0xc2) {
52
+ height = buf.readUInt16BE(offset + 5);
53
+ width = buf.readUInt16BE(offset + 7);
54
+ const components = buf[offset + 9];
55
+ if (components === 1) colorSpace = 'DeviceGray';
56
+ else if (components === 4) colorSpace = 'DeviceCMYK';
57
+ else colorSpace = 'DeviceRGB';
58
+ break;
59
+ }
60
+ if (marker === 0xd9 || marker === 0xda) break;
61
+ const len = buf.readUInt16BE(offset + 2);
62
+ offset += 2 + len;
63
+ }
64
+
65
+ if (!width || !height) {
66
+ throw new Error('Could not read JPEG dimensions');
67
+ }
68
+
69
+ return {
70
+ width,
71
+ height,
72
+ colorSpace,
73
+ bitsPerComponent: 8,
74
+ filter: 'DCTDecode',
75
+ data: buf,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Minimal PNG decoder supporting 8-bit grayscale/RGB/RGBA (non-interlaced).
81
+ * @param {Buffer} buf
82
+ */
83
+ function parsePng(buf) {
84
+ if (buf.toString('ascii', 1, 4) !== 'PNG') {
85
+ throw new Error('Invalid PNG signature');
86
+ }
87
+
88
+ let offset = 8;
89
+ let width = 0;
90
+ let height = 0;
91
+ let bitDepth = 8;
92
+ let colorType = 2;
93
+ /** @type {Buffer[]} */
94
+ const idatParts = [];
95
+
96
+ while (offset + 8 <= buf.length) {
97
+ const length = buf.readUInt32BE(offset);
98
+ const type = buf.toString('ascii', offset + 4, offset + 8);
99
+ const data = buf.subarray(offset + 8, offset + 8 + length);
100
+ offset += 12 + length; // length + type + data + crc
101
+
102
+ if (type === 'IHDR') {
103
+ width = data.readUInt32BE(0);
104
+ height = data.readUInt32BE(4);
105
+ bitDepth = data[8];
106
+ colorType = data[9];
107
+ const interlace = data[12];
108
+ if (bitDepth !== 8) {
109
+ throw new Error('Only 8-bit PNGs are supported');
110
+ }
111
+ if (interlace !== 0) {
112
+ throw new Error('Interlaced PNGs are not supported');
113
+ }
114
+ if (![0, 2, 4, 6].includes(colorType)) {
115
+ throw new Error('Unsupported PNG color type (use grayscale, RGB, or RGBA)');
116
+ }
117
+ } else if (type === 'IDAT') {
118
+ idatParts.push(data);
119
+ } else if (type === 'IEND') {
120
+ break;
121
+ }
122
+ }
123
+
124
+ if (!width || !height || idatParts.length === 0) {
125
+ throw new Error('Invalid or incomplete PNG');
126
+ }
127
+
128
+ const compressed = Buffer.concat(idatParts);
129
+ const inflated = inflateSync(compressed);
130
+
131
+ const channels = colorType === 0 ? 1 : colorType === 2 ? 3 : colorType === 4 ? 2 : 4;
132
+ const stride = width * channels;
133
+ const expected = (stride + 1) * height;
134
+ if (inflated.length < expected) {
135
+ throw new Error('PNG data truncated');
136
+ }
137
+
138
+ const rgb = Buffer.alloc(width * height * 3);
139
+ /** @type {Buffer | undefined} */
140
+ let alpha;
141
+
142
+ if (colorType === 6 || colorType === 4) {
143
+ alpha = Buffer.alloc(width * height);
144
+ }
145
+
146
+ let src = 0;
147
+ let dst = 0;
148
+ let aIdx = 0;
149
+ /** @type {Buffer | null} */
150
+ let prev = null;
151
+
152
+ for (let y = 0; y < height; y++) {
153
+ const filter = inflated[src++];
154
+ const row = inflated.subarray(src, src + stride);
155
+ src += stride;
156
+ const recon = Buffer.alloc(stride);
157
+
158
+ for (let i = 0; i < stride; i++) {
159
+ const x = row[i];
160
+ const a = i >= channels ? recon[i - channels] : 0;
161
+ const b = prev ? prev[i] : 0;
162
+ const c = prev && i >= channels ? prev[i - channels] : 0;
163
+ let val;
164
+ switch (filter) {
165
+ case 0:
166
+ val = x;
167
+ break;
168
+ case 1:
169
+ val = (x + a) & 0xff;
170
+ break;
171
+ case 2:
172
+ val = (x + b) & 0xff;
173
+ break;
174
+ case 3:
175
+ val = (x + ((a + b) >> 1)) & 0xff;
176
+ break;
177
+ case 4:
178
+ val = (x + paeth(a, b, c)) & 0xff;
179
+ break;
180
+ default:
181
+ throw new Error(`Unsupported PNG filter type: ${filter}`);
182
+ }
183
+ recon[i] = val;
184
+ }
185
+
186
+ for (let x = 0; x < width; x++) {
187
+ const i = x * channels;
188
+ if (colorType === 0) {
189
+ const g = recon[i];
190
+ rgb[dst++] = g;
191
+ rgb[dst++] = g;
192
+ rgb[dst++] = g;
193
+ } else if (colorType === 2) {
194
+ rgb[dst++] = recon[i];
195
+ rgb[dst++] = recon[i + 1];
196
+ rgb[dst++] = recon[i + 2];
197
+ } else if (colorType === 4) {
198
+ const g = recon[i];
199
+ rgb[dst++] = g;
200
+ rgb[dst++] = g;
201
+ rgb[dst++] = g;
202
+ alpha[aIdx++] = recon[i + 1];
203
+ } else {
204
+ rgb[dst++] = recon[i];
205
+ rgb[dst++] = recon[i + 1];
206
+ rgb[dst++] = recon[i + 2];
207
+ alpha[aIdx++] = recon[i + 3];
208
+ }
209
+ }
210
+ prev = recon;
211
+ }
212
+
213
+ const result = {
214
+ width,
215
+ height,
216
+ colorSpace: 'DeviceRGB',
217
+ bitsPerComponent: 8,
218
+ filter: 'FlateDecode',
219
+ data: deflateSync(rgb),
220
+ };
221
+
222
+ if (alpha) {
223
+ result.smask = deflateSync(alpha);
224
+ }
225
+
226
+ return result;
227
+ }
228
+
229
+ function paeth(a, b, c) {
230
+ const p = a + b - c;
231
+ const pa = Math.abs(p - a);
232
+ const pb = Math.abs(p - b);
233
+ const pc = Math.abs(p - c);
234
+ if (pa <= pb && pa <= pc) return a;
235
+ if (pb <= pc) return b;
236
+ return c;
237
+ }
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { PDFDocument } from './document.js';
2
+ export { PAGE_SIZES } from './utils.js';
3
+ export { FONTS } from './fonts.js';
package/src/page.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Per-page content stream accumulator.
3
+ * Used internally by PDFDocument.
4
+ */
5
+ export class PageState {
6
+ /**
7
+ * @param {number} width
8
+ * @param {number} height
9
+ */
10
+ constructor(width, height) {
11
+ this.width = width;
12
+ this.height = height;
13
+ /** @type {string[]} */
14
+ this.ops = [];
15
+ /** @type {Set<string>} */
16
+ this.imageNames = new Set();
17
+ }
18
+
19
+ /**
20
+ * @param {string} op
21
+ */
22
+ push(op) {
23
+ this.ops.push(op);
24
+ }
25
+
26
+ /**
27
+ * @returns {string}
28
+ */
29
+ toContent() {
30
+ return this.ops.join('\n') + '\n';
31
+ }
32
+ }
package/src/utils.js ADDED
@@ -0,0 +1,106 @@
1
+ /** @typedef {[number, number, number]} RGB */
2
+
3
+ export const PAGE_SIZES = {
4
+ A4: [595.28, 841.89],
5
+ Letter: [612, 792],
6
+ Legal: [612, 1008],
7
+ A3: [841.89, 1190.55],
8
+ A5: [419.53, 595.28],
9
+ };
10
+
11
+ /**
12
+ * @param {string | [number, number]} size
13
+ * @returns {[number, number]}
14
+ */
15
+ export function resolvePageSize(size = 'A4') {
16
+ if (Array.isArray(size) && size.length === 2) {
17
+ return [Number(size[0]), Number(size[1])];
18
+ }
19
+ const key = String(size);
20
+ if (PAGE_SIZES[key]) return [...PAGE_SIZES[key]];
21
+ throw new Error(`Unknown page size: ${size}. Use A4, Letter, Legal, A3, A5, or [width, height].`);
22
+ }
23
+
24
+ /**
25
+ * @param {string | RGB | number} color
26
+ * @returns {RGB}
27
+ */
28
+ export function parseColor(color) {
29
+ if (typeof color === 'number') {
30
+ const n = Math.max(0, Math.min(1, color));
31
+ return [n, n, n];
32
+ }
33
+ if (Array.isArray(color) && color.length >= 3) {
34
+ return [
35
+ clamp01(color[0]),
36
+ clamp01(color[1]),
37
+ clamp01(color[2]),
38
+ ];
39
+ }
40
+ if (typeof color === 'string') {
41
+ const hex = color.trim().replace(/^#/, '');
42
+ if (/^[0-9a-fA-F]{3}$/.test(hex)) {
43
+ return [
44
+ parseInt(hex[0] + hex[0], 16) / 255,
45
+ parseInt(hex[1] + hex[1], 16) / 255,
46
+ parseInt(hex[2] + hex[2], 16) / 255,
47
+ ];
48
+ }
49
+ if (/^[0-9a-fA-F]{6}$/.test(hex)) {
50
+ return [
51
+ parseInt(hex.slice(0, 2), 16) / 255,
52
+ parseInt(hex.slice(2, 4), 16) / 255,
53
+ parseInt(hex.slice(4, 6), 16) / 255,
54
+ ];
55
+ }
56
+ const named = NAMED_COLORS[hex.toLowerCase()];
57
+ if (named) return [...named];
58
+ }
59
+ throw new Error(`Invalid color: ${color}`);
60
+ }
61
+
62
+ const NAMED_COLORS = {
63
+ black: [0, 0, 0],
64
+ white: [1, 1, 1],
65
+ red: [1, 0, 0],
66
+ green: [0, 0.5, 0],
67
+ blue: [0, 0, 1],
68
+ gray: [0.5, 0.5, 0.5],
69
+ grey: [0.5, 0.5, 0.5],
70
+ };
71
+
72
+ function clamp01(n) {
73
+ const v = Number(n);
74
+ if (Number.isNaN(v)) return 0;
75
+ return Math.max(0, Math.min(1, v));
76
+ }
77
+
78
+ /**
79
+ * Escape a string for PDF literal strings `(...)`.
80
+ * @param {string} str
81
+ */
82
+ export function escapePdfString(str) {
83
+ return String(str)
84
+ .replace(/\\/g, '\\\\')
85
+ .replace(/\(/g, '\\(')
86
+ .replace(/\)/g, '\\)')
87
+ .replace(/\r/g, '\\r')
88
+ .replace(/\n/g, '\\n');
89
+ }
90
+
91
+ /**
92
+ * Format a number for PDF content (trim trailing zeros).
93
+ * @param {number} n
94
+ */
95
+ export function pdfNumber(n) {
96
+ if (!Number.isFinite(n)) return '0';
97
+ const rounded = Math.round(n * 1000) / 1000;
98
+ return String(rounded);
99
+ }
100
+
101
+ /**
102
+ * @param {RGB} rgb
103
+ */
104
+ export function rgbOps(rgb) {
105
+ return `${pdfNumber(rgb[0])} ${pdfNumber(rgb[1])} ${pdfNumber(rgb[2])}`;
106
+ }
package/src/writer.js ADDED
@@ -0,0 +1,114 @@
1
+ import { escapePdfString } from './utils.js';
2
+
3
+ /**
4
+ * Low-level PDF object writer. Builds a PDF 1.4 document from numbered objects.
5
+ */
6
+ export class PDFWriter {
7
+ constructor() {
8
+ /** @type {Array<Buffer | null>} */
9
+ this.objects = [null]; // 1-indexed
10
+ }
11
+
12
+ /**
13
+ * Reserve an object number (content filled later).
14
+ * @returns {number}
15
+ */
16
+ reserve() {
17
+ this.objects.push(null);
18
+ return this.objects.length - 1;
19
+ }
20
+
21
+ /**
22
+ * @param {number} id
23
+ * @param {string | Buffer} body object body without "N 0 obj" wrapper
24
+ */
25
+ set(id, body) {
26
+ const content = Buffer.isBuffer(body) ? body : Buffer.from(String(body), 'utf8');
27
+ this.objects[id] = content;
28
+ }
29
+
30
+ /**
31
+ * Add a new object and return its id.
32
+ * @param {string | Buffer} body
33
+ * @returns {number}
34
+ */
35
+ add(body) {
36
+ const id = this.reserve();
37
+ this.set(id, body);
38
+ return id;
39
+ }
40
+
41
+ /**
42
+ * Add a stream object.
43
+ * @param {Record<string, string | number>} dict
44
+ * @param {Buffer | string} streamData
45
+ * @returns {number}
46
+ */
47
+ addStream(dict, streamData) {
48
+ const data = Buffer.isBuffer(streamData)
49
+ ? streamData
50
+ : Buffer.from(String(streamData), 'binary');
51
+ const entries = Object.entries(dict)
52
+ .map(([k, v]) => `/${k} ${v}`)
53
+ .join('\n');
54
+ const header = `<<\n${entries}\n/Length ${data.length}\n>>\nstream\n`;
55
+ const footer = '\nendstream';
56
+ return this.add(Buffer.concat([
57
+ Buffer.from(header, 'utf8'),
58
+ data,
59
+ Buffer.from(footer, 'utf8'),
60
+ ]));
61
+ }
62
+
63
+ /**
64
+ * Serialize the full PDF.
65
+ * @param {{
66
+ * catalogId: number,
67
+ * info?: { title?: string, author?: string, creator?: string, subject?: string },
68
+ * }} options
69
+ * @returns {Buffer}
70
+ */
71
+ build({ catalogId, info = {} }) {
72
+ let infoId = null;
73
+ if (info.title || info.author || info.creator || info.subject) {
74
+ const parts = [];
75
+ if (info.title) parts.push(`/Title (${escapePdfString(info.title)})`);
76
+ if (info.author) parts.push(`/Author (${escapePdfString(info.author)})`);
77
+ if (info.subject) parts.push(`/Subject (${escapePdfString(info.subject)})`);
78
+ if (info.creator) parts.push(`/Creator (${escapePdfString(info.creator)})`);
79
+ parts.push(`/Producer (anas-pdf)`);
80
+ infoId = this.add(`<<\n${parts.join('\n')}\n>>`);
81
+ }
82
+
83
+ const chunks = [Buffer.from('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n', 'binary')];
84
+ const offsets = [0];
85
+ let cursor = chunks[0].length;
86
+
87
+ for (let i = 1; i < this.objects.length; i++) {
88
+ const body = this.objects[i];
89
+ if (body == null) {
90
+ throw new Error(`PDF object ${i} was reserved but never set`);
91
+ }
92
+ offsets[i] = cursor;
93
+ const header = Buffer.from(`${i} 0 obj\n`, 'utf8');
94
+ const footer = Buffer.from('\nendobj\n', 'utf8');
95
+ chunks.push(header, body, footer);
96
+ cursor += header.length + body.length + footer.length;
97
+ }
98
+
99
+ const xrefOffset = cursor;
100
+ const count = this.objects.length;
101
+ let xref = `xref\n0 ${count}\n`;
102
+ xref += '0000000000 65535 f \n';
103
+ for (let i = 1; i < count; i++) {
104
+ xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
105
+ }
106
+
107
+ let trailer = `trailer\n<<\n/Size ${count}\n/Root ${catalogId} 0 R`;
108
+ if (infoId != null) trailer += `\n/Info ${infoId} 0 R`;
109
+ trailer += `\n>>\nstartxref\n${xrefOffset}\n%%EOF\n`;
110
+
111
+ chunks.push(Buffer.from(xref, 'utf8'), Buffer.from(trailer, 'utf8'));
112
+ return Buffer.concat(chunks);
113
+ }
114
+ }