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.

PSFontUtils.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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.render.ps;
  19. import java.io.FileNotFoundException;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.net.MalformedURLException;
  23. import java.util.Iterator;
  24. import java.util.Map;
  25. import javax.xml.transform.Source;
  26. import javax.xml.transform.stream.StreamSource;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.apache.xmlgraphics.fonts.Glyphs;
  30. import org.apache.xmlgraphics.ps.DSCConstants;
  31. import org.apache.xmlgraphics.ps.PSGenerator;
  32. import org.apache.xmlgraphics.ps.PSResource;
  33. import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
  34. import org.apache.fop.fonts.Base14Font;
  35. import org.apache.fop.fonts.CustomFont;
  36. import org.apache.fop.fonts.Font;
  37. import org.apache.fop.fonts.FontInfo;
  38. import org.apache.fop.fonts.FontType;
  39. import org.apache.fop.fonts.LazyFont;
  40. import org.apache.fop.fonts.SingleByteEncoding;
  41. import org.apache.fop.fonts.SingleByteFont;
  42. import org.apache.fop.fonts.Typeface;
  43. /**
  44. * Utility code for font handling in PostScript.
  45. */
  46. public class PSFontUtils extends org.apache.xmlgraphics.ps.PSFontUtils {
  47. /** logging instance */
  48. protected static final Log log = LogFactory.getLog(PSFontUtils.class);
  49. /**
  50. * Generates the PostScript code for the font dictionary. This method should only be
  51. * used if no "resource optimization" is performed, i.e. when the fonts are not embedded
  52. * in a second pass.
  53. * @param gen PostScript generator to use for output
  54. * @param fontInfo available fonts
  55. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  56. * @throws IOException in case of an I/O problem
  57. */
  58. public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo)
  59. throws IOException {
  60. return writeFontDict(gen, fontInfo, fontInfo.getFonts(), true);
  61. }
  62. /**
  63. * Generates the PostScript code for the font dictionary. This method assumes all used
  64. * fonts and characters are known, i.e. when PostScript is generated with resource
  65. * optimization turned on.
  66. * @param gen PostScript generator to use for output
  67. * @param fontInfo available fonts
  68. * @param fonts the set of fonts to work with
  69. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  70. * @throws IOException in case of an I/O problem
  71. */
  72. public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map fonts)
  73. throws IOException {
  74. return writeFontDict(gen, fontInfo, fonts, false);
  75. }
  76. /**
  77. * Generates the PostScript code for the font dictionary.
  78. * @param gen PostScript generator to use for output
  79. * @param fontInfo available fonts
  80. * @param fonts the set of fonts to work with
  81. * @param encodeAllCharacters true if all characters shall be encoded using additional,
  82. * generated encodings.
  83. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  84. * @throws IOException in case of an I/O problem
  85. */
  86. private static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map fonts,
  87. boolean encodeAllCharacters) throws IOException {
  88. gen.commentln("%FOPBeginFontDict");
  89. Map fontResources = new java.util.HashMap();
  90. Iterator iter = fonts.keySet().iterator();
  91. while (iter.hasNext()) {
  92. String key = (String)iter.next();
  93. Typeface tf = getTypeFace(fontInfo, fonts, key);
  94. PSResource fontRes = new PSResource(PSResource.TYPE_FONT, tf.getFontName());
  95. fontResources.put(key, fontRes);
  96. embedFont(gen, tf, fontRes);
  97. if (tf instanceof SingleByteFont) {
  98. SingleByteFont sbf = (SingleByteFont)tf;
  99. if (encodeAllCharacters) {
  100. sbf.encodeAllUnencodedCharacters();
  101. }
  102. for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) {
  103. SingleByteEncoding encoding = sbf.getAdditionalEncoding(i);
  104. defineEncoding(gen, encoding);
  105. String postFix = "_" + (i + 1);
  106. PSResource derivedFontRes = defineDerivedFont(gen, tf.getFontName(),
  107. tf.getFontName() + postFix, encoding.getName());
  108. fontResources.put(key + postFix, derivedFontRes);
  109. }
  110. }
  111. }
  112. gen.commentln("%FOPEndFontDict");
  113. reencodeFonts(gen, fonts);
  114. return fontResources;
  115. }
  116. private static void reencodeFonts(PSGenerator gen, Map fonts) throws IOException {
  117. ResourceTracker tracker = gen.getResourceTracker();
  118. if (!tracker.isResourceSupplied(WINANSI_ENCODING_RESOURCE)) {
  119. //Only out Base 14 fonts still use that
  120. defineWinAnsiEncoding(gen);
  121. }
  122. gen.commentln("%FOPBeginFontReencode");
  123. //Rewrite font encodings
  124. Iterator iter = fonts.keySet().iterator();
  125. while (iter.hasNext()) {
  126. String key = (String)iter.next();
  127. Typeface tf = (Typeface)fonts.get(key);
  128. if (tf instanceof LazyFont) {
  129. tf = ((LazyFont)tf).getRealFont();
  130. if (tf == null) {
  131. continue;
  132. }
  133. }
  134. if (null == tf.getEncodingName()) {
  135. //ignore (ZapfDingbats and Symbol used to run through here, kept for safety reasons)
  136. } else if ("SymbolEncoding".equals(tf.getEncodingName())) {
  137. //ignore (no encoding redefinition)
  138. } else if ("ZapfDingbatsEncoding".equals(tf.getEncodingName())) {
  139. //ignore (no encoding redefinition)
  140. } else {
  141. if (tf instanceof Base14Font) {
  142. //Our Base 14 fonts don't use the default encoding
  143. redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName());
  144. } else if (tf instanceof SingleByteFont) {
  145. SingleByteFont sbf = (SingleByteFont)tf;
  146. if (!sbf.isUsingNativeEncoding()) {
  147. //Font has been configured to use an encoding other than the default one
  148. redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName());
  149. }
  150. }
  151. }
  152. }
  153. gen.commentln("%FOPEndFontReencode");
  154. }
  155. private static Typeface getTypeFace(FontInfo fontInfo, Map fonts, String key) {
  156. Typeface tf = (Typeface)fonts.get(key);
  157. if (tf instanceof LazyFont) {
  158. tf = ((LazyFont)tf).getRealFont();
  159. }
  160. if (tf == null) {
  161. //This is to avoid an NPE if a malconfigured font is in the configuration but not
  162. //used in the document. If it were used, we wouldn't get this far.
  163. String fallbackKey = fontInfo.getInternalFontKey(Font.DEFAULT_FONT);
  164. tf = (Typeface)fonts.get(fallbackKey);
  165. }
  166. return tf;
  167. }
  168. /**
  169. * Embeds a font in the PostScript file.
  170. * @param gen the PostScript generator
  171. * @param tf the font
  172. * @param fontRes the PSResource associated with the font
  173. * @throws IOException In case of an I/O error
  174. */
  175. public static void embedFont(PSGenerator gen, Typeface tf, PSResource fontRes)
  176. throws IOException {
  177. boolean embeddedFont = false;
  178. if (FontType.TYPE1 == tf.getFontType()) {
  179. if (tf instanceof CustomFont) {
  180. CustomFont cf = (CustomFont)tf;
  181. if (isEmbeddable(cf)) {
  182. InputStream in = getInputStreamOnFont(gen, cf);
  183. if (in != null) {
  184. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE,
  185. fontRes);
  186. embedType1Font(gen, in);
  187. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  188. gen.getResourceTracker().registerSuppliedResource(fontRes);
  189. embeddedFont = true;
  190. } else {
  191. gen.commentln("%WARNING: Could not embed font: " + cf.getFontName());
  192. log.warn("Font " + cf.getFontName() + " is marked as supplied in the"
  193. + " PostScript file but could not be embedded!");
  194. }
  195. }
  196. }
  197. }
  198. if (!embeddedFont) {
  199. gen.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, fontRes);
  200. }
  201. }
  202. private static boolean isEmbeddable(CustomFont font) {
  203. return font.isEmbeddable();
  204. }
  205. private static InputStream getInputStreamOnFont(PSGenerator gen, CustomFont font)
  206. throws IOException {
  207. if (isEmbeddable(font)) {
  208. Source source = font.getEmbedFileSource();
  209. if (source == null && font.getEmbedResourceName() != null) {
  210. source = new StreamSource(PSFontUtils.class
  211. .getResourceAsStream(font.getEmbedResourceName()));
  212. }
  213. if (source == null) {
  214. return null;
  215. }
  216. InputStream in = null;
  217. if (source instanceof StreamSource) {
  218. in = ((StreamSource) source).getInputStream();
  219. }
  220. if (in == null && source.getSystemId() != null) {
  221. try {
  222. in = new java.net.URL(source.getSystemId()).openStream();
  223. } catch (MalformedURLException e) {
  224. new FileNotFoundException(
  225. "File not found. URL could not be resolved: "
  226. + e.getMessage());
  227. }
  228. }
  229. if (in == null) {
  230. return null;
  231. }
  232. //Make sure the InputStream is decorated with a BufferedInputStream
  233. if (!(in instanceof java.io.BufferedInputStream)) {
  234. in = new java.io.BufferedInputStream(in);
  235. }
  236. return in;
  237. } else {
  238. return null;
  239. }
  240. }
  241. /**
  242. * Determines the set of fonts that will be supplied with the PS file and registers them
  243. * with the resource tracker. All the fonts that are being processed are returned as a Map.
  244. * @param resTracker the resource tracker
  245. * @param fontInfo available fonts
  246. * @param fonts the set of fonts to work with
  247. * @return a Map of PSResource instances representing all defined fonts (key: font key)
  248. */
  249. public static Map determineSuppliedFonts(ResourceTracker resTracker,
  250. FontInfo fontInfo, Map fonts) {
  251. Map fontResources = new java.util.HashMap();
  252. Iterator iter = fonts.keySet().iterator();
  253. while (iter.hasNext()) {
  254. String key = (String)iter.next();
  255. Typeface tf = getTypeFace(fontInfo, fonts, key);
  256. PSResource fontRes = new PSResource("font", tf.getFontName());
  257. fontResources.put(key, fontRes);
  258. if (FontType.TYPE1 == tf.getFontType()) {
  259. if (tf instanceof CustomFont) {
  260. CustomFont cf = (CustomFont)tf;
  261. if (isEmbeddable(cf)) {
  262. resTracker.registerSuppliedResource(fontRes);
  263. }
  264. if (tf instanceof SingleByteFont) {
  265. SingleByteFont sbf = (SingleByteFont)tf;
  266. for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) {
  267. SingleByteEncoding encoding = sbf.getAdditionalEncoding(i);
  268. PSResource encodingRes = new PSResource(
  269. PSResource.TYPE_ENCODING, encoding.getName());
  270. resTracker.registerSuppliedResource(encodingRes);
  271. PSResource derivedFontRes = new PSResource(
  272. PSResource.TYPE_FONT, tf.getFontName() + "_" + (i + 1));
  273. resTracker.registerSuppliedResource(derivedFontRes);
  274. }
  275. }
  276. }
  277. }
  278. }
  279. return fontResources;
  280. }
  281. /**
  282. * Defines the single-byte encoding for use in PostScript files.
  283. * @param gen the PostScript generator
  284. * @param encoding the single-byte encoding
  285. * @return the PSResource instance that represents the encoding
  286. * @throws IOException In case of an I/O problem
  287. */
  288. public static PSResource defineEncoding(PSGenerator gen, SingleByteEncoding encoding)
  289. throws IOException {
  290. PSResource res = new PSResource(PSResource.TYPE_ENCODING, encoding.getName());
  291. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res);
  292. gen.writeln("/" + encoding.getName() + " [");
  293. String[] charNames = encoding.getCharNameMap();
  294. for (int i = 0; i < 256; i++) {
  295. if (i > 0) {
  296. if ((i % 5) == 0) {
  297. gen.newLine();
  298. } else {
  299. gen.write(" ");
  300. }
  301. }
  302. String glyphname = null;
  303. if (i < charNames.length) {
  304. glyphname = charNames[i];
  305. }
  306. if (glyphname == null || "".equals(glyphname)) {
  307. glyphname = Glyphs.NOTDEF;
  308. }
  309. gen.write("/");
  310. gen.write(glyphname);
  311. }
  312. gen.newLine();
  313. gen.writeln("] def");
  314. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  315. gen.getResourceTracker().registerSuppliedResource(res);
  316. return res;
  317. }
  318. /**
  319. * Derives a new font based on an existing font with a given encoding. The encoding must
  320. * have been registered before.
  321. * @param gen the PostScript generator
  322. * @param baseFontName the font name of the font to derive from
  323. * @param fontName the font name of the new font to be define
  324. * @param encoding the new encoding (must be predefined in the PS file)
  325. * @return the PSResource representing the derived font
  326. * @throws IOException In case of an I/O problem
  327. */
  328. public static PSResource defineDerivedFont
  329. (PSGenerator gen, String baseFontName, String fontName, String encoding)
  330. throws IOException {
  331. PSResource res = new PSResource(PSResource.TYPE_FONT, fontName);
  332. gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res);
  333. gen.commentln("%XGCDependencies: font " + baseFontName);
  334. gen.commentln("%XGC+ encoding " + encoding);
  335. gen.writeln("/" + baseFontName + " findfont");
  336. gen.writeln("dup length dict begin");
  337. gen.writeln(" {1 index /FID ne {def} {pop pop} ifelse} forall");
  338. gen.writeln(" /Encoding " + encoding + " def");
  339. gen.writeln(" currentdict");
  340. gen.writeln("end");
  341. gen.writeln("/" + fontName + " exch definefont pop");
  342. gen.writeDSCComment(DSCConstants.END_RESOURCE);
  343. gen.getResourceTracker().registerSuppliedResource(res);
  344. return res;
  345. }
  346. }