UNPKG

pdf-lib

Version:

Create and modify PDF files with JavaScript

57 lines 2.8 kB
import { toHexString, toHexStringOfMinLength } from "../../utils"; import { hasSurrogates, highSurrogate, isWithinBMP, lowSurrogate, } from "../../utils/unicode"; /** `glyphs` should be an array of unique glyphs sorted by their ID */ export var createCmap = function (glyphs, glyphId) { var bfRanges = []; var first = glyphId(glyphs[0]); var mappings = []; for (var idx = 0, len = glyphs.length; idx < len; idx++) { var currGlyph = glyphs[idx]; var nextGlyph = glyphs[idx + 1]; var currGlyphId = glyphId(currGlyph); var nextGlyphId = glyphId(nextGlyph); var codePoints = currGlyph.codePoints; mappings.push(cmapHexFormat.apply(void 0, codePoints.map(cmapCodePointFormat))); if (idx !== 0 && nextGlyphId - currGlyphId !== 1) { var last = currGlyphId; var delimiters = [ cmapHexFormat(cmapHexString(first)), cmapHexFormat(cmapHexString(last)), ]; bfRanges.push([delimiters, mappings]); first = nextGlyphId; mappings = []; } } return fillCmapTemplate(bfRanges); }; /* =============================== Templates ================================ */ // prettier-ignore var fillBfrangeTemplate = function (_a) { var _b = _a[0], start = _b[0], end = _b[1], mappings = _a[1]; return ("\n" + mappings.length + " beginbfrange\n" + start + " " + end + " [" + mappings.join(' ') + "]\nendbfrange\n").trim(); }; // prettier-ignore var fillCmapTemplate = function (bfRanges) { return ("\n/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange\n" + bfRanges.map(fillBfrangeTemplate).join('\n') + "\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n").trim(); }; /* =============================== Utilities ================================ */ var cmapHexFormat = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return "<" + values.join('') + ">"; }; var cmapHexString = function (value) { return toHexStringOfMinLength(value, 4); }; var cmapCodePointFormat = function (codePoint) { if (isWithinBMP(codePoint)) return cmapHexString(codePoint); if (hasSurrogates(codePoint)) { var hs = highSurrogate(codePoint); var ls = lowSurrogate(codePoint); return "" + cmapHexString(hs) + cmapHexString(ls); } var hex = toHexString(codePoint); var msg = "0x" + hex + " is not a valid UTF-8 or UTF-16 codepoint."; throw new Error(msg); }; //# sourceMappingURL=CMap.js.map