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 18KB

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