pdf-lib
Version:
Library for creating and modifying PDF files in JavaScript
96 lines (94 loc) • 3.57 kB
JavaScript
import PDFDocument from '../../pdf-document/PDFDocument';
import { PDFDictionary, PDFHexString, PDFName, } from '../../pdf-objects';
import values from 'lodash/values';
import { isInstance, oneOf, validate } from '../../../utils/validate';
import Standard14Fonts from '../../pdf-document/Standard14Fonts';
var UnicodeToWinAnsiMap = {
402: 131,
8211: 150,
8212: 151,
8216: 145,
8217: 146,
8218: 130,
8220: 147,
8221: 148,
8222: 132,
8224: 134,
8225: 135,
8226: 149,
8230: 133,
8364: 128,
8240: 137,
8249: 139,
8250: 155,
710: 136,
8482: 153,
338: 140,
339: 156,
732: 152,
352: 138,
353: 154,
376: 159,
381: 142,
382: 158,
};
/**
* This Factory supports Standard fonts. Note that the apparent
* hardcoding of values for OpenType fonts does not actually affect TrueType
* fonts.
*
* A note of thanks to the developers of https://github.com/foliojs/pdfkit,
* as this class borrows from:
* https://github.com/foliojs/pdfkit/blob/f91bdd61c164a72ea06be1a43dc0a412afc3925f/lib/font/afm.coffee
*/
var PDFStandardFontFactory = /** @class */ (function () {
function PDFStandardFontFactory(fontName) {
var _this = this;
this.encodeText = function (text) {
return PDFHexString.fromString(text
.split('')
.map(function (char) { return char.charCodeAt(0); })
.map(function (charCode) { return UnicodeToWinAnsiMap[charCode] || charCode; })
.map(function (charCode) { return charCode.toString(16); })
.join(''));
};
/*
TODO:
A Type 1 font dictionary may contain the entries listed in Table 111.
Some entries are optional for the standard 14 fonts listed under 9.6.2.2,
"Standard Type 1 Fonts (Standard 14 Fonts)", but are required otherwise.
NOTE: For compliance sake, these standard 14 font dictionaries need to be
updated to include the following entries:
• FirstChar
• LastChar
• Widths
• FontDescriptor
See "Table 111 – Entries in a Type 1 font dictionary (continued)"
for details on this...
*/
this.embedFontIn = function (pdfDoc) {
validate(pdfDoc, isInstance(PDFDocument), 'PDFFontFactory.embedFontIn: "pdfDoc" must be an instance of PDFDocument');
return pdfDoc.register(PDFDictionary.from({
Type: PDFName.from('Font'),
Subtype: PDFName.from('Type1'),
Encoding: PDFName.from('WinAnsiEncoding'),
BaseFont: PDFName.from(_this.fontName),
}, pdfDoc.index));
};
/** @hidden */
this.getWidths = function () {
throw new Error('getWidths() Not implemented yet for Standard Font');
};
this.getCodePointWidth = function () {
throw new Error('getCodePointWidth() Not implemented yet for Standard Font');
};
validate(fontName, oneOf.apply(void 0, Standard14Fonts), 'PDFDocument.embedStandardFont: "fontName" must be one of the Standard 14 Fonts: ' +
values(Standard14Fonts).join(', '));
this.fontName = fontName;
}
PDFStandardFontFactory.for = function (fontName) {
return new PDFStandardFontFactory(fontName);
};
return PDFStandardFontFactory;
}());
export default PDFStandardFontFactory;