@aglyn/shared-util-tools 1.0.0-beta.289 → 1.0.0-beta.290

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @aglyn/shared-util-tools
2
2
 
3
- General-purpose TypeScript helpers: type guards, array and object utilities, deep get/set, cloning, JSON and base64 serialization, plus a few larger standalone modules (a linear-time regex engine, an AES-GCM secret box, WCAG contrast math, HTML escaping). It is a dependency of most Aglyn packages and is usable on its own.
3
+ General-purpose TypeScript helpers: type guards, array and object utilities, deep get/set, cloning, JSON and base64 serialization, plus a few larger standalone modules (a linear-time regex engine, an AES-GCM secret box, WCAG contrast math, HTML escaping, a PDF writer). It is a dependency of most Aglyn packages and is usable on its own.
4
4
 
5
5
  > Beta. Published from the Aglyn monorepo under the `beta` dist-tag; APIs can change between beta releases.
6
6
 
@@ -50,6 +50,9 @@ By subpath only (kept off the root so they are not pulled into every consumer's
50
50
  - `@aglyn/shared-util-tools/escape-html` - `escapeHtml(value)`, escaping `& < > " '`.
51
51
  - `@aglyn/shared-util-tools/contrast` - `relativeLuminanceOfRgb`, `rgbChannelsOfHex`, `prefersDarkInk` and related sRGB helpers.
52
52
  - `@aglyn/shared-util-tools/serialize/php-serial-*` - wrappers over `php-serialize`.
53
+ - `@aglyn/shared-util-tools/pdf/pdf-writer` - `PdfWriter`, a PDF page layout with no PDF library under it: text in the standard Helvetica faces (left, right or centered, in any RGB color), paragraphs that wrap and run onto new pages, filled and stroked rectangles and rules, JPEG images fitted to a box, clickable links, tables whose cells wrap and whose header row repeats on every page, and a footer with page numbers. `pdfRgbFromHex` turns `#rrggbb` into its color.
54
+ - `@aglyn/shared-util-tools/pdf/pdf-text` - the text half: `toWinAnsiText` (any string as characters the standard fonts can draw: look-alikes swapped in, accents dropped, emoji removed, `?` for other scripts), `pdfString`, `measureText` and `wrapLines` by Adobe's Helvetica widths, and the quicker `textWidth`/`wrapText` estimate.
55
+ - `@aglyn/shared-util-tools/pdf/pdf-file` - the file half: `buildPdfFile` (pages of drawing operators, JPEG images as DCTDecode streams and URI links into a PDF with a correct cross-reference table, the same bytes for the same input), `readJpeg` (a JPEG's size and channels from its header) and `pdfNumber`/`pdfUri`.
53
56
 
54
57
  ## Usage
55
58
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/shared-util-tools",
3
- "version": "1.0.0-beta.289",
3
+ "version": "1.0.0-beta.290",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/shared-data-types": "1.0.0-beta.289",
28
+ "@aglyn/shared-data-types": "1.0.0-beta.290",
29
29
  "@swc/helpers": "0.5.23",
30
30
  "lodash-es": "^4.18.1",
31
31
  "php-serialize": "^5.1.3"
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /** A JPEG ready to draw: its bytes untouched, with what the image dictionary needs. */
18
+ export interface PdfJpegImage {
19
+ bytes: Uint8Array;
20
+ width: number;
21
+ height: number;
22
+ /** 1 gray, 3 RGB, 4 CMYK. */
23
+ components: 1 | 3 | 4;
24
+ /** An Adobe CMYK JPEG stores its ink inverted. */
25
+ invertedCmyk?: boolean;
26
+ }
27
+ /** A clickable area on a page, in points from the bottom-left corner, opening `url`. */
28
+ export interface PdfLinkArea {
29
+ x: number;
30
+ y: number;
31
+ width: number;
32
+ height: number;
33
+ url: string;
34
+ }
35
+ export interface PdfFilePage {
36
+ width: number;
37
+ height: number;
38
+ /** The page's content stream: drawing operators in printable ASCII. */
39
+ content: string;
40
+ links?: readonly PdfLinkArea[];
41
+ }
42
+ export interface PdfFileInput {
43
+ pages: readonly PdfFilePage[];
44
+ /** Images every page may draw as `/Im1`, `/Im2`, … in this order. */
45
+ images?: readonly PdfJpegImage[];
46
+ title: string;
47
+ /** The making software, in the document's properties; left out when not given. */
48
+ producer?: string;
49
+ }
50
+ /** A number as a PDF operand: two decimals at most, no trailing zeros. */
51
+ export declare function pdfNumber(value: number): string;
52
+ /**
53
+ * A link target as a PDF string literal's body. Only web and mail addresses
54
+ * are linked; a URI is 7-bit ASCII in a PDF, so anything else is
55
+ * percent-encoded. Null for an address that is not one of those.
56
+ */
57
+ export declare function pdfUri(url: string): string | null;
58
+ /**
59
+ * The size and color layout of a JPEG from its frame header, or null when the
60
+ * bytes are not a JPEG this can place (no start-of-image, no frame, or a frame
61
+ * with an unusual channel count).
62
+ */
63
+ export declare function readJpeg(bytes: Uint8Array): PdfJpegImage | null;
64
+ /** The bytes of a PDF file holding `input.pages`. */
65
+ export declare function buildPdfFile(input: PdfFileInput): Uint8Array;
@@ -0,0 +1,170 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { pdfString } from "./pdf-text.js";
18
+ /** A number as a PDF operand: two decimals at most, no trailing zeros. */ export function pdfNumber(value) {
19
+ const rounded = Math.round(value * 100) / 100;
20
+ return (Object.is(rounded, -0) ? 0 : rounded).toString();
21
+ }
22
+ /**
23
+ * A link target as a PDF string literal's body. Only web and mail addresses
24
+ * are linked; a URI is 7-bit ASCII in a PDF, so anything else is
25
+ * percent-encoded. Null for an address that is not one of those.
26
+ */ export function pdfUri(url) {
27
+ const value = String(url != null ? url : '').trim();
28
+ if (!/^(https?:\/\/|mailto:)/i.test(value) || value.length > 2000) return null;
29
+ let ascii = '';
30
+ for (const char of value){
31
+ var _char_codePointAt;
32
+ const code = (_char_codePointAt = char.codePointAt(0)) != null ? _char_codePointAt : 0;
33
+ ascii += code > 0x20 && code < 0x7f ? char : encodeURIComponent(char);
34
+ }
35
+ return ascii.replace(/[\\()]/g, (match)=>`\\${match}`);
36
+ }
37
+ /**
38
+ * The size and color layout of a JPEG from its frame header, or null when the
39
+ * bytes are not a JPEG this can place (no start-of-image, no frame, or a frame
40
+ * with an unusual channel count).
41
+ */ export function readJpeg(bytes) {
42
+ if (!bytes || bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
43
+ let offset = 2;
44
+ let adobe = false;
45
+ while(offset + 4 <= bytes.length){
46
+ if (bytes[offset] !== 0xff) return null;
47
+ const marker = bytes[offset + 1];
48
+ if (marker === 0xff) {
49
+ offset += 1;
50
+ continue;
51
+ }
52
+ // Markers that stand alone: restart, start and end of image, TEM.
53
+ if (marker >= 0xd0 && marker <= 0xd9 || marker === 0x01) {
54
+ offset += 2;
55
+ continue;
56
+ }
57
+ const length = bytes[offset + 2] << 8 | bytes[offset + 3];
58
+ if (length < 2 || offset + 2 + length > bytes.length) return null;
59
+ if (marker === 0xee) adobe = true;
60
+ const frame = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
61
+ if (frame) {
62
+ const start = offset + 4;
63
+ if (length < 8 || bytes[start] !== 8) return null;
64
+ const height = bytes[start + 1] << 8 | bytes[start + 2];
65
+ const width = bytes[start + 3] << 8 | bytes[start + 4];
66
+ const components = bytes[start + 5];
67
+ if (!width || !height || components !== 1 && components !== 3 && components !== 4) return null;
68
+ return _extends({
69
+ bytes,
70
+ width,
71
+ height,
72
+ components
73
+ }, components === 4 && adobe ? {
74
+ invertedCmyk: true
75
+ } : {});
76
+ }
77
+ if (marker === 0xda) return null;
78
+ offset += 2 + length;
79
+ }
80
+ return null;
81
+ }
82
+ function imageDictionary(image) {
83
+ const space = image.components === 1 ? '/DeviceGray' : image.components === 4 ? '/DeviceCMYK' : '/DeviceRGB';
84
+ const decode = image.components === 4 && image.invertedCmyk ? ' /Decode [1 0 1 0 1 0 1 0]' : '';
85
+ return `<< /Type /XObject /Subtype /Image /Width ${image.width} /Height ${image.height} ` + `/ColorSpace ${space} /BitsPerComponent 8${decode} /Filter /DCTDecode /Length ${image.bytes.length} >>`;
86
+ }
87
+ /** The bytes of a PDF file holding `input.pages`. */ export function buildPdfFile(input) {
88
+ var _input_images;
89
+ const pages = input.pages;
90
+ const images = (_input_images = input.images) != null ? _input_images : [];
91
+ // Each object is text, or text around binary stream data.
92
+ const objects = [];
93
+ const pageIds = pages.map((_, index)=>7 + index * 2);
94
+ const firstImageId = 7 + pages.length * 2;
95
+ const imageIds = images.map((_, index)=>firstImageId + index);
96
+ let nextId = firstImageId + images.length;
97
+ objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
98
+ objects[2] = `<< /Type /Pages /Kids [${pageIds.map((id)=>`${id} 0 R`).join(' ')}] /Count ${pages.length} >>`;
99
+ objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
100
+ objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
101
+ objects[5] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';
102
+ objects[6] = input.producer === undefined ? `<< /Title (${pdfString(input.title)}) >>` : `<< /Title (${pdfString(input.title)}) /Producer (${pdfString(input.producer)}) >>`;
103
+ const xObjects = imageIds.length ? ` /XObject << ${imageIds.map((id, index)=>`/Im${index + 1} ${id} 0 R`).join(' ')} >>` : '';
104
+ pages.forEach((page, index)=>{
105
+ var _page_links;
106
+ const pageId = pageIds[index];
107
+ const annotIds = [];
108
+ for (const link of (_page_links = page.links) != null ? _page_links : []){
109
+ const uri = pdfUri(link.url);
110
+ if (!uri) continue;
111
+ const id = nextId++;
112
+ annotIds.push(id);
113
+ const rect = [
114
+ link.x,
115
+ link.y,
116
+ link.x + link.width,
117
+ link.y + link.height
118
+ ].map(pdfNumber).join(' ');
119
+ objects[id] = `<< /Type /Annot /Subtype /Link /Rect [${rect}] /Border [0 0 0] ` + `/A << /Type /Action /S /URI /URI (${uri}) >> >>`;
120
+ }
121
+ const annots = annotIds.length ? ` /Annots [${annotIds.map((id)=>`${id} 0 R`).join(' ')}]` : '';
122
+ objects[pageId] = `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pdfNumber(page.width)} ${pdfNumber(page.height)}] ` + `/Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >>${xObjects} >>${annots} /Contents ${pageId + 1} 0 R >>`;
123
+ objects[pageId + 1] = `<< /Length ${page.content.length} >>\nstream\n${page.content}\nendstream`;
124
+ });
125
+ images.forEach((image, index)=>{
126
+ objects[imageIds[index]] = [
127
+ `${imageDictionary(image)}\nstream\n`,
128
+ image.bytes,
129
+ '\nendstream'
130
+ ];
131
+ });
132
+ // Text is one byte per character (every string above is ASCII or Latin-1),
133
+ // so its length is its byte count.
134
+ const chunks = [];
135
+ let length = 0;
136
+ const push = (part)=>{
137
+ const bytes = typeof part === 'string' ? latin1(part) : part;
138
+ chunks.push(bytes);
139
+ length += bytes.length;
140
+ };
141
+ push('%PDF-1.4\n%âãÏÓ\n');
142
+ const offsets = [];
143
+ for(let id = 1; id < objects.length; id += 1){
144
+ offsets[id] = length;
145
+ const object = objects[id];
146
+ push(`${id} 0 obj\n`);
147
+ if (typeof object === 'string') push(object);
148
+ else object.forEach(push);
149
+ push('\nendobj\n');
150
+ }
151
+ const xref = length;
152
+ let tail = `xref\n0 ${objects.length}\n0000000000 65535 f \n`;
153
+ for(let id = 1; id < objects.length; id += 1)tail += `${String(offsets[id]).padStart(10, '0')} 00000 n \n`;
154
+ tail += `trailer\n<< /Size ${objects.length} /Root 1 0 R /Info 6 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
155
+ push(tail);
156
+ const out = new Uint8Array(length);
157
+ let at = 0;
158
+ for (const chunk of chunks){
159
+ out.set(chunk, at);
160
+ at += chunk.length;
161
+ }
162
+ return out;
163
+ }
164
+ function latin1(text) {
165
+ const bytes = new Uint8Array(text.length);
166
+ for(let index = 0; index < text.length; index += 1)bytes[index] = text.charCodeAt(index) & 0xff;
167
+ return bytes;
168
+ }
169
+
170
+ //# sourceMappingURL=pdf-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/shared/util/tools/src/lib/pdf/pdf-file.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { pdfString } from './pdf-text'\n\n/*==========================================\n * A PDF FILE FROM PAGES OF DRAWING OPERATORS, with no PDF library.\n *\n * Object numbers are fixed, so a document is the same bytes every time it is\n * made from the same input:\n *\n * 1 catalog · 2 page tree · 3 Helvetica (`/F1`) · 4 Helvetica-Bold (`/F2`)\n * · 5 Helvetica-Oblique (`/F3`) · 6 document info · then each page and its\n * content stream · then each JPEG image · then each link annotation.\n *\n * Fonts are the standard ones in WinAnsi (nothing embedded); images are JPEG\n * passed through as DCTDecode streams (no decoding here); links are URI\n * annotations. The cross-reference table is written from the byte offsets of\n * the objects as they are laid down.\n *\n * Reached as `@aglyn/shared-util-tools/pdf/pdf-file`.\n *=========================================*/\n\n/** A JPEG ready to draw: its bytes untouched, with what the image dictionary needs. */\nexport interface PdfJpegImage {\n bytes: Uint8Array\n width: number\n height: number\n /** 1 gray, 3 RGB, 4 CMYK. */\n components: 1 | 3 | 4\n /** An Adobe CMYK JPEG stores its ink inverted. */\n invertedCmyk?: boolean\n}\n\n/** A clickable area on a page, in points from the bottom-left corner, opening `url`. */\nexport interface PdfLinkArea {\n x: number\n y: number\n width: number\n height: number\n url: string\n}\n\nexport interface PdfFilePage {\n width: number\n height: number\n /** The page's content stream: drawing operators in printable ASCII. */\n content: string\n links?: readonly PdfLinkArea[]\n}\n\nexport interface PdfFileInput {\n pages: readonly PdfFilePage[]\n /** Images every page may draw as `/Im1`, `/Im2`, … in this order. */\n images?: readonly PdfJpegImage[]\n title: string\n /** The making software, in the document's properties; left out when not given. */\n producer?: string\n}\n\n/** A number as a PDF operand: two decimals at most, no trailing zeros. */\nexport function pdfNumber(value: number): string {\n const rounded = Math.round(value * 100) / 100\n return (Object.is(rounded, -0) ? 0 : rounded).toString()\n}\n\n/**\n * A link target as a PDF string literal's body. Only web and mail addresses\n * are linked; a URI is 7-bit ASCII in a PDF, so anything else is\n * percent-encoded. Null for an address that is not one of those.\n */\nexport function pdfUri(url: string): string | null {\n const value = String(url ?? '').trim()\n if (!/^(https?:\\/\\/|mailto:)/i.test(value) || value.length > 2000) return null\n let ascii = ''\n for (const char of value) {\n const code = char.codePointAt(0) ?? 0\n ascii += code > 0x20 && code < 0x7f ? char : encodeURIComponent(char)\n }\n return ascii.replace(/[\\\\()]/g, (match) => `\\\\${match}`)\n}\n\n/**\n * The size and color layout of a JPEG from its frame header, or null when the\n * bytes are not a JPEG this can place (no start-of-image, no frame, or a frame\n * with an unusual channel count).\n */\nexport function readJpeg(bytes: Uint8Array): PdfJpegImage | null {\n if (!bytes || bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null\n let offset = 2\n let adobe = false\n while (offset + 4 <= bytes.length) {\n if (bytes[offset] !== 0xff) return null\n const marker = bytes[offset + 1]\n if (marker === 0xff) {\n offset += 1\n continue\n }\n // Markers that stand alone: restart, start and end of image, TEM.\n if ((marker >= 0xd0 && marker <= 0xd9) || marker === 0x01) {\n offset += 2\n continue\n }\n const length = (bytes[offset + 2] << 8) | bytes[offset + 3]\n if (length < 2 || offset + 2 + length > bytes.length) return null\n if (marker === 0xee) adobe = true\n const frame = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc\n if (frame) {\n const start = offset + 4\n if (length < 8 || bytes[start] !== 8) return null\n const height = (bytes[start + 1] << 8) | bytes[start + 2]\n const width = (bytes[start + 3] << 8) | bytes[start + 4]\n const components = bytes[start + 5]\n if (!width || !height || (components !== 1 && components !== 3 && components !== 4)) return null\n return { bytes, width, height, components, ...(components === 4 && adobe ? { invertedCmyk: true } : {}) }\n }\n if (marker === 0xda) return null\n offset += 2 + length\n }\n return null\n}\n\nfunction imageDictionary(image: PdfJpegImage): string {\n const space = image.components === 1 ? '/DeviceGray' : image.components === 4 ? '/DeviceCMYK' : '/DeviceRGB'\n const decode = image.components === 4 && image.invertedCmyk ? ' /Decode [1 0 1 0 1 0 1 0]' : ''\n return (\n `<< /Type /XObject /Subtype /Image /Width ${image.width} /Height ${image.height} ` +\n `/ColorSpace ${space} /BitsPerComponent 8${decode} /Filter /DCTDecode /Length ${image.bytes.length} >>`\n )\n}\n\n/** The bytes of a PDF file holding `input.pages`. */\nexport function buildPdfFile(input: PdfFileInput): Uint8Array {\n const pages = input.pages\n const images = input.images ?? []\n // Each object is text, or text around binary stream data.\n const objects: Array<string | [string, Uint8Array, string]> = []\n const pageIds = pages.map((_, index) => 7 + index * 2)\n const firstImageId = 7 + pages.length * 2\n const imageIds = images.map((_, index) => firstImageId + index)\n let nextId = firstImageId + images.length\n\n objects[1] = '<< /Type /Catalog /Pages 2 0 R >>'\n objects[2] = `<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(' ')}] /Count ${pages.length} >>`\n objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'\n objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>'\n objects[5] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>'\n objects[6] =\n input.producer === undefined\n ? `<< /Title (${pdfString(input.title)}) >>`\n : `<< /Title (${pdfString(input.title)}) /Producer (${pdfString(input.producer)}) >>`\n\n const xObjects = imageIds.length\n ? ` /XObject << ${imageIds.map((id, index) => `/Im${index + 1} ${id} 0 R`).join(' ')} >>`\n : ''\n pages.forEach((page, index) => {\n const pageId = pageIds[index]\n const annotIds: number[] = []\n for (const link of page.links ?? []) {\n const uri = pdfUri(link.url)\n if (!uri) continue\n const id = nextId++\n annotIds.push(id)\n const rect = [link.x, link.y, link.x + link.width, link.y + link.height].map(pdfNumber).join(' ')\n objects[id] =\n `<< /Type /Annot /Subtype /Link /Rect [${rect}] /Border [0 0 0] ` +\n `/A << /Type /Action /S /URI /URI (${uri}) >> >>`\n }\n const annots = annotIds.length ? ` /Annots [${annotIds.map((id) => `${id} 0 R`).join(' ')}]` : ''\n objects[pageId] =\n `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pdfNumber(page.width)} ${pdfNumber(page.height)}] ` +\n `/Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >>${xObjects} >>${annots} /Contents ${pageId + 1} 0 R >>`\n objects[pageId + 1] = `<< /Length ${page.content.length} >>\\nstream\\n${page.content}\\nendstream`\n })\n images.forEach((image, index) => {\n objects[imageIds[index]] = [`${imageDictionary(image)}\\nstream\\n`, image.bytes, '\\nendstream']\n })\n\n // Text is one byte per character (every string above is ASCII or Latin-1),\n // so its length is its byte count.\n const chunks: Uint8Array[] = []\n let length = 0\n const push = (part: string | Uint8Array) => {\n const bytes = typeof part === 'string' ? latin1(part) : part\n chunks.push(bytes)\n length += bytes.length\n }\n push('%PDF-1.4\\n%âãÏÓ\\n')\n const offsets: number[] = []\n for (let id = 1; id < objects.length; id += 1) {\n offsets[id] = length\n const object = objects[id]\n push(`${id} 0 obj\\n`)\n if (typeof object === 'string') push(object)\n else object.forEach(push)\n push('\\nendobj\\n')\n }\n const xref = length\n let tail = `xref\\n0 ${objects.length}\\n0000000000 65535 f \\n`\n for (let id = 1; id < objects.length; id += 1) tail += `${String(offsets[id]).padStart(10, '0')} 00000 n \\n`\n tail += `trailer\\n<< /Size ${objects.length} /Root 1 0 R /Info 6 0 R >>\\nstartxref\\n${xref}\\n%%EOF\\n`\n push(tail)\n\n const out = new Uint8Array(length)\n let at = 0\n for (const chunk of chunks) {\n out.set(chunk, at)\n at += chunk.length\n }\n return out\n}\n\nfunction latin1(text: string): Uint8Array {\n const bytes = new Uint8Array(text.length)\n for (let index = 0; index < text.length; index += 1) bytes[index] = text.charCodeAt(index) & 0xff\n return bytes\n}\n"],"names":["pdfString","pdfNumber","value","rounded","Math","round","Object","is","toString","pdfUri","url","String","trim","test","length","ascii","char","code","codePointAt","encodeURIComponent","replace","match","readJpeg","bytes","offset","adobe","marker","frame","start","height","width","components","invertedCmyk","imageDictionary","image","space","decode","buildPdfFile","input","pages","images","objects","pageIds","map","_","index","firstImageId","imageIds","nextId","id","join","producer","undefined","title","xObjects","forEach","page","pageId","annotIds","link","links","uri","push","rect","x","y","annots","content","chunks","part","latin1","offsets","object","xref","tail","padStart","out","Uint8Array","at","chunk","set","text","charCodeAt"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,gBAAY;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B,MAAM,GAAGoC,KAAKC,UAAU,CAACrC,SAAS;IAC7F,OAAOtB;AACT"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /** The three faces a document may set text in. */
18
+ export type PdfFont = 'regular' | 'bold' | 'italic';
19
+ /**
20
+ * `text` as characters WinAnsi holds, line breaks kept (`\r\n` and `\r`
21
+ * become `\n`). Text that is already WinAnsi comes back unchanged.
22
+ */
23
+ export declare function toWinAnsiText(text: string): string;
24
+ /** One character's WinAnsi byte, `?` (63) for a character WinAnsi does not hold. */
25
+ export declare function winAnsiByte(char: string): number;
26
+ /**
27
+ * A PDF string literal's body for `text`: WinAnsi bytes, `\`, `(` and `)`
28
+ * escaped, and every byte outside printable ASCII as an octal escape, so the
29
+ * literal itself is plain ASCII. A line break prints as a space.
30
+ */
31
+ export declare function pdfString(text: string): string;
32
+ /** `text`'s width in points at `size`, as a reader draws it in `font`. */
33
+ export declare function measureText(text: string, size: number, font?: PdfFont): number;
34
+ /**
35
+ * `text` wrapped to `width` points at `size` in `font`, by the exact widths.
36
+ * Each `\n` starts a new line; a blank line comes back as `''`.
37
+ */
38
+ export declare function wrapLines(text: string, size: number, width: number, font?: PdfFont): string[];
39
+ /** A string's estimated width in points at `size`; bold runs 7% wider. */
40
+ export declare function textWidth(text: string, size: number, bold?: boolean): number;
41
+ /** Words wrapped by {@link textWidth} into lines no wider than `width`; an overlong word is broken. */
42
+ export declare function wrapText(text: string, size: number, width: number, bold?: boolean): string[];