-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathembedded.js
290 lines (245 loc) · 7.4 KB
/
embedded.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import PDFFont from '../font';
const toHex = function (num) {
return `0000${num.toString(16)}`.slice(-4);
};
class EmbeddedFont extends PDFFont {
constructor(document, font, id) {
super();
this.document = document;
this.font = font;
this.id = id;
this.subset = this.font.createSubset();
this.unicode = [[0]];
this.widths = [this.font.getGlyph(0).advanceWidth];
this.name = this.font.postscriptName;
this.scale = 1000 / this.font.unitsPerEm;
this.ascender = this.font.ascent * this.scale;
this.descender = this.font.descent * this.scale;
this.xHeight = this.font.xHeight * this.scale;
this.capHeight = this.font.capHeight * this.scale;
this.lineGap = this.font.lineGap * this.scale;
this.bbox = this.font.bbox;
if (document.options.fontLayoutCache !== false) {
this.layoutCache = Object.create(null);
}
}
layoutRun(text, features) {
const run = this.font.layout(text, features);
// Normalize position values
for (let i = 0; i < run.positions.length; i++) {
const position = run.positions[i];
for (let key in position) {
position[key] *= this.scale;
}
position.advanceWidth = run.glyphs[i].advanceWidth * this.scale;
}
return run;
}
layoutCached(text) {
if (!this.layoutCache) {
return this.layoutRun(text);
}
let cached;
if ((cached = this.layoutCache[text])) {
return cached;
}
const run = this.layoutRun(text);
this.layoutCache[text] = run;
return run;
}
layout(text, features, onlyWidth) {
// Skip the cache if any user defined features are applied
if (features) {
return this.layoutRun(text, features);
}
let glyphs = onlyWidth ? null : [];
let positions = onlyWidth ? null : [];
let advanceWidth = 0;
// Split the string by words to increase cache efficiency.
// For this purpose, spaces and tabs are a good enough delimeter.
let last = 0;
let index = 0;
while (index <= text.length) {
var needle;
if (
(index === text.length && last < index) ||
((needle = text.charAt(index)), [' ', '\t'].includes(needle))
) {
const run = this.layoutCached(text.slice(last, ++index));
if (!onlyWidth) {
glyphs = glyphs.concat(run.glyphs);
positions = positions.concat(run.positions);
}
advanceWidth += run.advanceWidth;
last = index;
} else {
index++;
}
}
return { glyphs, positions, advanceWidth };
}
encode(text, features) {
const { glyphs, positions } = this.layout(text, features);
const res = [];
for (let i = 0; i < glyphs.length; i++) {
const glyph = glyphs[i];
const gid = this.subset.includeGlyph(glyph.id);
res.push(`0000${gid.toString(16)}`.slice(-4));
if (this.widths[gid] == null) {
this.widths[gid] = glyph.advanceWidth * this.scale;
}
if (this.unicode[gid] == null) {
this.unicode[gid] = glyph.codePoints;
}
}
return [res, positions];
}
widthOfString(string, size, features) {
const width = this.layout(string, features, true).advanceWidth;
const scale = size / 1000;
return width * scale;
}
embed() {
const isCFF = this.subset.cff != null;
const fontFile = this.document.ref();
if (isCFF) {
fontFile.data.Subtype = 'CIDFontType0C';
}
fontFile.end(this.subset.encode());
const familyClass =
((this.font['OS/2'] != null
? this.font['OS/2'].sFamilyClass
: undefined) || 0) >> 8;
let flags = 0;
if (this.font.post.isFixedPitch) {
flags |= 1 << 0;
}
if (1 <= familyClass && familyClass <= 7) {
flags |= 1 << 1;
}
flags |= 1 << 2; // assume the font uses non-latin characters
if (familyClass === 10) {
flags |= 1 << 3;
}
if (this.font.head.macStyle.italic) {
flags |= 1 << 6;
}
// generate a tag (6 uppercase letters. 17 is the char code offset from '0' to 'A'. 73 will map to 'Z')
const tag = [1, 2, 3, 4, 5, 6]
.map((i) => String.fromCharCode((this.id.charCodeAt(i) || 73) + 17))
.join('');
const name = tag + '+' + this.font.postscriptName?.replaceAll(' ', '_');
const { bbox } = this.font;
const descriptor = this.document.ref({
Type: 'FontDescriptor',
FontName: name,
Flags: flags,
FontBBox: [
bbox.minX * this.scale,
bbox.minY * this.scale,
bbox.maxX * this.scale,
bbox.maxY * this.scale,
],
ItalicAngle: this.font.italicAngle,
Ascent: this.ascender,
Descent: this.descender,
CapHeight: (this.font.capHeight || this.font.ascent) * this.scale,
XHeight: (this.font.xHeight || 0) * this.scale,
StemV: 0,
}); // not sure how to calculate this
if (isCFF) {
descriptor.data.FontFile3 = fontFile;
} else {
descriptor.data.FontFile2 = fontFile;
}
if (this.document.subset && this.document.subset === 1) {
const CIDSet = Buffer.from('FFFFFFFFC0', 'hex');
const CIDSetRef = this.document.ref();
CIDSetRef.write(CIDSet);
CIDSetRef.end();
descriptor.data.CIDSet = CIDSetRef;
}
descriptor.end();
const descendantFontData = {
Type: 'Font',
Subtype: 'CIDFontType0',
BaseFont: name,
CIDSystemInfo: {
Registry: new String('Adobe'),
Ordering: new String('Identity'),
Supplement: 0,
},
FontDescriptor: descriptor,
W: [0, this.widths],
};
if (!isCFF) {
descendantFontData.Subtype = 'CIDFontType2';
descendantFontData.CIDToGIDMap = 'Identity';
}
const descendantFont = this.document.ref(descendantFontData);
descendantFont.end();
this.dictionary.data = {
Type: 'Font',
Subtype: 'Type0',
BaseFont: name,
Encoding: 'Identity-H',
DescendantFonts: [descendantFont],
ToUnicode: this.toUnicodeCmap(),
};
return this.dictionary.end();
}
// Maps the glyph ids encoded in the PDF back to unicode strings
// Because of ligature substitutions and the like, there may be one or more
// unicode characters represented by each glyph.
toUnicodeCmap() {
const cmap = this.document.ref();
const entries = [];
for (let codePoints of this.unicode) {
const encoded = [];
// encode codePoints to utf16
for (let value of codePoints) {
if (value > 0xffff) {
value -= 0x10000;
encoded.push(toHex(((value >>> 10) & 0x3ff) | 0xd800));
value = 0xdc00 | (value & 0x3ff);
}
encoded.push(toHex(value));
}
entries.push(`<${encoded.join(' ')}>`);
}
const chunkSize = 256;
const chunks = Math.ceil(entries.length / chunkSize);
const ranges = [];
for (let i = 0; i < chunks; i++) {
const start = i * chunkSize;
const end = Math.min((i + 1) * chunkSize, entries.length);
ranges.push(
`<${toHex(start)}> <${toHex(end - 1)}> [${entries.slice(start, end).join(' ')}]`,
);
}
cmap.end(`\
/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo <<
/Registry (Adobe)
/Ordering (UCS)
/Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000><ffff>
endcodespacerange
1 beginbfrange
${ranges.join('\n')}
endbfrange
endcmap
CMapName currentdict /CMap defineresource pop
end
end\
`);
return cmap;
}
}
export default EmbeddedFont;