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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.Iterator;
  21. import java.util.Map;
  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.FontUtil;
  26. import org.apache.fop.fonts.truetype.FontFileReader;
  27. import org.apache.fop.fonts.truetype.TTFCmapEntry;
  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.getFamilyName());
  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. el = doc.createElement("embed");
  235. root.appendChild(el);
  236. if (file != null && ttf.isEmbeddable()) {
  237. el.setAttribute("file", file);
  238. }
  239. if (resource != null && ttf.isEmbeddable()) {
  240. el.setAttribute("class", resource);
  241. }
  242. el = doc.createElement("cap-height");
  243. root.appendChild(el);
  244. el.appendChild(doc.createTextNode(String.valueOf(ttf.getCapHeight())));
  245. el = doc.createElement("x-height");
  246. root.appendChild(el);
  247. el.appendChild(doc.createTextNode(String.valueOf(ttf.getXHeight())));
  248. el = doc.createElement("ascender");
  249. root.appendChild(el);
  250. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseAscent())));
  251. el = doc.createElement("descender");
  252. root.appendChild(el);
  253. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLowerCaseDescent())));
  254. Element bbox = doc.createElement("bbox");
  255. root.appendChild(bbox);
  256. int[] bb = ttf.getFontBBox();
  257. final String[] names = {"left", "bottom", "right", "top"};
  258. for (int i = 0; i < names.length; i++) {
  259. el = doc.createElement(names[i]);
  260. bbox.appendChild(el);
  261. el.appendChild(doc.createTextNode(String.valueOf(bb[i])));
  262. }
  263. el = doc.createElement("flags");
  264. root.appendChild(el);
  265. el.appendChild(doc.createTextNode(String.valueOf(ttf.getFlags())));
  266. el = doc.createElement("stemv");
  267. root.appendChild(el);
  268. el.appendChild(doc.createTextNode(ttf.getStemV()));
  269. el = doc.createElement("italicangle");
  270. root.appendChild(el);
  271. el.appendChild(doc.createTextNode(ttf.getItalicAngle()));
  272. if (ttcName != null) {
  273. el = doc.createElement("ttc-name");
  274. root.appendChild(el);
  275. el.appendChild(doc.createTextNode(ttcName));
  276. }
  277. el = doc.createElement("subtype");
  278. root.appendChild(el);
  279. // Fill in extras for CID keyed fonts
  280. if (isCid) {
  281. el.appendChild(doc.createTextNode("TYPE0"));
  282. generateDOM4MultiByteExtras(root, ttf, isCid);
  283. } else {
  284. // Fill in extras for singlebyte fonts
  285. el.appendChild(doc.createTextNode("TRUETYPE"));
  286. generateDOM4SingleByteExtras(root, ttf, isCid);
  287. }
  288. generateDOM4Kerning(root, ttf, isCid);
  289. return doc;
  290. }
  291. private void generateDOM4MultiByteExtras(Element parent, TTFFile ttf, boolean isCid) {
  292. Element el;
  293. Document doc = parent.getOwnerDocument();
  294. Element mel = doc.createElement("multibyte-extras");
  295. parent.appendChild(mel);
  296. el = doc.createElement("cid-type");
  297. mel.appendChild(el);
  298. el.appendChild(doc.createTextNode("CIDFontType2"));
  299. el = doc.createElement("default-width");
  300. mel.appendChild(el);
  301. el.appendChild(doc.createTextNode("0"));
  302. el = doc.createElement("bfranges");
  303. mel.appendChild(el);
  304. Iterator iter = ttf.getCMaps().listIterator();
  305. while (iter.hasNext()) {
  306. TTFCmapEntry ce = (TTFCmapEntry)iter.next();
  307. Element el2 = doc.createElement("bf");
  308. el.appendChild(el2);
  309. el2.setAttribute("us", String.valueOf(ce.getUnicodeStart()));
  310. el2.setAttribute("ue", String.valueOf(ce.getUnicodeEnd()));
  311. el2.setAttribute("gi", String.valueOf(ce.getGlyphStartIndex()));
  312. }
  313. el = doc.createElement("cid-widths");
  314. el.setAttribute("start-index", "0");
  315. mel.appendChild(el);
  316. int[] wx = ttf.getWidths();
  317. for (int i = 0; i < wx.length; i++) {
  318. Element wxel = doc.createElement("wx");
  319. wxel.setAttribute("w", String.valueOf(wx[i]));
  320. el.appendChild(wxel);
  321. }
  322. }
  323. private void generateDOM4SingleByteExtras(Element parent, TTFFile ttf, boolean isCid) {
  324. Element el;
  325. Document doc = parent.getOwnerDocument();
  326. Element sel = doc.createElement("singlebyte-extras");
  327. parent.appendChild(sel);
  328. el = doc.createElement("encoding");
  329. sel.appendChild(el);
  330. el.appendChild(doc.createTextNode(ttf.getCharSetName()));
  331. el = doc.createElement("first-char");
  332. sel.appendChild(el);
  333. el.appendChild(doc.createTextNode(String.valueOf(ttf.getFirstChar())));
  334. el = doc.createElement("last-char");
  335. sel.appendChild(el);
  336. el.appendChild(doc.createTextNode(String.valueOf(ttf.getLastChar())));
  337. Element widths = doc.createElement("widths");
  338. sel.appendChild(widths);
  339. for (short i = ttf.getFirstChar(); i <= ttf.getLastChar(); i++) {
  340. el = doc.createElement("char");
  341. widths.appendChild(el);
  342. el.setAttribute("idx", String.valueOf(i));
  343. el.setAttribute("wdt", String.valueOf(ttf.getCharWidth(i)));
  344. }
  345. }
  346. private void generateDOM4Kerning(Element parent, TTFFile ttf, boolean isCid) {
  347. Element el;
  348. Document doc = parent.getOwnerDocument();
  349. // Get kerning
  350. Iterator iter;
  351. if (isCid) {
  352. iter = ttf.getKerning().keySet().iterator();
  353. } else {
  354. iter = ttf.getAnsiKerning().keySet().iterator();
  355. }
  356. while (iter.hasNext()) {
  357. Integer kpx1 = (Integer)iter.next();
  358. el = doc.createElement("kerning");
  359. el.setAttribute("kpx1", kpx1.toString());
  360. parent.appendChild(el);
  361. Element el2 = null;
  362. Map h2;
  363. if (isCid) {
  364. h2 = (Map)ttf.getKerning().get(kpx1);
  365. } else {
  366. h2 = (Map)ttf.getAnsiKerning().get(kpx1);
  367. }
  368. Iterator iter2 = h2.keySet().iterator();
  369. while (iter2.hasNext()) {
  370. Integer kpx2 = (Integer)iter2.next();
  371. if (isCid || kpx2.intValue() < 256) {
  372. el2 = doc.createElement("pair");
  373. el2.setAttribute("kpx2", kpx2.toString());
  374. Integer val = (Integer)h2.get(kpx2);
  375. el2.setAttribute("kern", val.toString());
  376. el.appendChild(el2);
  377. }
  378. }
  379. }
  380. }
  381. /**
  382. * Bugzilla 40739, check that attr has a metrics-version attribute
  383. * compatible with ours.
  384. * @param attr attributes read from the root element of a metrics XML file
  385. * @throws SAXException if incompatible
  386. */
  387. public static void checkMetricsVersion(Attributes attr) throws SAXException {
  388. String err = null;
  389. final String str = attr.getValue(METRICS_VERSION_ATTR);
  390. if (str == null) {
  391. err = "Missing " + METRICS_VERSION_ATTR + " attribute";
  392. } else {
  393. int version = 0;
  394. try {
  395. version = Integer.parseInt(str);
  396. if (version < METRICS_VERSION) {
  397. err = "Incompatible " + METRICS_VERSION_ATTR
  398. + " value (" + version + ", should be " + METRICS_VERSION
  399. + ")"
  400. ;
  401. }
  402. } catch (NumberFormatException e) {
  403. err = "Invalid " + METRICS_VERSION_ATTR
  404. + " attribute value (" + str + ")";
  405. }
  406. }
  407. if (err != null) {
  408. throw new SAXException(
  409. err
  410. + " - please regenerate the font metrics file with "
  411. + "a more recent version of FOP."
  412. );
  413. }
  414. }
  415. }