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

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