UNPKG

afm

Version:
73 lines (67 loc) 2.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fs_1 = require("fs"); /** parseCharMetrics() takes a single line from the "CharMetrics" section in an AFM file, and extracts the crucial metrics for that character. For example, the line describing capital A in Times-Roman from Adobe's Core14 font set is this: C 65 ; WX 722 ; N A ; B 15 0 706 674 ; For which parseCharMetrics() would return a plain object: { charCode: 65, width: 722, name: 'A' } From https://partners.adobe.com/public/developer/en/font/5004.AFM_Spec.pdf: > `C integer`: Decimal value of default character code (−1 if not encoded). > `CH` hex`: Same as C, but the character code is given in hexadecimal. Either C or CH is required > `WX number`: Width of character. > `N name`: (Optional.) PostScript language character name. */ function parseCharMetrics(line) { var charCode_match = line.match(/C\s+(\d+|-1)/); var width_match = line.match(/WX\s+(\d+)/); var name_match = line.match(/N\s+(\w+)/); var charCode = charCode_match ? parseInt(charCode_match[1], 10) : null; var width = width_match ? parseInt(width_match[1], 10) : null; var name = name_match ? name_match[1] : null; return { charCode: charCode, width: width, name: name }; } exports.parseCharMetrics = parseCharMetrics; /** parseFontMetrics() takes an entire AFM file as a string, finds the "CharMetrics" section, and parses all of the char metrics lines from that section, returning an Array of those charmetrics. */ function parseFontMetrics(data) { var start_match = data.match(/^StartCharMetrics\s+(\d+)/m); var end_match = data.match(/^EndCharMetrics/m); var char_metrics_start = start_match.index + start_match[0].length; var char_metrics_data = data.slice(char_metrics_start, end_match.index); var char_metrics_lines = char_metrics_data.trim().split(/\r\n|\r|\n|\t/); return char_metrics_lines.map(parseCharMetrics); } exports.parseFontMetrics = parseFontMetrics; /** Parse Adobe Font Metrics data from inputStream and write array of CharMetrics objects to outputStream as JSON. */ function convert(inputStream, outputStream, callback) { var chunks = []; inputStream .on('data', function (chunk) { chunks.push(chunk); }) .on('end', function () { var data = Buffer.concat(chunks).toString('ascii'); var charMetrics = parseFontMetrics(data); var json = JSON.stringify(charMetrics); outputStream.write(json); }); } exports.convert = convert; if (require.main === module) { var _a = process.argv, input_argument = _a[2], output_argument = _a[3]; var inputStream = input_argument ? fs_1.createReadStream(input_argument) : process.stdin; var outputStream = output_argument ? fs_1.createWriteStream(output_argument) : process.stdout; convert(inputStream, outputStream, function (error) { if (error) throw error; process.exit(); }); }