You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TTFReader.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.fonts.apps;
  19. import java.io.FileInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import javax.xml.parsers.DocumentBuilderFactory;
  25. import org.w3c.dom.Document;
  26. import org.w3c.dom.Element;
  27. import org.xml.sax.Attributes;
  28. import org.xml.sax.SAXException;
  29. import org.apache.fop.Version;
  30. import org.apache.fop.fonts.CMapSegment;
  31. import org.apache.fop.fonts.FontUtil;
  32. import org.apache.fop.fonts.truetype.FontFileReader;
  33. import org.apache.fop.fonts.truetype.OFFontLoader;
  34. import org.apache.fop.fonts.truetype.TTFFile;
  35. // CSOFF: LineLengthCheck
  36. /**
  37. * A tool which reads TTF files and generates
  38. * XML font metrics file for use in FOP.
  39. */
  40. public class TTFReader extends AbstractFontReader {
  41. /** Used to detect incompatible versions of the generated XML files */
  42. public static final String METRICS_VERSION_ATTR = "metrics-version";
  43. /** Current version number for the metrics file */
  44. public static final int METRICS_VERSION = 2;
  45. /**
  46. * Main constructor.
  47. */
  48. public TTFReader() {
  49. super();
  50. }
  51. private static void displayUsage() {
  52. System.out.println(
  53. "java " + TTFReader.class.getName() + " [options] fontfile.ttf xmlfile.xml");
  54. System.out.println();
  55. System.out.println("where options can be:");
  56. System.out.println("-t Trace mode");
  57. System.out.println("-d Debug mode");
  58. System.out.println("-q Quiet mode");
  59. System.out.println("-enc ansi");
  60. System.out.println(" With this option you create a WinAnsi encoded font.");
  61. System.out.println(" The default is to create a CID keyed font.");
  62. System.out.println(" If you're not going to use characters outside the");
  63. System.out.println(" pdfencoding range (almost the same as iso-8889-1)");
  64. System.out.println(" you can add this option.");
  65. System.out.println("-ttcname <fontname>");
  66. System.out.println(" If you're reading data from a TrueType Collection");
  67. System.out.println(" (.ttc file) you must specify which font from the");
  68. System.out.println(" collection you will read metrics from. If you read");
  69. System.out.println(" from a .ttc file without this option, the fontnames");
  70. System.out.println(" will be listed for you.");
  71. System.out.println(" -fn <fontname>");
  72. System.out.println(" default is to use the fontname in the .ttf file, but");
  73. System.out.println(" you can override that name to make sure that the");
  74. System.out.println(" embedded font is used (if you're embedding fonts)");
  75. System.out.println(" instead of installed fonts when viewing documents ");
  76. System.out.println(" with Acrobat Reader.");
  77. }
  78. /**
  79. * The main method for the TTFReader tool.
  80. *
  81. * @param args Command-line arguments: [options] fontfile.ttf xmlfile.xml
  82. * where options can be:
  83. * -fn <fontname>
  84. * default is to use the fontname in the .ttf file, but you can override
  85. * that name to make sure that the embedded font is used instead of installed
  86. * fonts when viewing documents with Acrobat Reader.
  87. * -cn <classname>
  88. * default is to use the fontname
  89. * -ef <path to the truetype fontfile>
  90. * will add the possibility to embed the font. When running fop, fop will look
  91. * for this file to embed it
  92. * -er <path to truetype fontfile relative to org/apache/fop/render/pdf/fonts>
  93. * you can also include the fontfile in the fop.jar file when building fop.
  94. * You can use both -ef and -er. The file specified in -ef will be searched first,
  95. * then the -er file.
  96. * -nocs
  97. * if complex script features are disabled
  98. */
  99. public static void main(String[] args) {
  100. String embFile = null;
  101. String embResource = null;
  102. String className = null;
  103. String fontName = null;
  104. String ttcName = null;
  105. boolean isCid = true;
  106. Map options = new java.util.HashMap();
  107. String[] arguments = parseArguments(options, args);
  108. determineLogLevel(options);
  109. TTFReader app = new TTFReader();
  110. log.info("TTF Reader for Apache FOP " + Version.getVersion() + "\n");
  111. if (options.get("-enc") != null) {
  112. String enc = (String)options.get("-enc");
  113. if ("ansi".equals(enc)) {
  114. isCid = false;
  115. }
  116. }
  117. if (options.get("-ttcname") != null) {
  118. ttcName = (String)options.get("-ttcname");
  119. }
  120. if (options.get("-ef") != null) {
  121. embFile = (String)options.get("-ef");
  122. }
  123. if (options.get("-er") != null) {
  124. embResource = (String)options.get("-er");
  125. }
  126. if (options.get("-fn") != null) {
  127. fontName = (String)options.get("-fn");
  128. }
  129. if (options.get("-cn") != null) {
  130. className = (String)options.get("-cn");
  131. }
  132. boolean useKerning = true;
  133. boolean useAdvanced = true;
  134. if (options.get("-nocs") != null) {
  135. useAdvanced = false;
  136. }
  137. if (arguments.length != 2 || options.get("-h") != null
  138. || options.get("-help") != null || options.get("--help") != null) {
  139. displayUsage();
  140. } else {
  141. try {
  142. log.info("Parsing font...");
  143. TTFFile ttf = app.loadTTF(arguments[0], ttcName, useKerning, useAdvanced);
  144. if (ttf != null) {
  145. org.w3c.dom.Document doc = app.constructFontXML(ttf,
  146. fontName, className, embResource, embFile, isCid,
  147. ttcName);
  148. if (isCid) {
  149. log.info("Creating CID encoded metrics...");
  150. } else {
  151. log.info("Creating WinAnsi encoded metrics...");
  152. }
  153. if (doc != null) {
  154. app.writeFontXML(doc, arguments[1]);
  155. }
  156. if (ttf.isEmbeddable()) {
  157. log.info("This font contains no embedding license restrictions.");
  158. } else {
  159. log.info("** Note: This font contains license retrictions for\n"
  160. + " embedding. This font shouldn't be embedded.");
  161. }
  162. }
  163. log.info("");
  164. log.info("XML font metrics file successfully created.");
  165. } catch (Exception e) {
  166. log.error("Error while building XML font metrics file.", e);
  167. System.exit(-1);
  168. }
  169. }
  170. }
  171. /**
  172. * Read a TTF file and returns it as an object.
  173. *
  174. * @param fileName The filename of the TTF file.
  175. * @param fontName The name of the font
  176. * @param useKerning true if should load kerning data
  177. * @param useAdvanced true if should load advanced typographic table data
  178. * @return The TTF as an object, null if the font is incompatible.
  179. * @throws IOException In case of an I/O problem
  180. */
  181. public TTFFile loadTTF(String fileName, String fontName, boolean useKerning, boolean useAdvanced) throws IOException {
  182. TTFFile ttfFile = new TTFFile(useKerning, useAdvanced);
  183. log.info("Reading " + fileName + "...");
  184. InputStream stream = new FileInputStream(fileName);
  185. try {
  186. FontFileReader reader = new FontFileReader(stream);
  187. String header = OFFontLoader.readHeader(reader);
  188. boolean supported = ttfFile.readFont(reader, header, fontName);
  189. if (!supported) {
  190. return null;
  191. }
  192. } finally {
  193. stream.close();
  194. }
  195. log.info("Font Family: " + ttfFile.getFamilyNames());
  196. if (ttfFile.isCFF()) {
  197. throw new UnsupportedOperationException(
  198. "OpenType fonts with CFF data are not supported, yet");
  199. }
  200. return ttfFile;
  201. }
  202. /**
  203. * Generates the font metrics file from the TTF/TTC file.
  204. *
  205. * @param ttf The PFM file to generate the font metrics from.
  206. * @param fontName Name of the font
  207. * @param className Class name for the font
  208. * @param resource path to the font as embedded resource
  209. * @param file path to the font as file
  210. * @param isCid True if the font is CID encoded
  211. * @param ttcName Name of the TrueType Collection
  212. * @return The DOM document representing the font metrics file.
  213. */
  214. public org.w3c.dom.Document constructFontXML(TTFFile ttf,
  215. String fontName, String className, String resource, String file,
  216. boolean isCid, String ttcName) {
  217. log.info("Creating xml font file...");
  218. Document doc;
  219. try {
  220. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  221. doc = factory.newDocumentBuilder().newDocument();
  222. } catch (javax.xml.parsers.ParserConfigurationException e) {
  223. log.error("Can't create DOM implementation", e);
  224. return null;
  225. }
  226. Element root = doc.createElement("font-metrics");
  227. doc.appendChild(root);
  228. root.setAttribute(METRICS_VERSION_ATTR, String.valueOf(METRICS_VERSION));
  229. if (isCid) {
  230. root.setAttribute("type", "TYPE0");
  231. } else {
  232. root.setAttribute("type", "TRUETYPE");
  233. }
  234. Element el = doc.createElement("font-name");
  235. root.appendChild(el);
  236. // Note that the PostScript name usually is something like
  237. // "Perpetua-Bold", but the TrueType spec says that in the ttf file
  238. // it should be "Perpetua,Bold".
  239. String s = FontUtil.stripWhiteSpace(ttf.getPostScriptName());
  240. if (fontName != null) {
  241. el.appendChild(doc.createTextNode(FontUtil.stripWhiteSpace(fontName)));
  242. } else {
  243. el.appendChild(doc.createTextNode(s));
  244. }
  245. if (ttf.getFullName() != null) {
  246. el = doc.createElement("full-name");
  247. root.appendChild(el);
  248. el.appendChild(doc.createTextNode(ttf.getFullName()));
  249. }
  250. Set<String> familyNames = ttf.getFamilyNames();
  251. if (familyNames.size() > 0) {
  252. String familyName = familyNames.iterator().next();
  253. el = doc.createElement("family-name");
  254. root.appendChild(el);
  255. el.appendChild(doc.createTextNode(familyName));
  256. }
  257. el = doc.createElement("embed");
  258. root.appendChild(el);
  259. if (file != null && ttf.isEmbeddable()) {
  260. el.setAttribute("file", file);
  261. }
  262. if (resource != null && ttf.isEmbeddable()) {
  263. el.setAttribute("class", resource);
  264. }
  265. el = doc.createElement("cap-height");
  266. root.appendChild(el);
  267. el.appendChild(doc.createTextNode(String.valueOf(ttf.getCapHeight())));
  268. el = doc.createElement("x-height");
  269. root.appendChild(el);
  270. el.appendChild(doc.createTextNode(String.valueOf(ttf.getXHeight())));
  271. el = doc.createElement("ascender");
  272. root.appendChild(el);
  273. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseAscent())));
  274. el = doc.createElement("descender");
  275. root.appendChild(el);
  276. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseDescent())));
  277. Element bbox = doc.createElement("bbox");
  278. root.appendChild(bbox);
  279. int[] bb = ttf.getFontBBox();
  280. final String[] names = {"left", "bottom", "right", "top"};
  281. for (int i = 0; i < names.length; i++) {
  282. el = doc.createElement(names[i]);
  283. bbox.appendChild(el);
  284. el.appendChild(doc.createTextNode(String.valueOf(bb[i])));
  285. }
  286. el = doc.createElement("flags");
  287. root.appendChild(el);
  288. el.appendChild(doc.createTextNode(String.valueOf(ttf.getFlags())));
  289. el = doc.createElement("stemv");
  290. root.appendChild(el);
  291. el.appendChild(doc.createTextNode(ttf.getStemV()));
  292. el = doc.createElement("italicangle");
  293. root.appendChild(el);
  294. el.appendChild(doc.createTextNode(ttf.getItalicAngle()));
  295. if (ttcName != null) {
  296. el = doc.createElement("ttc-name");
  297. root.appendChild(el);
  298. el.appendChild(doc.createTextNode(ttcName));
  299. }
  300. el = doc.createElement("subtype");
  301. root.appendChild(el);
  302. // Fill in extras for CID keyed fonts
  303. if (isCid) {
  304. el.appendChild(doc.createTextNode("TYPE0"));
  305. generateDOM4MultiByteExtras(root, ttf, isCid);
  306. } else {
  307. // Fill in extras for singlebyte fonts
  308. el.appendChild(doc.createTextNode("TRUETYPE"));
  309. generateDOM4SingleByteExtras(root, ttf, isCid);
  310. }
  311. generateDOM4Kerning(root, ttf, isCid);
  312. return doc;
  313. }
  314. private void generateDOM4MultiByteExtras(Element parent, TTFFile ttf, boolean isCid) {
  315. Element el;
  316. Document doc = parent.getOwnerDocument();
  317. Element mel = doc.createElement("multibyte-extras");
  318. parent.appendChild(mel);
  319. el = doc.createElement("cid-type");
  320. mel.appendChild(el);
  321. el.appendChild(doc.createTextNode("CIDFontType2"));
  322. el = doc.createElement("default-width");
  323. mel.appendChild(el);
  324. el.appendChild(doc.createTextNode("0"));
  325. el = doc.createElement("bfranges");
  326. mel.appendChild(el);
  327. for (CMapSegment ce : ttf.getCMaps()) {
  328. Element el2 = doc.createElement("bf");
  329. el.appendChild(el2);
  330. el2.setAttribute("us", String.valueOf(ce.getUnicodeStart()));
  331. el2.setAttribute("ue", String.valueOf(ce.getUnicodeEnd()));
  332. el2.setAttribute("gi", String.valueOf(ce.getGlyphStartIndex()));
  333. }
  334. el = doc.createElement("cid-widths");
  335. el.setAttribute("start-index", "0");
  336. mel.appendChild(el);
  337. int[] wx = ttf.getWidths();
  338. for (int i = 0; i < wx.length; i++) {
  339. Element wxel = doc.createElement("wx");
  340. wxel.setAttribute("w", String.valueOf(wx[i]));
  341. int[] bbox = ttf.getBBox(i);
  342. wxel.setAttribute("xMin", String.valueOf(bbox[0]));
  343. wxel.setAttribute("yMin", String.valueOf(bbox[1]));
  344. wxel.setAttribute("xMax", String.valueOf(bbox[2]));
  345. wxel.setAttribute("yMax", String.valueOf(bbox[3]));
  346. el.appendChild(wxel);
  347. }
  348. }
  349. private void generateDOM4SingleByteExtras(Element parent, TTFFile ttf, boolean isCid) {
  350. Element el;
  351. Document doc = parent.getOwnerDocument();
  352. Element sel = doc.createElement("singlebyte-extras");
  353. parent.appendChild(sel);
  354. el = doc.createElement("encoding");
  355. sel.appendChild(el);
  356. el.appendChild(doc.createTextNode(ttf.getCharSetName()));
  357. el = doc.createElement("first-char");
  358. sel.appendChild(el);
  359. el.appendChild(doc.createTextNode(String.valueOf(ttf.getFirstChar())));
  360. el = doc.createElement("last-char");
  361. sel.appendChild(el);
  362. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLastChar())));
  363. Element widths = doc.createElement("widths");
  364. sel.appendChild(widths);
  365. for (short i = ttf.getFirstChar(); i <= ttf.getLastChar(); i++) {
  366. el = doc.createElement("char");
  367. widths.appendChild(el);
  368. el.setAttribute("idx", String.valueOf(i));
  369. el.setAttribute("wdt", String.valueOf(ttf.getCharWidth(i)));
  370. }
  371. }
  372. private void generateDOM4Kerning(Element parent, TTFFile ttf, boolean isCid) {
  373. Element el;
  374. Document doc = parent.getOwnerDocument();
  375. // Get kerning
  376. Set<Integer> kerningKeys;
  377. if (isCid) {
  378. kerningKeys = ttf.getKerning().keySet();
  379. } else {
  380. kerningKeys = ttf.getAnsiKerning().keySet();
  381. }
  382. for (Integer kpx1 : kerningKeys) {
  383. el = doc.createElement("kerning");
  384. el.setAttribute("kpx1", kpx1.toString());
  385. parent.appendChild(el);
  386. Element el2 = null;
  387. Map<Integer, Integer> h2;
  388. if (isCid) {
  389. h2 = ttf.getKerning().get(kpx1);
  390. } else {
  391. h2 = ttf.getAnsiKerning().get(kpx1);
  392. }
  393. for (Integer kpx2 : h2.keySet()) {
  394. if (isCid || kpx2.intValue() < 256) {
  395. el2 = doc.createElement("pair");
  396. el2.setAttribute("kpx2", kpx2.toString());
  397. Integer val = h2.get(kpx2);
  398. el2.setAttribute("kern", val.toString());
  399. el.appendChild(el2);
  400. }
  401. }
  402. }
  403. }
  404. /**
  405. * Bugzilla 40739, check that attr has a metrics-version attribute
  406. * compatible with ours.
  407. * @param attr attributes read from the root element of a metrics XML file
  408. * @throws SAXException if incompatible
  409. */
  410. public static void checkMetricsVersion(Attributes attr) throws SAXException {
  411. String err = null;
  412. final String str = attr.getValue(METRICS_VERSION_ATTR);
  413. if (str == null) {
  414. err = "Missing " + METRICS_VERSION_ATTR + " attribute";
  415. } else {
  416. int version = 0;
  417. try {
  418. version = Integer.parseInt(str);
  419. if (version < METRICS_VERSION) {
  420. err = "Incompatible " + METRICS_VERSION_ATTR
  421. + " value (" + version + ", should be " + METRICS_VERSION
  422. + ")";
  423. }
  424. } catch (NumberFormatException e) {
  425. err = "Invalid " + METRICS_VERSION_ATTR
  426. + " attribute value (" + str + ")";
  427. }
  428. }
  429. if (err != null) {
  430. throw new SAXException(
  431. err
  432. + " - please regenerate the font metrics file with "
  433. + "a more recent version of FOP."
  434. );
  435. }
  436. }
  437. }