@jasy/pdf 1.0.0-alpha.5 → 1.0.0-alpha.7

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 (105) hide show
  1. package/dist/api/content.d.ts +6 -3
  2. package/dist/api/content.js +12 -3
  3. package/dist/api/descriptor.js +24 -1
  4. package/dist/api/dimension.d.ts +20 -0
  5. package/dist/api/dimension.js +16 -0
  6. package/dist/api/index.d.ts +2 -0
  7. package/dist/api/index.js +2 -0
  8. package/dist/api/layout.d.ts +112 -17
  9. package/dist/api/layout.js +118 -13
  10. package/dist/api/page-builder.d.ts +32 -0
  11. package/dist/api/page-builder.js +32 -0
  12. package/dist/api/structure.d.ts +5 -0
  13. package/dist/api/structure.js +1 -0
  14. package/dist/api/text.d.ts +24 -2
  15. package/dist/api/text.js +46 -4
  16. package/dist/elements/container-element.d.ts +26 -1
  17. package/dist/elements/container-element.js +79 -29
  18. package/dist/elements/image-element.d.ts +19 -1
  19. package/dist/elements/image-element.js +52 -11
  20. package/dist/elements/index.d.ts +8 -0
  21. package/dist/elements/index.js +8 -0
  22. package/dist/elements/layout/anchor-element.d.ts +23 -0
  23. package/dist/elements/layout/anchor-element.js +27 -0
  24. package/dist/elements/layout/bookmark-element.d.ts +27 -0
  25. package/dist/elements/layout/bookmark-element.js +30 -0
  26. package/dist/elements/layout/keep-together-element.d.ts +42 -0
  27. package/dist/elements/layout/keep-together-element.js +85 -0
  28. package/dist/elements/layout/link-element.d.ts +33 -0
  29. package/dist/elements/layout/link-element.js +39 -0
  30. package/dist/elements/layout/padding-element.d.ts +3 -0
  31. package/dist/elements/layout/padding-element.js +12 -0
  32. package/dist/elements/layout/page-break-element.d.ts +17 -0
  33. package/dist/elements/layout/page-break-element.js +24 -0
  34. package/dist/elements/layout/page-builder-element.d.ts +32 -0
  35. package/dist/elements/layout/page-builder-element.js +43 -0
  36. package/dist/elements/layout/positioned-element.d.ts +10 -7
  37. package/dist/elements/layout/positioned-element.js +21 -9
  38. package/dist/elements/layout/rotated-box-element.d.ts +35 -0
  39. package/dist/elements/layout/rotated-box-element.js +54 -0
  40. package/dist/elements/layout/rotated-element.d.ts +32 -0
  41. package/dist/elements/layout/rotated-element.js +41 -0
  42. package/dist/elements/page-element.d.ts +19 -1
  43. package/dist/elements/page-element.js +54 -17
  44. package/dist/elements/pdf-element.d.ts +59 -0
  45. package/dist/elements/pdf-element.js +51 -0
  46. package/dist/elements/rectangle-element.d.ts +20 -1
  47. package/dist/elements/rectangle-element.js +75 -18
  48. package/dist/elements/row-element.d.ts +19 -1
  49. package/dist/elements/row-element.js +45 -8
  50. package/dist/elements/text-element.d.ts +34 -4
  51. package/dist/elements/text-element.js +40 -17
  52. package/dist/ir/display-list.d.ts +60 -1
  53. package/dist/layout/box-constraints.d.ts +8 -0
  54. package/dist/layout/box-constraints.js +14 -0
  55. package/dist/layout/collect-images.d.ts +9 -0
  56. package/dist/layout/collect-images.js +34 -0
  57. package/dist/layout/fragmentation.d.ts +12 -0
  58. package/dist/layout/fragmentation.js +45 -8
  59. package/dist/renderer/anchor-renderer.d.ts +6 -0
  60. package/dist/renderer/anchor-renderer.js +11 -0
  61. package/dist/renderer/bookmark-renderer.d.ts +6 -0
  62. package/dist/renderer/bookmark-renderer.js +11 -0
  63. package/dist/renderer/keep-together-renderer.d.ts +10 -0
  64. package/dist/renderer/keep-together-renderer.js +12 -0
  65. package/dist/renderer/link-renderer.d.ts +6 -0
  66. package/dist/renderer/link-renderer.js +11 -0
  67. package/dist/renderer/page-break-renderer.d.ts +14 -0
  68. package/dist/renderer/page-break-renderer.js +15 -0
  69. package/dist/renderer/page-builder-renderer.d.ts +6 -0
  70. package/dist/renderer/page-builder-renderer.js +11 -0
  71. package/dist/renderer/page-renderer.js +37 -2
  72. package/dist/renderer/pdf-backend.d.ts +17 -0
  73. package/dist/renderer/pdf-backend.js +117 -7
  74. package/dist/renderer/pdf-document-class.js +3 -0
  75. package/dist/renderer/pdf-document-renderer.d.ts +16 -7
  76. package/dist/renderer/pdf-document-renderer.js +87 -36
  77. package/dist/renderer/pdf-renderer.js +53 -2
  78. package/dist/renderer/rotated-renderer.d.ts +7 -0
  79. package/dist/renderer/rotated-renderer.js +29 -0
  80. package/dist/renderer/text-renderer.d.ts +1 -1
  81. package/dist/renderer/text-renderer.js +123 -54
  82. package/dist/text/advance.d.ts +34 -0
  83. package/dist/text/advance.js +42 -0
  84. package/dist/text/line-breaker.d.ts +9 -8
  85. package/dist/text/line-breaker.js +28 -21
  86. package/dist/text/line-metrics.d.ts +49 -0
  87. package/dist/text/line-metrics.js +57 -0
  88. package/dist/text/text-decoration.d.ts +50 -0
  89. package/dist/text/text-decoration.js +62 -0
  90. package/dist/text/text-style.d.ts +13 -3
  91. package/dist/text/text-style.js +10 -3
  92. package/dist/utils/afm-parser.d.ts +34 -0
  93. package/dist/utils/afm-parser.js +73 -4
  94. package/dist/utils/dest-registry.d.ts +19 -0
  95. package/dist/utils/dest-registry.js +32 -0
  96. package/dist/utils/flex-layout.d.ts +10 -3
  97. package/dist/utils/flex-layout.js +26 -6
  98. package/dist/utils/font-metrics.d.ts +14 -0
  99. package/dist/utils/outline.d.ts +21 -0
  100. package/dist/utils/outline.js +80 -0
  101. package/dist/utils/pdf-object-manager.d.ts +33 -1
  102. package/dist/utils/pdf-object-manager.js +0 -0
  103. package/dist/utils/ttf-parser.d.ts +53 -0
  104. package/dist/utils/ttf-parser.js +368 -0
  105. package/package.json +1 -1
@@ -2,7 +2,11 @@ import type { OverflowPolicy } from "../layout/fragmentation.js";
2
2
  import { TTFParser } from "./ttf-parser.js";
3
3
  import type { SecurityHandler } from "../crypto/security-handler.js";
4
4
  import type { Gradient } from "../ir/display-list.js";
5
+ import type { FontVerticals } from "../text/line-metrics.js";
6
+ import type { FontDecoration } from "../text/text-decoration.js";
5
7
  import { StructTree } from "./struct-tree.js";
8
+ import { OutlineBuilder } from "./outline.js";
9
+ import { DestRegistry } from "./dest-registry.js";
6
10
  import type { PDFConfig } from "../renderer/pdf-document-class.js";
7
11
  import type { FontMetrics } from "./font-metrics.js";
8
12
  interface FontIndexes {
@@ -31,6 +35,8 @@ export declare class PDFObjectManager implements FontMetrics {
31
35
  pageFormat: [number, number];
32
36
  private afmParsers;
33
37
  private customFonts;
38
+ private verticalsCache;
39
+ private decorationCache;
34
40
  private customFontEmit;
35
41
  private attachments;
36
42
  private xmpMetadata?;
@@ -44,6 +50,10 @@ export declare class PDFObjectManager implements FontMetrics {
44
50
  private encryptObjNum?;
45
51
  private _struct;
46
52
  get struct(): StructTree;
53
+ private _outline;
54
+ get outline(): OutlineBuilder;
55
+ private _dests;
56
+ get dests(): DestRegistry;
47
57
  constructor();
48
58
  addObject(content: string): number;
49
59
  replaceObject(objectNumber: number, content: string): void;
@@ -113,10 +123,32 @@ export declare class PDFObjectManager implements FontMetrics {
113
123
  private buildCIDFont;
114
124
  private buildToUnicode;
115
125
  private buildType0;
126
+ getFontVerticals(fontFamily: string, fontStyle: FontStyle): FontVerticals;
127
+ getFontDecoration(fontFamily: string, fontStyle: FontStyle): FontDecoration;
128
+ kerningEnabled: boolean;
129
+ setKerning(enabled: boolean): void;
130
+ /**
131
+ * The kerning adjustment for each adjacent code-point pair of `text`, in em/1000 (the sign the
132
+ * font declares: negative tightens). Length is `codePointCount - 1`. Zero at any pair next to a
133
+ * space - letters are never kerned against a space, which also keeps a per-word measure equal to a
134
+ * whole-line one (the space pairs contribute nothing either way).
135
+ *
136
+ * Standard-14 answers from the AFM `KPX` pairs. An embedded font has no kerning yet (its `kern` /
137
+ * `GPOS` tables are unparsed), so it returns zeros - never a wrong value, just no adjustment.
138
+ */
139
+ getKernPairs(text: string, fontFamily: string, fontStyle: FontStyle): number[];
140
+ /**
141
+ * Where the glyphs of `text` put ink inside a horizontal band, as x-intervals in POINTS measured
142
+ * from the start of the run. This is what an underline steps around ("skip-ink").
143
+ *
144
+ * `bandTop` / `bandBottom` are in points relative to the baseline, y UP (so both negative under
145
+ * it). Only an EMBEDDED font can answer: the standard-14 outlines live in the viewer, not here.
146
+ * Callers must check `isCustomFont` first rather than treat an empty result as "no descenders".
147
+ */
148
+ getInkSpansInBand(text: string, fontSize: number, fontFamily: string, fontStyle: FontStyle, bandTop: number, bandBottom: number, letterSpacing?: number): Array<[number, number]>;
116
149
  getStringWidth(text: string, fontFamily: string, fontSize: number, fontStyle: FontStyle): number;
117
150
  private getAVMParserByFont;
118
151
  getCharWidth(char: string, fontSize: number, fullFontName?: string, fontName?: string, fontStyle?: FontStyle): number;
119
- private getKerning;
120
152
  getAllFontsRaw(): Map<string, FontIndexes>;
121
153
  getAllImagesRaw(): Map<string, number>;
122
154
  getRenderedObjects(): string;
Binary file
@@ -1,3 +1,4 @@
1
+ import type { FontDecoration } from "../text/text-decoration.js";
1
2
  export type GlyphPathCommand = {
2
3
  type: "M";
3
4
  x: number;
@@ -47,11 +48,19 @@ export interface ColorGlyphLayer {
47
48
  paint: Paint;
48
49
  transform?: Affine;
49
50
  }
51
+ /** Sorts x-intervals and unions the overlapping ones. */
52
+ export declare function mergeSpans(spans: Array<[number, number]>): Array<[number, number]>;
50
53
  export declare class TTFParser {
51
54
  private data;
52
55
  unitsPerEm: number;
53
56
  ascent: number;
54
57
  descent: number;
58
+ lineGap: number;
59
+ private underlinePositionRaw;
60
+ private underlineThicknessRaw;
61
+ private xHeightRaw;
62
+ private capHeightRaw;
63
+ private cachedDecoration?;
55
64
  bbox: [number, number, number, number];
56
65
  private numGlyphs;
57
66
  private numHMetrics;
@@ -65,6 +74,9 @@ export declare class TTFParser {
65
74
  private palette;
66
75
  private colrBaseV1;
67
76
  private colrLayerListOffset;
77
+ private kernPairs;
78
+ private hasKerning;
79
+ private gposPairPos;
68
80
  constructor(data: Uint8Array);
69
81
  getData(): Uint8Array;
70
82
  glyphCount(): number;
@@ -75,6 +87,47 @@ export declare class TTFParser {
75
87
  getAdvanceWidth(glyphIndex: number): number;
76
88
  getCharWidth(char: string, fontSize: number): number;
77
89
  getStringWidth(text: string, fontSize: number): number;
90
+ private readDecorationMetrics;
91
+ /**
92
+ * Underline / strikethrough geometry, as fractions of the em.
93
+ *
94
+ * A font without `post` (rare) gets the classic 10% below the baseline at 5% thickness - the same
95
+ * numbers all 14 standard AFMs happen to declare, so it is a measured convention rather than an
96
+ * invention. A font whose `OS/2` predates version 2 has no x- or cap-height, so we MEASURE them off
97
+ * the outlines of `x` and `H` instead of guessing.
98
+ */
99
+ decoration(): FontDecoration;
100
+ /** The highest ON-CURVE point of a code point's outline, in font units; 0 for a missing glyph.
101
+ * A quadratic's control point may sit above the curve, so it is not a bound - and `x`/`H` have
102
+ * flat tops in any face where this fallback matters. */
103
+ private outlineTop;
104
+ /**
105
+ * Where a glyph's INK crosses a horizontal band, as x-intervals in font units (pen origin at 0).
106
+ * This is what lets an underline step around a descender ("skip-ink"), the way a browser does.
107
+ *
108
+ * Scanline fill: sample a few horizontal lines across the band, find every place the outline
109
+ * crosses them, and pair the crossings up into filled spans. A handful of scanlines is plenty -
110
+ * the band is a few percent of the em tall, and a descender stem does not wander inside it.
111
+ *
112
+ * `yTop` / `yBottom` are in font units, y UP from the baseline (so both are negative under it).
113
+ * Returns [] for a glyph with no outline (a space, an unmapped code point, a composite we cannot
114
+ * decompose) - the caller then leaves the line unbroken there, which is the safe direction.
115
+ */
116
+ inkSpansInBand(codePoint: number, yTop: number, yBottom: number): Array<[number, number]>;
117
+ /** True if the font declares any horizontal kerning (kern table or GPOS). */
118
+ kerns(): boolean;
119
+ private kernCache;
120
+ /** Kerning between two glyphs, in em/1000 (the standard-14 unit); 0 if the pair is not kerned.
121
+ * Negative tightens, matching the AFM sign. GPOS wins over the legacy `kern` table when both
122
+ * exist (it is what a modern shaper uses, and can carry more pairs). */
123
+ getKerning(leftGid: number, rightGid: number): number;
124
+ private readKern;
125
+ private readGpos;
126
+ private gposKern;
127
+ private static valueRecordSize;
128
+ private xAdvance;
129
+ private coverageIndex;
130
+ private classOf;
78
131
  private table;
79
132
  private readTableDirectory;
80
133
  private readHmtx;
@@ -3,6 +3,21 @@
3
3
  // text width the same way AFMParser does for the standard-14. Embedding/subsetting come later.
4
4
  import { i16, latin1FromBytes, u8, u16, u32 } from "./bytes.js";
5
5
  const IDENTITY = [1, 0, 0, 1, 0, 0];
6
+ /** Sorts x-intervals and unions the overlapping ones. */
7
+ export function mergeSpans(spans) {
8
+ if (spans.length === 0)
9
+ return spans;
10
+ const sorted = [...spans].sort((a, b) => a[0] - b[0]);
11
+ const out = [sorted[0]];
12
+ for (const [start, end] of sorted.slice(1)) {
13
+ const last = out[out.length - 1];
14
+ if (start <= last[1])
15
+ last[1] = Math.max(last[1], end);
16
+ else
17
+ out.push([start, end]);
18
+ }
19
+ return out;
20
+ }
6
21
  function isIdentity(m) {
7
22
  return m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;
8
23
  }
@@ -37,6 +52,15 @@ export class TTFParser {
37
52
  // FontDescriptor metrics, in PDF glyph space (1000 units / em).
38
53
  this.ascent = 0;
39
54
  this.descent = 0;
55
+ // Extra leading the font asks for between two lines (hhea), same glyph space. Often 0.
56
+ this.lineGap = 0;
57
+ // Decoration metrics in RAW font units (divide by unitsPerEm). `post` always carries the underline
58
+ // pair; `OS/2` only carries sxHeight/sCapHeight from version 2 on, so those may stay 0 and are
59
+ // then measured off the glyph outlines instead (see `decoration()`).
60
+ this.underlinePositionRaw = 0; // negative = below the baseline
61
+ this.underlineThicknessRaw = 0;
62
+ this.xHeightRaw = 0;
63
+ this.capHeightRaw = 0;
40
64
  this.bbox = [0, 0, 0, 0];
41
65
  this.numGlyphs = 0;
42
66
  this.numHMetrics = 0;
@@ -53,6 +77,16 @@ export class TTFParser {
53
77
  // COLR v1: base glyph id → the absolute offset of its Paint table (a recursive paint graph).
54
78
  this.colrBaseV1 = new Map();
55
79
  this.colrLayerListOffset = 0; // absolute offset of the v1 LayerList (paint-offset array)
80
+ // Kerning: (leftGid << 16 | rightGid) -> value in FONT UNITS (from the `kern` table and/or GPOS).
81
+ this.kernPairs = new Map();
82
+ this.hasKerning = false;
83
+ // GPOS Type 2 (pair positioning) subtables, in absolute byte offsets. Queried per pair (format 2
84
+ // is class-based, so it cannot be enumerated into `kernPairs` up front). Preferred over `kern`.
85
+ this.gposPairPos = [];
86
+ // Memoised getKerning results, keyed (leftGid << 16 | rightGid) -> em/1000. A GPOS lookup walks
87
+ // subtables (coverage + classDef) per pair, and a long document repeats the same pairs thousands
88
+ // of times, so the first lookup of a pair pays; the rest are O(1).
89
+ this.kernCache = new Map();
56
90
  this.readTableDirectory();
57
91
  const head = this.table("head").offset;
58
92
  this.unitsPerEm = u16(this.data, head + 18);
@@ -67,6 +101,8 @@ export class TTFParser {
67
101
  const hhea = this.table("hhea").offset;
68
102
  this.ascent = this.toGlyphSpace(i16(this.data, hhea + 4));
69
103
  this.descent = this.toGlyphSpace(i16(this.data, hhea + 6));
104
+ this.lineGap = this.toGlyphSpace(i16(this.data, hhea + 8));
105
+ this.readDecorationMetrics();
70
106
  this.indexToLocFormat = i16(this.data, head + 50);
71
107
  this.readHmtx();
72
108
  this.readCmap();
@@ -74,6 +110,19 @@ export class TTFParser {
74
110
  this.readColr();
75
111
  this.readCpal();
76
112
  }
113
+ // Kerning tables are optional and only ever make text prettier; a malformed one must degrade to
114
+ // "no kerning", never break font loading. Guard both.
115
+ try {
116
+ if (this.tables["kern"])
117
+ this.readKern();
118
+ if (this.tables["GPOS"])
119
+ this.readGpos();
120
+ }
121
+ catch {
122
+ this.kernPairs.clear();
123
+ this.gposPairPos = [];
124
+ this.hasKerning = false;
125
+ }
77
126
  }
78
127
  // The raw font bytes, for the /FontFile2 stream.
79
128
  getData() {
@@ -131,6 +180,325 @@ export class TTFParser {
131
180
  width += this.getCharWidth(ch, fontSize);
132
181
  return width;
133
182
  }
183
+ // `post` carries the underline pair (always, from its header); `OS/2` carries the x- and cap-height
184
+ // but only from version 2 on. Both tables are optional in principle, so nothing here may throw.
185
+ readDecorationMetrics() {
186
+ const post = this.tables["post"];
187
+ if (post) {
188
+ this.underlinePositionRaw = i16(this.data, post.offset + 8);
189
+ this.underlineThicknessRaw = i16(this.data, post.offset + 10);
190
+ }
191
+ const os2 = this.tables["OS/2"];
192
+ if (os2 && u16(this.data, os2.offset) >= 2) {
193
+ this.xHeightRaw = i16(this.data, os2.offset + 86);
194
+ this.capHeightRaw = i16(this.data, os2.offset + 88);
195
+ }
196
+ }
197
+ /**
198
+ * Underline / strikethrough geometry, as fractions of the em.
199
+ *
200
+ * A font without `post` (rare) gets the classic 10% below the baseline at 5% thickness - the same
201
+ * numbers all 14 standard AFMs happen to declare, so it is a measured convention rather than an
202
+ * invention. A font whose `OS/2` predates version 2 has no x- or cap-height, so we MEASURE them off
203
+ * the outlines of `x` and `H` instead of guessing.
204
+ */
205
+ decoration() {
206
+ if (this.cachedDecoration)
207
+ return this.cachedDecoration;
208
+ const em = this.unitsPerEm;
209
+ const xHeight = this.xHeightRaw || this.outlineTop(0x78); // "x"
210
+ const capHeight = this.capHeightRaw || this.outlineTop(0x48); // "H"
211
+ this.cachedDecoration = {
212
+ underlinePosition: this.underlinePositionRaw ? -this.underlinePositionRaw / em : 0.1,
213
+ underlineThickness: this.underlineThicknessRaw ? this.underlineThicknessRaw / em : 0.05,
214
+ xHeight: xHeight / em,
215
+ capHeight: capHeight / em,
216
+ };
217
+ return this.cachedDecoration;
218
+ }
219
+ /** The highest ON-CURVE point of a code point's outline, in font units; 0 for a missing glyph.
220
+ * A quadratic's control point may sit above the curve, so it is not a bound - and `x`/`H` have
221
+ * flat tops in any face where this fallback matters. */
222
+ outlineTop(codePoint) {
223
+ let top = 0;
224
+ for (const cmd of this.getGlyphPath(this.getGlyphIndex(codePoint))) {
225
+ if (cmd.type !== "Z" && cmd.y > top)
226
+ top = cmd.y;
227
+ }
228
+ return top;
229
+ }
230
+ /**
231
+ * Where a glyph's INK crosses a horizontal band, as x-intervals in font units (pen origin at 0).
232
+ * This is what lets an underline step around a descender ("skip-ink"), the way a browser does.
233
+ *
234
+ * Scanline fill: sample a few horizontal lines across the band, find every place the outline
235
+ * crosses them, and pair the crossings up into filled spans. A handful of scanlines is plenty -
236
+ * the band is a few percent of the em tall, and a descender stem does not wander inside it.
237
+ *
238
+ * `yTop` / `yBottom` are in font units, y UP from the baseline (so both are negative under it).
239
+ * Returns [] for a glyph with no outline (a space, an unmapped code point, a composite we cannot
240
+ * decompose) - the caller then leaves the line unbroken there, which is the safe direction.
241
+ */
242
+ inkSpansInBand(codePoint, yTop, yBottom) {
243
+ const path = this.getGlyphPath(this.getGlyphIndex(codePoint));
244
+ if (path.length === 0)
245
+ return [];
246
+ // Flatten to straight edges; a quadratic becomes a short polyline (the band is thin, so a
247
+ // coarse subdivision is already below the printing resolution).
248
+ const edges = [];
249
+ let startX = 0;
250
+ let startY = 0;
251
+ let curX = 0;
252
+ let curY = 0;
253
+ const edge = (x, y) => {
254
+ edges.push([curX, curY, x, y]);
255
+ curX = x;
256
+ curY = y;
257
+ };
258
+ for (const cmd of path) {
259
+ if (cmd.type === "M") {
260
+ [curX, curY] = [cmd.x, cmd.y];
261
+ [startX, startY] = [cmd.x, cmd.y];
262
+ }
263
+ else if (cmd.type === "L") {
264
+ edge(cmd.x, cmd.y);
265
+ }
266
+ else if (cmd.type === "Q") {
267
+ const [x0, y0] = [curX, curY];
268
+ const STEPS = 8;
269
+ for (let i = 1; i <= STEPS; i++) {
270
+ const t = i / STEPS;
271
+ const u = 1 - t;
272
+ edge(u * u * x0 + 2 * u * t * cmd.cx + t * t * cmd.x, u * u * y0 + 2 * u * t * cmd.cy + t * t * cmd.y);
273
+ }
274
+ }
275
+ else {
276
+ edge(startX, startY); // Z: close the contour
277
+ }
278
+ }
279
+ const SCANLINES = 5;
280
+ const spans = [];
281
+ for (let i = 0; i < SCANLINES; i++) {
282
+ const y = yTop + ((yBottom - yTop) * i) / (SCANLINES - 1);
283
+ const xs = [];
284
+ for (const [x0, y0, x1, y1] of edges) {
285
+ if (y0 === y1)
286
+ continue;
287
+ // Half-open test so a vertex on the scanline is counted exactly once.
288
+ if (y >= Math.min(y0, y1) && y < Math.max(y0, y1)) {
289
+ xs.push(x0 + ((y - y0) / (y1 - y0)) * (x1 - x0));
290
+ }
291
+ }
292
+ xs.sort((a, b) => a - b);
293
+ for (let k = 0; k + 1 < xs.length; k += 2)
294
+ spans.push([xs[k], xs[k + 1]]);
295
+ }
296
+ return mergeSpans(spans);
297
+ }
298
+ /** True if the font declares any horizontal kerning (kern table or GPOS). */
299
+ kerns() {
300
+ return this.hasKerning;
301
+ }
302
+ /** Kerning between two glyphs, in em/1000 (the standard-14 unit); 0 if the pair is not kerned.
303
+ * Negative tightens, matching the AFM sign. GPOS wins over the legacy `kern` table when both
304
+ * exist (it is what a modern shaper uses, and can carry more pairs). */
305
+ getKerning(leftGid, rightGid) {
306
+ const key = (leftGid << 16) | rightGid;
307
+ const cached = this.kernCache.get(key);
308
+ if (cached !== undefined)
309
+ return cached;
310
+ let units;
311
+ if (this.gposPairPos.length > 0)
312
+ units = this.gposKern(leftGid, rightGid);
313
+ if (units === undefined)
314
+ units = this.kernPairs.get(key);
315
+ const em = units === undefined ? 0 : Math.round((units * 1000) / this.unitsPerEm);
316
+ this.kernCache.set(key, em);
317
+ return em;
318
+ }
319
+ // The legacy `kern` table, format 0 (an explicit list of glyph-pair adjustments). Only horizontal
320
+ // format-0 subtables are read; GPOS (parsed separately) supersedes this in modern fonts, but old
321
+ // TrueType (DejaVu, FreeSans) carries its kerning here.
322
+ readKern() {
323
+ const base = this.tables["kern"].offset;
324
+ // The OpenType (Microsoft) header is version:u16 = 0, nTables:u16. (Apple's is a u32 version; the
325
+ // fonts we target use the OpenType form.)
326
+ if (u16(this.data, base) !== 0)
327
+ return;
328
+ const nTables = u16(this.data, base + 2);
329
+ let p = base + 4;
330
+ for (let t = 0; t < nTables; t++) {
331
+ const length = u16(this.data, p + 2);
332
+ const coverage = u16(this.data, p + 4);
333
+ const format = coverage >> 8;
334
+ const horizontal = (coverage & 0x1) === 1;
335
+ if (format === 0 && horizontal) {
336
+ const nPairs = u16(this.data, p + 6);
337
+ let q = p + 14; // past nPairs, searchRange, entrySelector, rangeShift
338
+ for (let i = 0; i < nPairs; i++) {
339
+ const left = u16(this.data, q);
340
+ const right = u16(this.data, q + 2);
341
+ const value = i16(this.data, q + 4);
342
+ this.kernPairs.set((left << 16) | right, value);
343
+ q += 6;
344
+ }
345
+ }
346
+ p += length;
347
+ }
348
+ if (this.kernPairs.size > 0)
349
+ this.hasKerning = true;
350
+ }
351
+ // GPOS pair-adjustment kerning. We collect the PairPos (lookup type 2) subtables of the `kern`
352
+ // FEATURE only - not every pair-positioning lookup - so this is kerning, not arbitrary shaping.
353
+ // Script/language selection is skipped: the `kern` feature is the same across the Latin scripts we
354
+ // target, so a flat scan of the feature list for tag "kern" is correct here. Only pair positioning
355
+ // (type 2) is read; the rest of GPOS (mark attachment, cursive, contextual) is not kerning.
356
+ readGpos() {
357
+ const base = this.tables["GPOS"].offset;
358
+ const featureListOffset = base + u16(this.data, base + 6);
359
+ const lookupListOffset = base + u16(this.data, base + 8);
360
+ // Every lookup index referenced by a "kern" feature.
361
+ const kernLookups = new Set();
362
+ const featureCount = u16(this.data, featureListOffset);
363
+ for (let i = 0; i < featureCount; i++) {
364
+ const rec = featureListOffset + 2 + i * 6;
365
+ const tag = String.fromCharCode(this.data[rec], this.data[rec + 1], this.data[rec + 2], this.data[rec + 3]);
366
+ if (tag !== "kern")
367
+ continue;
368
+ const feature = featureListOffset + u16(this.data, rec + 4);
369
+ const lookupIndexCount = u16(this.data, feature + 2);
370
+ for (let j = 0; j < lookupIndexCount; j++) {
371
+ kernLookups.add(u16(this.data, feature + 4 + j * 2));
372
+ }
373
+ }
374
+ if (kernLookups.size === 0)
375
+ return;
376
+ // The PairPos subtables of those lookups (a lookup of another type in the set is ignored).
377
+ const lookupCount = u16(this.data, lookupListOffset);
378
+ for (const idx of kernLookups) {
379
+ if (idx >= lookupCount)
380
+ continue;
381
+ const lookup = lookupListOffset + u16(this.data, lookupListOffset + 2 + idx * 2);
382
+ if (u16(this.data, lookup) !== 2)
383
+ continue; // lookupType 2 = pair adjustment
384
+ const subTableCount = u16(this.data, lookup + 4);
385
+ for (let s = 0; s < subTableCount; s++) {
386
+ this.gposPairPos.push(lookup + u16(this.data, lookup + 6 + s * 2));
387
+ }
388
+ }
389
+ if (this.gposPairPos.length > 0)
390
+ this.hasKerning = true;
391
+ }
392
+ // The XAdvance adjustment on the LEFT glyph for a pair, in font units, from the first PairPos
393
+ // subtable that covers it; undefined if none does. (Kerning only ever uses value1's XAdvance.)
394
+ gposKern(leftGid, rightGid) {
395
+ for (const sub of this.gposPairPos) {
396
+ const posFormat = u16(this.data, sub);
397
+ const coverage = sub + u16(this.data, sub + 2);
398
+ const covIndex = this.coverageIndex(coverage, leftGid);
399
+ if (covIndex < 0)
400
+ continue;
401
+ const valueFormat1 = u16(this.data, sub + 4);
402
+ const valueFormat2 = u16(this.data, sub + 6);
403
+ const v1size = TTFParser.valueRecordSize(valueFormat1);
404
+ const v2size = TTFParser.valueRecordSize(valueFormat2);
405
+ if (posFormat === 1) {
406
+ const pairSet = sub + u16(this.data, sub + 10 + covIndex * 2);
407
+ const pairValueCount = u16(this.data, pairSet);
408
+ const recSize = 2 + v1size + v2size;
409
+ for (let i = 0; i < pairValueCount; i++) {
410
+ const rec = pairSet + 2 + i * recSize;
411
+ if (u16(this.data, rec) === rightGid) {
412
+ return this.xAdvance(rec + 2, valueFormat1);
413
+ }
414
+ }
415
+ }
416
+ else if (posFormat === 2) {
417
+ const classDef1 = sub + u16(this.data, sub + 8);
418
+ const classDef2 = sub + u16(this.data, sub + 10);
419
+ const class2Count = u16(this.data, sub + 14);
420
+ const c1 = this.classOf(classDef1, leftGid);
421
+ const c2 = this.classOf(classDef2, rightGid);
422
+ const recSize = v1size + v2size;
423
+ const record = sub + 16 + (c1 * class2Count + c2) * recSize;
424
+ return this.xAdvance(record, valueFormat1);
425
+ }
426
+ }
427
+ return undefined;
428
+ }
429
+ static valueRecordSize(valueFormat) {
430
+ let bits = 0;
431
+ for (let m = valueFormat; m; m >>= 1)
432
+ bits += m & 1;
433
+ return bits * 2;
434
+ }
435
+ // The XAdvance field of a GPOS value record, or 0 if the format has none. XAdvance (bit 0x0004) is
436
+ // preceded by XPlacement (0x0001) and YPlacement (0x0002), each an i16 when present.
437
+ xAdvance(recordOffset, valueFormat) {
438
+ if ((valueFormat & 0x0004) === 0)
439
+ return 0;
440
+ let off = recordOffset;
441
+ if (valueFormat & 0x0001)
442
+ off += 2;
443
+ if (valueFormat & 0x0002)
444
+ off += 2;
445
+ return i16(this.data, off);
446
+ }
447
+ // Coverage index of a glyph, or -1. Format 1: sorted glyph list. Format 2: sorted ranges.
448
+ coverageIndex(offset, gid) {
449
+ const format = u16(this.data, offset);
450
+ if (format === 1) {
451
+ const count = u16(this.data, offset + 2);
452
+ let lo = 0;
453
+ let hi = count - 1;
454
+ while (lo <= hi) {
455
+ const mid = (lo + hi) >> 1;
456
+ const g = u16(this.data, offset + 4 + mid * 2);
457
+ if (gid < g)
458
+ hi = mid - 1;
459
+ else if (gid > g)
460
+ lo = mid + 1;
461
+ else
462
+ return mid;
463
+ }
464
+ return -1;
465
+ }
466
+ if (format === 2) {
467
+ const rangeCount = u16(this.data, offset + 2);
468
+ for (let i = 0; i < rangeCount; i++) {
469
+ const rec = offset + 4 + i * 6;
470
+ const start = u16(this.data, rec);
471
+ const end = u16(this.data, rec + 2);
472
+ if (gid >= start && gid <= end)
473
+ return u16(this.data, rec + 4) + (gid - start);
474
+ }
475
+ }
476
+ return -1;
477
+ }
478
+ // Class of a glyph in a ClassDef, or 0 (the default class). Format 1: run from a start glyph.
479
+ // Format 2: ranges. Glyphs not listed are class 0.
480
+ classOf(offset, gid) {
481
+ const format = u16(this.data, offset);
482
+ if (format === 1) {
483
+ const startGlyph = u16(this.data, offset + 2);
484
+ const glyphCount = u16(this.data, offset + 4);
485
+ if (gid >= startGlyph && gid < startGlyph + glyphCount) {
486
+ return u16(this.data, offset + 6 + (gid - startGlyph) * 2);
487
+ }
488
+ return 0;
489
+ }
490
+ if (format === 2) {
491
+ const rangeCount = u16(this.data, offset + 2);
492
+ for (let i = 0; i < rangeCount; i++) {
493
+ const rec = offset + 4 + i * 6;
494
+ const start = u16(this.data, rec);
495
+ const end = u16(this.data, rec + 2);
496
+ if (gid >= start && gid <= end)
497
+ return u16(this.data, rec + 4);
498
+ }
499
+ }
500
+ return 0;
501
+ }
134
502
  table(tag) {
135
503
  const t = this.tables[tag];
136
504
  if (!t)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jasy/pdf",
3
- "version": "1.0.0-alpha.5",
3
+ "version": "1.0.0-alpha.7",
4
4
  "description": "Declarative, component-based PDF generation in pure TypeScript - Flutter-style components, real AFM font metrics, a hand-rolled PDF writer. No headless browser, no Java.",
5
5
  "keywords": [
6
6
  "declarative",