pdfkit 0.19.1 → 0.20.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.
Files changed (56) hide show
  1. package/.yarn/install-state.gz +0 -0
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +97 -25
  4. package/js/output.cjs +53 -0
  5. package/js/output.mjs +50 -0
  6. package/js/pdfkit.browser.js +7524 -0
  7. package/js/pdfkit.browser.js.map +1 -0
  8. package/js/pdfkit.browser.mjs +7344 -0
  9. package/js/pdfkit.browser.mjs.map +1 -0
  10. package/js/pdfkit.browser.old.js +7517 -0
  11. package/js/pdfkit.browser.old.mjs +7342 -0
  12. package/js/pdfkit.js +1417 -487
  13. package/js/pdfkit.js.map +1 -1
  14. package/js/{pdfkit.es.js → pdfkit.old.js} +1423 -502
  15. package/js/pdfkit.standalone.js +23432 -35943
  16. package/js/standard-fonts/Courier.cjs +17 -0
  17. package/js/standard-fonts/Courier.mjs +15 -0
  18. package/js/standard-fonts/CourierBold.cjs +17 -0
  19. package/js/standard-fonts/CourierBold.mjs +15 -0
  20. package/js/standard-fonts/CourierBoldOblique.cjs +17 -0
  21. package/js/standard-fonts/CourierBoldOblique.mjs +15 -0
  22. package/js/standard-fonts/CourierOblique.cjs +17 -0
  23. package/js/standard-fonts/CourierOblique.mjs +15 -0
  24. package/js/standard-fonts/Helvetica.cjs +17 -0
  25. package/js/standard-fonts/Helvetica.mjs +15 -0
  26. package/js/standard-fonts/HelveticaBold.cjs +17 -0
  27. package/js/standard-fonts/HelveticaBold.mjs +15 -0
  28. package/js/standard-fonts/HelveticaBoldOblique.cjs +17 -0
  29. package/js/standard-fonts/HelveticaBoldOblique.mjs +15 -0
  30. package/js/standard-fonts/HelveticaOblique.cjs +17 -0
  31. package/js/standard-fonts/HelveticaOblique.mjs +15 -0
  32. package/js/standard-fonts/Symbol.cjs +15 -0
  33. package/js/standard-fonts/Symbol.mjs +13 -0
  34. package/js/standard-fonts/TimesBold.cjs +17 -0
  35. package/js/standard-fonts/TimesBold.mjs +15 -0
  36. package/js/standard-fonts/TimesBoldItalic.cjs +17 -0
  37. package/js/standard-fonts/TimesBoldItalic.mjs +15 -0
  38. package/js/standard-fonts/TimesItalic.cjs +17 -0
  39. package/js/standard-fonts/TimesItalic.mjs +15 -0
  40. package/js/standard-fonts/TimesRoman.cjs +17 -0
  41. package/js/standard-fonts/TimesRoman.mjs +15 -0
  42. package/js/standard-fonts/ZapfDingbats.cjs +15 -0
  43. package/js/standard-fonts/ZapfDingbats.mjs +13 -0
  44. package/js/standard-fonts/chunks/standardGlyphNames-DNHAb7rp.cjs +5 -0
  45. package/js/standard-fonts/chunks/standardGlyphNames-w3QlG7PW.mjs +3 -0
  46. package/package.json +109 -28
  47. package/rollup.config.mjs +111 -50
  48. package/tools/README.md +124 -0
  49. package/tools/afm-converter.js +317 -0
  50. package/tools/asset-plugin.mjs +17 -0
  51. package/tools/binary-plugin.mjs +18 -0
  52. package/tools/convert-afm-parsed.js +8 -0
  53. package/tools/convert-afm-runtime.js +8 -0
  54. package/vitest.config.js +2 -0
  55. package/js/pdfkit.es.js.map +0 -1
  56. package/js/virtual-fs.js +0 -49
@@ -0,0 +1,317 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const RUNTIME_GLYPH_NAMES = `\
5
+ .notdef space exclam quotedbl numbersign dollar percent ampersand quotesingle
6
+ parenleft parenright asterisk plus comma hyphen period slash zero one two three
7
+ four five six seven eight nine colon semicolon less equal greater question at A
8
+ B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash
9
+ bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r
10
+ s t u v w x y z braceleft bar braceright asciitilde Euro quotesinglbase florin
11
+ quotedblbase ellipsis dagger daggerdbl circumflex perthousand Scaron
12
+ guilsinglleft OE Zcaron quoteleft quoteright quotedblleft quotedblright bullet
13
+ endash emdash tilde trademark scaron guilsinglright oe zcaron ydieresis
14
+ exclamdown cent sterling currency yen brokenbar section dieresis copyright
15
+ ordfeminine guillemotleft logicalnot registered macron degree plusminus
16
+ twosuperior threesuperior acute mu paragraph periodcentered cedilla onesuperior
17
+ ordmasculine guillemotright onequarter onehalf threequarters questiondown Agrave
18
+ Aacute Acircumflex Atilde Adieresis Aring AE Ccedilla Egrave Eacute Ecircumflex
19
+ Edieresis Igrave Iacute Icircumflex Idieresis Eth Ntilde Ograve Oacute
20
+ Ocircumflex Otilde Odieresis multiply Oslash Ugrave Uacute Ucircumflex Udieresis
21
+ Yacute Thorn germandbls agrave aacute acircumflex atilde adieresis aring ae
22
+ ccedilla egrave eacute ecircumflex edieresis igrave iacute icircumflex idieresis
23
+ eth ntilde ograve oacute ocircumflex otilde odieresis divide oslash ugrave
24
+ uacute ucircumflex udieresis yacute thorn`.split(/\s+/);
25
+
26
+ const STANDARD_GLYPH_NAMES = RUNTIME_GLYPH_NAMES.filter(
27
+ (name) => name !== '.notdef',
28
+ ).join(' ');
29
+ const STANDARD_GLYPH_NAMES_FILE = 'standardGlyphNames.js';
30
+ const DEFAULT_AFM_DIRECTORY = path.join(__dirname, '../lib/font/data');
31
+
32
+ const ADOBE_DISTRIBUTION_NOTICE =
33
+ 'This file and the 14 PostScript(R) AFM files it accompanies may be used, ' +
34
+ 'copied, and distributed for any purpose and without charge, with or ' +
35
+ 'without modification, provided that all copyright notices are retained; ' +
36
+ 'that the AFM files are not distributed without this file; that all ' +
37
+ 'modifications to this file or any of the AFM files are prominently noted ' +
38
+ 'in the modified file(s); and that this paragraph is not modified. Adobe ' +
39
+ 'Systems has no responsibility or obligation to support the use of the AFM ' +
40
+ 'files.';
41
+
42
+ function parseAFM(contents) {
43
+ const attributes = {};
44
+ const glyphWidths = {};
45
+ const kernPairs = {};
46
+ let section = '';
47
+
48
+ for (const line of contents.split('\n')) {
49
+ let match;
50
+ let attribute;
51
+
52
+ if ((match = line.match(/^Start(\w+)/))) {
53
+ section = match[1];
54
+ continue;
55
+ } else if (/^End(\w+)/.test(line)) {
56
+ section = '';
57
+ continue;
58
+ }
59
+
60
+ switch (section) {
61
+ case 'FontMetrics': {
62
+ match = line.match(/(^\w+)\s+(.*)/);
63
+ if (!match) {
64
+ throw new Error(`Invalid font metrics line: ${line}`);
65
+ }
66
+
67
+ const key = match[1];
68
+ const value = match[2];
69
+ if ((attribute = attributes[key])) {
70
+ if (!Array.isArray(attribute)) {
71
+ attribute = attributes[key] = [attribute];
72
+ }
73
+ attribute.push(value);
74
+ } else {
75
+ attributes[key] = value;
76
+ }
77
+ break;
78
+ }
79
+
80
+ case 'CharMetrics': {
81
+ if (!/^CH?\s/.test(line)) {
82
+ continue;
83
+ }
84
+
85
+ const nameMatch = line.match(/\bN\s+(\.?\w+)\s*;/);
86
+ const widthMatch = line.match(/\bWX\s+(\d+)\s*;/);
87
+ if (!nameMatch || !widthMatch) {
88
+ throw new Error(`Invalid character metrics line: ${line}`);
89
+ }
90
+
91
+ glyphWidths[nameMatch[1]] = +widthMatch[1];
92
+ break;
93
+ }
94
+
95
+ case 'KernPairs': {
96
+ match = line.match(/^KPX\s+(\.?\w+)\s+(\.?\w+)\s+(-?\d+)/);
97
+ if (match) {
98
+ kernPairs[`${match[1]}\0${match[2]}`] = parseInt(match[3]);
99
+ }
100
+ break;
101
+ }
102
+ }
103
+ }
104
+
105
+ if (!attributes.FontName || !attributes.FontBBox) {
106
+ throw new Error('AFM data is missing FontName or FontBBox.');
107
+ }
108
+
109
+ return { attributes, glyphWidths, kernPairs };
110
+ }
111
+
112
+ function createParsedData(parsed) {
113
+ return parsed;
114
+ }
115
+
116
+ function createRuntimeData(parsed) {
117
+ const { attributes, glyphWidths, kernPairs } = parsed;
118
+ const glyphNames = RUNTIME_GLYPH_NAMES.filter((name) =>
119
+ Object.hasOwn(glyphWidths, name),
120
+ );
121
+ const glyphIndexes = Object.fromEntries(
122
+ glyphNames.map((name, index) => [name, index]),
123
+ );
124
+ const pairsByAmount = new Map();
125
+
126
+ for (const [pair, amount] of Object.entries(kernPairs)) {
127
+ const [left, right] = pair.split('\0');
128
+ if (!(left in glyphIndexes) || !(right in glyphIndexes)) {
129
+ continue;
130
+ }
131
+
132
+ let pairIds = pairsByAmount.get(amount);
133
+ if (!pairIds) {
134
+ pairIds = [];
135
+ pairsByAmount.set(amount, pairIds);
136
+ }
137
+
138
+ pairIds.push(glyphIndexes[left] * glyphNames.length + glyphIndexes[right]);
139
+ }
140
+
141
+ const compactKernPairs = [];
142
+ const amounts = [...pairsByAmount.keys()].sort((a, b) => a - b);
143
+ for (const amount of amounts) {
144
+ const pairIds = pairsByAmount.get(amount).sort((a, b) => a - b);
145
+ const deltas = pairIds.map((pairId, index) =>
146
+ index === 0 ? pairId : pairId - pairIds[index - 1],
147
+ );
148
+ compactKernPairs.push(amount, deltas);
149
+ }
150
+
151
+ return {
152
+ name: attributes.FontName,
153
+ bbox: attributes.FontBBox.trim().split(/\s+/).map(Number),
154
+ ascender: +(attributes.Ascender || 0),
155
+ descender: +(attributes.Descender || 0),
156
+ xHeight: +(attributes.XHeight || 0),
157
+ capHeight: +(attributes.CapHeight || 0),
158
+ glyphNames: glyphNames.join(' '),
159
+ glyphWidths: glyphNames.map((name) => glyphWidths[name]),
160
+ kernPairs: compactKernPairs,
161
+ };
162
+ }
163
+
164
+ function asArray(value) {
165
+ return Array.isArray(value) ? value : value ? [value] : [];
166
+ }
167
+
168
+ function createHeader(inputName, attributes) {
169
+ const notices = asArray(attributes.Notice).map((notice) => ` * ${notice}`);
170
+
171
+ return [
172
+ '/*',
173
+ ` * Generated from ${inputName}. Do not edit directly.`,
174
+ ' * The source AFM metrics were converted to JavaScript; this is a modification.',
175
+ ...notices,
176
+ ' *',
177
+ ` * ${ADOBE_DISTRIBUTION_NOTICE}`,
178
+ ' */',
179
+ ].join('\n');
180
+ }
181
+
182
+ function createModule(inputName, parsed, format) {
183
+ const header = createHeader(inputName, parsed.attributes);
184
+ if (format === 'parsed') {
185
+ return {
186
+ output: `${header}\nexport default ${JSON.stringify(createParsedData(parsed))};\n`,
187
+ usesStandardGlyphNames: false,
188
+ };
189
+ }
190
+
191
+ const data = createRuntimeData(parsed);
192
+ if (data.glyphNames !== STANDARD_GLYPH_NAMES) {
193
+ return {
194
+ output: `${header}\nexport default ${JSON.stringify(data)};\n`,
195
+ usesStandardGlyphNames: false,
196
+ };
197
+ }
198
+
199
+ const serialized = JSON.stringify(data).replace(
200
+ `"glyphNames":${JSON.stringify(STANDARD_GLYPH_NAMES)}`,
201
+ 'glyphNames',
202
+ );
203
+ return {
204
+ output:
205
+ `${header}\n` +
206
+ `import glyphNames from './${STANDARD_GLYPH_NAMES_FILE}';\n` +
207
+ `export default ${serialized};\n`,
208
+ usesStandardGlyphNames: true,
209
+ };
210
+ }
211
+
212
+ function createStandardGlyphNamesModule() {
213
+ return (
214
+ '/* Generated by tools/convert-afm-runtime.js. Do not edit directly. */\n' +
215
+ `export default ${JSON.stringify(STANDARD_GLYPH_NAMES)};\n`
216
+ );
217
+ }
218
+
219
+ function parseArguments(argv) {
220
+ let outputDirectory;
221
+ const inputs = [];
222
+
223
+ for (let index = 0; index < argv.length; index++) {
224
+ const argument = argv[index];
225
+ if (argument === '--output-dir') {
226
+ outputDirectory = argv[++index];
227
+ if (!outputDirectory || outputDirectory.startsWith('--')) {
228
+ throw new Error('--output-dir requires a directory.');
229
+ }
230
+ } else if (argument.startsWith('--')) {
231
+ throw new Error(`Unknown option: ${argument}`);
232
+ } else {
233
+ inputs.push(argument);
234
+ }
235
+ }
236
+
237
+ if (!outputDirectory) {
238
+ throw new Error('Usage: --output-dir <directory> [font.afm ...]');
239
+ }
240
+
241
+ if (inputs.length === 0) {
242
+ inputs.push(
243
+ ...fs
244
+ .readdirSync(DEFAULT_AFM_DIRECTORY)
245
+ .filter((file) => path.extname(file).toLowerCase() === '.afm')
246
+ .sort()
247
+ .map((file) => path.join(DEFAULT_AFM_DIRECTORY, file)),
248
+ );
249
+ }
250
+
251
+ return { outputDirectory, inputs };
252
+ }
253
+
254
+ function convertFiles(argv, format, log = console.log) {
255
+ const { outputDirectory, inputs } = parseArguments(argv);
256
+ const conversions = [];
257
+ const outputNames = new Set();
258
+
259
+ for (const input of inputs) {
260
+ if (path.extname(input).toLowerCase() !== '.afm') {
261
+ throw new Error(`Expected an .afm input file: ${input}`);
262
+ }
263
+
264
+ const basename = path.basename(input, path.extname(input));
265
+ const outputName = `${basename.replaceAll('-', '')}.js`;
266
+ if (outputNames.has(outputName)) {
267
+ throw new Error(`Duplicate output filename: ${outputName}`);
268
+ }
269
+ outputNames.add(outputName);
270
+
271
+ const contents = fs.readFileSync(input, 'utf8');
272
+ const parsed = parseAFM(contents);
273
+ const generatedModule = createModule(path.basename(input), parsed, format);
274
+ conversions.push({
275
+ input,
276
+ inputBytes: Buffer.byteLength(contents),
277
+ outputName,
278
+ ...generatedModule,
279
+ });
280
+ }
281
+
282
+ fs.mkdirSync(outputDirectory, { recursive: true });
283
+ if (
284
+ conversions.some(({ usesStandardGlyphNames }) => usesStandardGlyphNames)
285
+ ) {
286
+ const output = createStandardGlyphNamesModule();
287
+ const outputPath = path.join(outputDirectory, STANDARD_GLYPH_NAMES_FILE);
288
+ fs.writeFileSync(outputPath, output);
289
+ log(
290
+ `Standard glyph names -> ${outputPath} ` +
291
+ `(${Buffer.byteLength(output)} bytes)`,
292
+ );
293
+ }
294
+
295
+ for (const conversion of conversions) {
296
+ const outputPath = path.join(outputDirectory, conversion.outputName);
297
+ fs.writeFileSync(outputPath, conversion.output);
298
+ const outputBytes = Buffer.byteLength(conversion.output);
299
+ const reduction = (100 * (1 - outputBytes / conversion.inputBytes)).toFixed(
300
+ 1,
301
+ );
302
+ log(
303
+ `${conversion.input} -> ${outputPath} ` +
304
+ `(${conversion.inputBytes} -> ${outputBytes} bytes, ${reduction}% smaller)`,
305
+ );
306
+ }
307
+ }
308
+
309
+ module.exports = {
310
+ convertFiles,
311
+ createParsedData,
312
+ createRuntimeData,
313
+ parseAFM,
314
+ RUNTIME_GLYPH_NAMES,
315
+ STANDARD_GLYPH_NAMES,
316
+ STANDARD_GLYPH_NAMES_FILE,
317
+ };
@@ -0,0 +1,17 @@
1
+ import { readFile } from 'fs/promises';
2
+
3
+ /**
4
+ * Emits a source file as an asset at a fixed path in the Rollup output.
5
+ */
6
+ export default function asset(sourcePath, outputPath) {
7
+ return {
8
+ name: 'asset',
9
+ async buildStart() {
10
+ this.emitFile({
11
+ type: 'asset',
12
+ fileName: outputPath,
13
+ source: await readFile(sourcePath),
14
+ });
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,18 @@
1
+ import { readFile } from 'fs/promises';
2
+
3
+ /**
4
+ * Bundles binary files (by extension) as base64 strings, so they can be
5
+ * imported without reading them from disk at runtime.
6
+ */
7
+ export default function binary(...extensions) {
8
+ return {
9
+ name: 'binary',
10
+ enforce: 'pre',
11
+ async load(id) {
12
+ if (!extensions.some((extension) => id.endsWith(extension))) return null;
13
+
14
+ const data = await readFile(id);
15
+ return `export default ${JSON.stringify(data.toString('base64'))};`;
16
+ },
17
+ };
18
+ }
@@ -0,0 +1,8 @@
1
+ const { convertFiles } = require('./afm-converter');
2
+
3
+ try {
4
+ convertFiles(process.argv.slice(2), 'parsed');
5
+ } catch (error) {
6
+ console.error(error.message);
7
+ process.exitCode = 1;
8
+ }
@@ -0,0 +1,8 @@
1
+ const { convertFiles } = require('./afm-converter');
2
+
3
+ try {
4
+ convertFiles(process.argv.slice(2), 'runtime');
5
+ } catch (error) {
6
+ console.error(error.message);
7
+ process.exitCode = 1;
8
+ }
package/vitest.config.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { defineConfig } from 'vitest/config';
2
+ import binary from './tools/binary-plugin.mjs';
2
3
 
3
4
  export default defineConfig({
5
+ plugins: [binary('.icc')],
4
6
  test: {
5
7
  globals: true,
6
8
  environment: 'node',