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.

FontReader.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*
  2. * $Id$
  3. * ============================================================================
  4. * The Apache Software License, Version 1.1
  5. * ============================================================================
  6. *
  7. * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without modifica-
  10. * tion, are permitted provided that the following conditions are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright notice,
  13. * this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if any, must
  20. * include the following acknowledgment: "This product includes software
  21. * developed by the Apache Software Foundation (http://www.apache.org/)."
  22. * Alternately, this acknowledgment may appear in the software itself, if
  23. * and wherever such third-party acknowledgments normally appear.
  24. *
  25. * 4. The names "FOP" and "Apache Software Foundation" must not be used to
  26. * endorse or promote products derived from this software without prior
  27. * written permission. For written permission, please contact
  28. * apache@apache.org.
  29. *
  30. * 5. Products derived from this software may not be called "Apache", nor may
  31. * "Apache" appear in their name, without prior written permission of the
  32. * Apache Software Foundation.
  33. *
  34. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  36. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  37. * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  38. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  39. * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  40. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  41. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  42. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  43. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. * ============================================================================
  45. *
  46. * This software consists of voluntary contributions made by many individuals
  47. * on behalf of the Apache Software Foundation and was originally created by
  48. * James Tauber <jtauber@jtauber.com>. For more information on the Apache
  49. * Software Foundation, please see <http://www.apache.org/>.
  50. */
  51. package org.apache.fop.render.pdf;
  52. //Java
  53. import java.util.List;
  54. import java.util.Map;
  55. import java.io.IOException;
  56. //SAX
  57. import org.xml.sax.XMLReader;
  58. import org.xml.sax.SAXException;
  59. import org.xml.sax.Locator;
  60. import org.xml.sax.Attributes;
  61. import org.xml.sax.helpers.DefaultHandler;
  62. //FOP
  63. import org.apache.fop.apps.FOPException;
  64. import org.apache.fop.fonts.BFEntry;
  65. import org.apache.fop.fonts.CIDFontType;
  66. import org.apache.fop.fonts.CustomFont;
  67. import org.apache.fop.fonts.Font;
  68. import org.apache.fop.fonts.FontType;
  69. import org.apache.fop.fonts.MultiByteFont;
  70. import org.apache.fop.fonts.SingleByteFont;
  71. /**
  72. * Class for reading a metric.xml file and creating a font object.
  73. * Typical usage:
  74. * <pre>
  75. * FontReader reader = new FontReader(<path til metrics.xml>);
  76. * reader.setFontEmbedPath(<path to a .ttf or .pfb file or null to diable embedding>);
  77. * reader.useKerning(true);
  78. * Font f = reader.getFont();
  79. * </pre>
  80. */
  81. public class FontReader extends DefaultHandler {
  82. private Locator locator = null;
  83. private boolean isCID = false;
  84. private CustomFont returnFont = null;
  85. private MultiByteFont multiFont = null;
  86. private SingleByteFont singleFont = null;
  87. private StringBuffer text = new StringBuffer();
  88. private List cidWidths = null;
  89. private int cidWidthIndex = 0;
  90. private Map currentKerning = null;
  91. private List bfranges = null;
  92. private void createFont(String path) throws FOPException {
  93. XMLReader parser = null;
  94. try {
  95. parser = javax.xml.parsers.SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  96. } catch (Exception e) {
  97. throw new FOPException(e);
  98. }
  99. if (parser == null) {
  100. throw new FOPException("Unable to create SAX parser");
  101. }
  102. try {
  103. parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
  104. false);
  105. } catch (SAXException e) {
  106. throw new FOPException("You need a SAX parser which supports SAX version 2",
  107. e);
  108. }
  109. parser.setContentHandler(this);
  110. try {
  111. parser.parse(path);
  112. } catch (SAXException e) {
  113. throw new FOPException(e);
  114. } catch (IOException e) {
  115. throw new FOPException(e);
  116. }
  117. }
  118. /**
  119. * Sets the path to embed a font. A null value disables font embedding.
  120. * @param path URI for the embeddable file
  121. */
  122. public void setFontEmbedPath(String path) {
  123. returnFont.setEmbedFileName(path);
  124. }
  125. /**
  126. * Enable/disable use of kerning for the font
  127. * @param enabled true to enable kerning, false to disable
  128. */
  129. public void setKerningEnabled(boolean enabled) {
  130. returnFont.setKerningEnabled(enabled);
  131. }
  132. /**
  133. * Get the generated font object
  134. * @return the font
  135. */
  136. public Font getFont() {
  137. return returnFont;
  138. }
  139. /**
  140. * Construct a FontReader object from a path to a metric.xml file
  141. * and read metric data
  142. * @param path URI to the font metric file
  143. * @throws FOPException if loading the font fails
  144. */
  145. public FontReader(String path) throws FOPException {
  146. createFont(path);
  147. }
  148. /**
  149. * @see org.xml.sax.ContentHandler#startDocument()
  150. */
  151. public void startDocument() {
  152. }
  153. /**
  154. * @see org.xml.sax.ContentHandler#setDocumentLocator(Locator)
  155. */
  156. public void setDocumentLocator(Locator locator) {
  157. this.locator = locator;
  158. }
  159. /**
  160. * @see org.xml.sax.ContentHandler#startElement(String, String, String, Attributes)
  161. */
  162. public void startElement(String uri, String localName, String qName,
  163. Attributes attributes) {
  164. if (localName.equals("font-metrics")) {
  165. if ("TYPE0".equals(attributes.getValue("type"))) {
  166. multiFont = new MultiByteFont();
  167. returnFont = multiFont;
  168. isCID = true;
  169. } else if ("TRUETYPE".equals(attributes.getValue("type"))) {
  170. singleFont = new SingleByteFont();
  171. singleFont.setFontType(FontType.TRUETYPE);
  172. returnFont = singleFont;
  173. isCID = false;
  174. } else {
  175. singleFont = new SingleByteFont();
  176. singleFont.setFontType(FontType.TYPE1);
  177. returnFont = singleFont;
  178. isCID = false;
  179. }
  180. } else if ("embed".equals(localName)) {
  181. returnFont.setEmbedFileName(attributes.getValue("file"));
  182. returnFont.setEmbedResourceName(attributes.getValue("class"));
  183. } else if ("cid-widths".equals(localName)) {
  184. cidWidthIndex = getInt(attributes.getValue("start-index"));
  185. cidWidths = new java.util.ArrayList();
  186. } else if ("kerning".equals(localName)) {
  187. currentKerning = new java.util.HashMap();
  188. returnFont.putKerningEntry(new Integer(attributes.getValue("kpx1")),
  189. currentKerning);
  190. } else if ("bfranges".equals(localName)) {
  191. bfranges = new java.util.ArrayList();
  192. } else if ("bf".equals(localName)) {
  193. BFEntry entry = new BFEntry(getInt(attributes.getValue("us")),
  194. getInt(attributes.getValue("ue")),
  195. getInt(attributes.getValue("gi")));
  196. bfranges.add(entry);
  197. } else if ("wx".equals(localName)) {
  198. cidWidths.add(new Integer(attributes.getValue("w")));
  199. } else if ("widths".equals(localName)) {
  200. //singleFont.width = new int[256];
  201. } else if ("char".equals(localName)) {
  202. try {
  203. singleFont.setWidth(Integer.parseInt(attributes.getValue("idx")),
  204. Integer.parseInt(attributes.getValue("wdt")));
  205. } catch (NumberFormatException ne) {
  206. System.out.println("Malformed width in metric file: "
  207. + ne.getMessage());
  208. }
  209. } else if ("pair".equals(localName)) {
  210. currentKerning.put(new Integer(attributes.getValue("kpx2")),
  211. new Integer(attributes.getValue("kern")));
  212. }
  213. }
  214. private int getInt(String str) {
  215. int ret = 0;
  216. try {
  217. ret = Integer.parseInt(str);
  218. } catch (Exception e) {
  219. /**@todo log this exception */
  220. }
  221. return ret;
  222. }
  223. /**
  224. * @see org.xml.sax.ContentHandler#endElement(String, String, String)
  225. */
  226. public void endElement(String uri, String localName, String qName) {
  227. if ("font-name".equals(localName)) {
  228. returnFont.setFontName(text.toString());
  229. } else if ("ttc-name".equals(localName) && isCID) {
  230. multiFont.setTTCName(text.toString());
  231. } else if ("cap-height".equals(localName)) {
  232. returnFont.setCapHeight(getInt(text.toString()));
  233. } else if ("x-height".equals(localName)) {
  234. returnFont.setXHeight(getInt(text.toString()));
  235. } else if ("ascender".equals(localName)) {
  236. returnFont.setAscender(getInt(text.toString()));
  237. } else if ("descender".equals(localName)) {
  238. returnFont.setDescender(getInt(text.toString()));
  239. } else if ("left".equals(localName)) {
  240. int[] bbox = returnFont.getFontBBox();
  241. bbox[0] = getInt(text.toString());
  242. returnFont.setFontBBox(bbox);
  243. } else if ("bottom".equals(localName)) {
  244. int[] bbox = returnFont.getFontBBox();
  245. bbox[1] = getInt(text.toString());
  246. returnFont.setFontBBox(bbox);
  247. } else if ("right".equals(localName)) {
  248. int[] bbox = returnFont.getFontBBox();
  249. bbox[2] = getInt(text.toString());
  250. returnFont.setFontBBox(bbox);
  251. } else if ("top".equals(localName)) {
  252. int[] bbox = returnFont.getFontBBox();
  253. bbox[3] = getInt(text.toString());
  254. returnFont.setFontBBox(bbox);
  255. } else if ("first-char".equals(localName)) {
  256. returnFont.setFirstChar(getInt(text.toString()));
  257. } else if ("last-char".equals(localName)) {
  258. returnFont.setLastChar(getInt(text.toString()));
  259. } else if ("flags".equals(localName)) {
  260. returnFont.setFlags(getInt(text.toString()));
  261. } else if ("stemv".equals(localName)) {
  262. returnFont.setStemV(getInt(text.toString()));
  263. } else if ("italic-angle".equals(localName)) {
  264. returnFont.setItalicAngle(getInt(text.toString()));
  265. } else if ("missing-width".equals(localName)) {
  266. returnFont.setMissingWidth(getInt(text.toString()));
  267. } else if ("cid-type".equals(localName)) {
  268. multiFont.setCIDType(CIDFontType.byName(text.toString()));
  269. } else if ("default-width".equals(localName)) {
  270. multiFont.setDefaultWidth(getInt(text.toString()));
  271. } else if ("cid-widths".equals(localName)) {
  272. int[] wds = new int[cidWidths.size()];
  273. int j = 0;
  274. for (int count = 0; count < cidWidths.size(); count++) {
  275. Integer i = (Integer)cidWidths.get(count);
  276. wds[j++] = i.intValue();
  277. }
  278. multiFont.addCIDWidthEntry(cidWidthIndex, wds);
  279. multiFont.setWidthArray(wds);
  280. } else if ("bfranges".equals(localName)) {
  281. multiFont.setBFEntries((BFEntry[])bfranges.toArray(new BFEntry[0]));
  282. }
  283. text.setLength(0); //Reset text buffer (see characters())
  284. }
  285. /**
  286. * @see org.xml.sax.ContentHandler#characters(char[], int, int)
  287. */
  288. public void characters(char[] ch, int start, int length) {
  289. text.append(ch, start, length);
  290. }
  291. }