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.

Type1FontLoader.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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.type1;
  19. import java.awt.geom.RectangularShape;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Set;
  25. import org.apache.commons.io.IOUtils;
  26. import org.apache.fop.fonts.CodePointMapping;
  27. import org.apache.fop.fonts.FontLoader;
  28. import org.apache.fop.fonts.FontResolver;
  29. import org.apache.fop.fonts.FontType;
  30. import org.apache.fop.fonts.SingleByteFont;
  31. /**
  32. * Loads a Type 1 font into memory directly from the original font file.
  33. */
  34. public class Type1FontLoader extends FontLoader {
  35. private SingleByteFont singleFont;
  36. /**
  37. * Constructs a new Type 1 font loader.
  38. * @param fontFileURI the URI to the PFB file of a Type 1 font
  39. * @param embedded indicates whether the font is embedded or referenced
  40. * @param useKerning indicates whether to load kerning information if available
  41. * @param resolver the font resolver used to resolve URIs
  42. * @throws IOException In case of an I/O error
  43. */
  44. public Type1FontLoader(String fontFileURI, boolean embedded, boolean useKerning,
  45. FontResolver resolver) throws IOException {
  46. super(fontFileURI, embedded, useKerning, resolver);
  47. }
  48. private String getPFMURI(String pfbURI) {
  49. String pfbExt = pfbURI.substring(pfbURI.length() - 3, pfbURI.length());
  50. String pfmExt = pfbExt.substring(0, 2)
  51. + (Character.isUpperCase(pfbExt.charAt(2)) ? "M" : "m");
  52. return pfbURI.substring(0, pfbURI.length() - 4) + "." + pfmExt;
  53. }
  54. private static final String[] AFM_EXTENSIONS = new String[] {".AFM", ".afm", ".Afm"};
  55. /** {@inheritDoc} */
  56. protected void read() throws IOException {
  57. AFMFile afm = null;
  58. PFMFile pfm = null;
  59. InputStream afmIn = null;
  60. for (int i = 0; i < AFM_EXTENSIONS.length; i++) {
  61. try {
  62. String afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4)
  63. + AFM_EXTENSIONS[i];
  64. afmIn = openFontUri(resolver, afmUri);
  65. if (afmIn != null) {
  66. break;
  67. }
  68. } catch (IOException ioe) {
  69. //Ignore, AFM probably not available under the URI
  70. }
  71. }
  72. if (afmIn != null) {
  73. try {
  74. AFMParser afmParser = new AFMParser();
  75. afm = afmParser.parse(afmIn);
  76. } finally {
  77. IOUtils.closeQuietly(afmIn);
  78. }
  79. }
  80. String pfmUri = getPFMURI(this.fontFileURI);
  81. InputStream pfmIn = null;
  82. try {
  83. pfmIn = openFontUri(resolver, pfmUri);
  84. } catch (IOException ioe) {
  85. //Ignore, PFM probably not available under the URI
  86. }
  87. if (pfmIn != null) {
  88. try {
  89. pfm = new PFMFile();
  90. pfm.load(pfmIn);
  91. } catch (IOException ioe) {
  92. if (afm == null) {
  93. //Ignore the exception if we have a valid PFM. PFM is only the fallback.
  94. throw ioe;
  95. }
  96. } finally {
  97. IOUtils.closeQuietly(pfmIn);
  98. }
  99. }
  100. if (afm == null && pfm == null) {
  101. throw new java.io.FileNotFoundException(
  102. "Neither an AFM nor a PFM file was found for " + this.fontFileURI);
  103. }
  104. buildFont(afm, pfm);
  105. this.loaded = true;
  106. }
  107. private void buildFont(AFMFile afm, PFMFile pfm) {
  108. if (afm == null && pfm == null) {
  109. throw new IllegalArgumentException("Need at least an AFM or a PFM!");
  110. }
  111. singleFont = new SingleByteFont();
  112. singleFont.setFontType(FontType.TYPE1);
  113. singleFont.setResolver(this.resolver);
  114. if (this.embedded) {
  115. singleFont.setEmbedFileName(this.fontFileURI);
  116. }
  117. returnFont = singleFont;
  118. handleEncoding(afm, pfm);
  119. handleFontName(afm, pfm);
  120. handleMetrics(afm, pfm);
  121. }
  122. private void handleEncoding(AFMFile afm, PFMFile pfm) {
  123. //Encoding
  124. if (afm != null) {
  125. String encoding = afm.getEncodingScheme();
  126. singleFont.setUseNativeEncoding(true);
  127. if ("AdobeStandardEncoding".equals(encoding)) {
  128. singleFont.setEncoding(CodePointMapping.STANDARD_ENCODING);
  129. } else {
  130. String effEncodingName;
  131. if ("FontSpecific".equals(encoding)) {
  132. effEncodingName = afm.getFontName() + "Encoding";
  133. } else {
  134. effEncodingName = encoding;
  135. }
  136. if (log.isDebugEnabled()) {
  137. log.debug("Unusual font encoding encountered: "
  138. + encoding + " -> " + effEncodingName);
  139. }
  140. CodePointMapping mapping = buildCustomEncoding(effEncodingName, afm);
  141. singleFont.setEncoding(mapping);
  142. }
  143. List charMetrics = afm.getCharMetrics();
  144. for (int i = 0, c = afm.getCharCount(); i < c; i++) {
  145. AFMCharMetrics metrics = (AFMCharMetrics)charMetrics.get(i);
  146. if (!metrics.hasCharCode() && metrics.getCharacter() != null) {
  147. singleFont.addUnencodedCharacter(metrics.getCharacter(),
  148. (int)Math.round(metrics.getWidthX()));
  149. }
  150. }
  151. } else {
  152. if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) {
  153. singleFont.setEncoding(pfm.getCharSetName() + "Encoding");
  154. } else {
  155. log.warn("The PFM reports an unsupported encoding ("
  156. + pfm.getCharSetName() + "). The font may not work as expected.");
  157. singleFont.setEncoding("WinAnsiEncoding"); //Try fallback, no guarantees!
  158. }
  159. }
  160. }
  161. private void handleFontName(AFMFile afm, PFMFile pfm) {
  162. //Font name
  163. if (afm != null) {
  164. returnFont.setFontName(afm.getFontName()); //PostScript font name
  165. returnFont.setFullName(afm.getFullName());
  166. Set names = new java.util.HashSet();
  167. names.add(afm.getFamilyName());
  168. returnFont.setFamilyNames(names);
  169. } else {
  170. returnFont.setFontName(pfm.getPostscriptName());
  171. String fullName = pfm.getPostscriptName();
  172. fullName = fullName.replace('-', ' '); //Hack! Try to emulate full name
  173. returnFont.setFullName(fullName); //emulate afm.getFullName()
  174. Set names = new java.util.HashSet();
  175. names.add(pfm.getWindowsName()); //emulate afm.getFamilyName()
  176. returnFont.setFamilyNames(names);
  177. }
  178. }
  179. private void handleMetrics(AFMFile afm, PFMFile pfm) {
  180. //Basic metrics
  181. if (afm != null) {
  182. if (afm.getCapHeight() != null) {
  183. returnFont.setCapHeight(afm.getCapHeight().intValue());
  184. }
  185. if (afm.getXHeight() != null) {
  186. returnFont.setXHeight(afm.getXHeight().intValue());
  187. }
  188. if (afm.getAscender() != null) {
  189. returnFont.setAscender(afm.getAscender().intValue());
  190. }
  191. if (afm.getDescender() != null) {
  192. returnFont.setDescender(afm.getDescender().intValue());
  193. }
  194. returnFont.setFontBBox(afm.getFontBBoxAsIntArray());
  195. if (afm.getStdVW() != null) {
  196. returnFont.setStemV(afm.getStdVW().intValue());
  197. } else {
  198. returnFont.setStemV(80); //Arbitrary value
  199. }
  200. returnFont.setItalicAngle((int)afm.getWritingDirectionMetrics(0).getItalicAngle());
  201. } else {
  202. returnFont.setFontBBox(pfm.getFontBBox());
  203. returnFont.setStemV(pfm.getStemV());
  204. returnFont.setItalicAngle(pfm.getItalicAngle());
  205. }
  206. if (pfm != null) {
  207. //Sometimes the PFM has these metrics while the AFM doesn't (ex. Symbol)
  208. if (returnFont.getCapHeight() == 0) {
  209. returnFont.setCapHeight(pfm.getCapHeight());
  210. }
  211. if (returnFont.getXHeight(1) == 0) {
  212. returnFont.setXHeight(pfm.getXHeight());
  213. }
  214. if (returnFont.getAscender() == 0) {
  215. returnFont.setAscender(pfm.getLowerCaseAscent());
  216. }
  217. if (returnFont.getDescender() == 0) {
  218. returnFont.setDescender(pfm.getLowerCaseDescent());
  219. }
  220. }
  221. //Fallbacks when some crucial font metrics aren't available
  222. //(the following are all optional in AFM, but FontBBox is always available)
  223. if (returnFont.getXHeight(1) == 0) {
  224. int xHeight = 0;
  225. if (afm != null) {
  226. AFMCharMetrics chm = afm.getChar("x");
  227. if (chm != null) {
  228. RectangularShape rect = chm.getBBox();
  229. if (rect != null) {
  230. xHeight = (int)Math.round(rect.getMinX());
  231. }
  232. }
  233. }
  234. if (xHeight == 0) {
  235. xHeight = Math.round(returnFont.getFontBBox()[3] * 0.6f);
  236. }
  237. returnFont.setXHeight(xHeight);
  238. }
  239. if (returnFont.getAscender() == 0) {
  240. int asc = 0;
  241. if (afm != null) {
  242. AFMCharMetrics chm = afm.getChar("d");
  243. if (chm != null) {
  244. RectangularShape rect = chm.getBBox();
  245. if (rect != null) {
  246. asc = (int)Math.round(rect.getMinX());
  247. }
  248. }
  249. }
  250. if (asc == 0) {
  251. asc = Math.round(returnFont.getFontBBox()[3] * 0.9f);
  252. }
  253. returnFont.setAscender(asc);
  254. }
  255. if (returnFont.getDescender() == 0) {
  256. int desc = 0;
  257. if (afm != null) {
  258. AFMCharMetrics chm = afm.getChar("p");
  259. if (chm != null) {
  260. RectangularShape rect = chm.getBBox();
  261. if (rect != null) {
  262. desc = (int)Math.round(rect.getMinX());
  263. }
  264. }
  265. }
  266. if (desc == 0) {
  267. desc = returnFont.getFontBBox()[1];
  268. }
  269. returnFont.setDescender(desc);
  270. }
  271. if (returnFont.getCapHeight() == 0) {
  272. returnFont.setCapHeight(returnFont.getAscender());
  273. }
  274. if (afm != null) {
  275. String charSet = afm.getCharacterSet();
  276. int flags = 0;
  277. if ("Special".equals(charSet)) {
  278. flags |= 4; //bit 3: Symbolic
  279. } else {
  280. if (singleFont.getEncoding().mapChar('A') == 'A') {
  281. //High likelyhood that the font is non-symbolic
  282. flags |= 32; //bit 6: Nonsymbolic
  283. } else {
  284. flags |= 4; //bit 3: Symbolic
  285. }
  286. }
  287. if (afm.getWritingDirectionMetrics(0).isFixedPitch()) {
  288. flags |= 1; //bit 1: FixedPitch
  289. }
  290. if (afm.getWritingDirectionMetrics(0).getItalicAngle() != 0.0) {
  291. flags |= 64; //bit 7: Italic
  292. }
  293. returnFont.setFlags(flags);
  294. returnFont.setFirstChar(afm.getFirstChar());
  295. returnFont.setLastChar(afm.getLastChar());
  296. Iterator iter = afm.getCharMetrics().iterator();
  297. while (iter.hasNext()) {
  298. AFMCharMetrics chm = (AFMCharMetrics)iter.next();
  299. if (chm.hasCharCode()) {
  300. singleFont.setWidth(chm.getCharCode(), (int)Math.round(chm.getWidthX()));
  301. }
  302. }
  303. if (useKerning) {
  304. returnFont.replaceKerningMap(afm.createXKerningMapEncoded());
  305. }
  306. } else {
  307. returnFont.setFlags(pfm.getFlags());
  308. returnFont.setFirstChar(pfm.getFirstChar());
  309. returnFont.setLastChar(pfm.getLastChar());
  310. for (short i = pfm.getFirstChar(); i <= pfm.getLastChar(); i++) {
  311. singleFont.setWidth(i, pfm.getCharWidth(i));
  312. }
  313. if (useKerning) {
  314. returnFont.replaceKerningMap(pfm.getKerning());
  315. }
  316. }
  317. }
  318. private CodePointMapping buildCustomEncoding(String encodingName, AFMFile afm) {
  319. List chars = afm.getCharMetrics();
  320. int mappingCount = 0;
  321. //Just count the first time...
  322. Iterator iter = chars.iterator();
  323. while (iter.hasNext()) {
  324. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  325. if (charMetrics.getCharCode() >= 0) {
  326. String u = charMetrics.getUnicodeSequence();
  327. if (u != null && u.length() == 1) {
  328. mappingCount++;
  329. }
  330. }
  331. }
  332. //...and now build the table.
  333. int[] table = new int[mappingCount * 2];
  334. String[] charNameMap = new String[256];
  335. iter = chars.iterator();
  336. int idx = 0;
  337. while (iter.hasNext()) {
  338. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  339. if (charMetrics.getCharCode() >= 0) {
  340. charNameMap[charMetrics.getCharCode()] = charMetrics.getCharName();
  341. String unicodes = charMetrics.getUnicodeSequence();
  342. if (unicodes == null) {
  343. log.info("No Unicode mapping for glyph: " + charMetrics);
  344. } else if (unicodes.length() == 1) {
  345. table[idx] = charMetrics.getCharCode();
  346. idx++;
  347. table[idx] = unicodes.charAt(0);
  348. idx++;
  349. } else {
  350. log.warn("Multi-character representation of glyph not currently supported: "
  351. + charMetrics);
  352. }
  353. }
  354. }
  355. return new CodePointMapping(encodingName, table, charNameMap);
  356. }
  357. }