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.

AbstractFOPTranscoder.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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.svg;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import javax.xml.transform.Source;
  22. import javax.xml.transform.stream.StreamSource;
  23. import org.w3c.dom.DOMImplementation;
  24. import org.xml.sax.EntityResolver;
  25. import org.apache.commons.logging.Log;
  26. import org.apache.commons.logging.impl.SimpleLog;
  27. import org.apache.batik.anim.dom.SVGDOMImplementation;
  28. import org.apache.batik.bridge.FontFamilyResolver;
  29. import org.apache.batik.dom.util.DocumentFactory;
  30. import org.apache.batik.transcoder.ErrorHandler;
  31. import org.apache.batik.transcoder.SVGAbstractTranscoder;
  32. import org.apache.batik.transcoder.TranscoderException;
  33. import org.apache.batik.transcoder.TranscodingHints;
  34. import org.apache.batik.transcoder.image.ImageTranscoder;
  35. import org.apache.batik.transcoder.keys.BooleanKey;
  36. import org.apache.batik.transcoder.keys.FloatKey;
  37. import org.apache.batik.util.ParsedURL;
  38. import org.apache.batik.util.SVGConstants;
  39. import org.apache.xmlgraphics.image.GraphicsConstants;
  40. import org.apache.xmlgraphics.image.loader.ImageContext;
  41. import org.apache.xmlgraphics.image.loader.ImageManager;
  42. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  43. import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext;
  44. import org.apache.xmlgraphics.util.UnitConv;
  45. import org.apache.fop.configuration.Configurable;
  46. import org.apache.fop.configuration.Configuration;
  47. import org.apache.fop.configuration.ConfigurationException;
  48. import org.apache.fop.configuration.DefaultConfiguration;
  49. import org.apache.fop.svg.font.FOPFontFamilyResolver;
  50. /**
  51. * This is the common base class of all of FOP's transcoders.
  52. */
  53. public abstract class AbstractFOPTranscoder extends SVGAbstractTranscoder implements Configurable {
  54. /**
  55. * The key is used to specify the resolution for on-the-fly images generated
  56. * due to complex effects like gradients and filters.
  57. */
  58. public static final TranscodingHints.Key KEY_DEVICE_RESOLUTION = new FloatKey();
  59. /**
  60. * The key to specify whether to stroke text instead of using text
  61. * operations.
  62. */
  63. public static final TranscodingHints.Key KEY_STROKE_TEXT = new BooleanKey();
  64. /**
  65. * The key is used to specify whether the available fonts should be automatically
  66. * detected. The alternative is to configure the transcoder manually using a configuration
  67. * file.
  68. */
  69. public static final TranscodingHints.Key KEY_AUTO_FONTS = new BooleanKey();
  70. /** The value to turn on text stroking. */
  71. public static final Boolean VALUE_FORMAT_ON = Boolean.TRUE;
  72. /** The value to turn off text stroking. */
  73. public static final Boolean VALUE_FORMAT_OFF = Boolean.FALSE;
  74. private Log logger;
  75. private EntityResolver resolver;
  76. private Configuration cfg;
  77. private ImageManager imageManager;
  78. private ImageSessionContext imageSessionContext;
  79. /**
  80. * Constructs a new FOP-style transcoder.
  81. */
  82. public AbstractFOPTranscoder() {
  83. hints.put(KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
  84. SVGConstants.SVG_NAMESPACE_URI);
  85. hints.put(KEY_DOCUMENT_ELEMENT, SVGConstants.SVG_SVG_TAG);
  86. hints.put(KEY_DOM_IMPLEMENTATION,
  87. SVGDOMImplementation.getDOMImplementation());
  88. }
  89. /**
  90. * Creates and returns the default user agent for this transcoder. Override
  91. * this method if you need non-default behaviour.
  92. * @return UserAgent the newly created user agent
  93. */
  94. protected FOPTranscoderUserAgent createUserAgent() {
  95. return new FOPTranscoderUserAgent();
  96. }
  97. /**
  98. * Sets the logger.
  99. * @param logger the logger
  100. */
  101. public void setLogger(Log logger) {
  102. this.logger = logger;
  103. }
  104. /**
  105. * Sets the EntityResolver that should be used when building SVG documents.
  106. * @param resolver the resolver
  107. */
  108. public void setEntityResolver(EntityResolver resolver) {
  109. this.resolver = resolver;
  110. }
  111. /**
  112. * @param cfg the configuration
  113. * @throws ConfigurationException if not caught
  114. */
  115. public void configure(Configuration cfg) throws ConfigurationException {
  116. this.cfg = cfg;
  117. }
  118. /**
  119. * Returns the default value for the KEY_AUTO_FONTS value.
  120. * @return the default value
  121. */
  122. protected boolean getAutoFontsDefault() {
  123. return true;
  124. }
  125. /**
  126. * Returns the effective configuration for the transcoder.
  127. * @return the effective configuration
  128. */
  129. protected Configuration getEffectiveConfiguration() {
  130. Configuration effCfg = this.cfg;
  131. if (effCfg == null) {
  132. //By default, enable font auto-detection if no cfg is given
  133. boolean autoFonts = getAutoFontsDefault();
  134. if (hints.containsKey(KEY_AUTO_FONTS)) {
  135. autoFonts = (Boolean) hints.get(KEY_AUTO_FONTS);
  136. }
  137. if (autoFonts) {
  138. DefaultConfiguration c = new DefaultConfiguration("cfg");
  139. DefaultConfiguration fonts = new DefaultConfiguration("fonts");
  140. c.addChild(fonts);
  141. DefaultConfiguration autodetect = new DefaultConfiguration("auto-detect");
  142. fonts.addChild(autodetect);
  143. effCfg = c;
  144. }
  145. }
  146. return effCfg;
  147. }
  148. /**
  149. * Returns the logger associated with this transcoder. It returns a
  150. * SimpleLog if no logger has been explicitly set.
  151. * @return Logger the logger for the transcoder.
  152. */
  153. protected final Log getLogger() {
  154. if (this.logger == null) {
  155. this.logger = new SimpleLog("FOP/Transcoder");
  156. }
  157. return this.logger;
  158. }
  159. /**
  160. * Creates a {@link DocumentFactory} that is used to create an SVG DOM
  161. * tree. The specified DOM Implementation is ignored and the Batik
  162. * SVG DOM Implementation is automatically used.
  163. *
  164. * @param domImpl the DOM Implementation (not used)
  165. * @param parserClassname the XML parser classname
  166. * @return the document factory
  167. */
  168. protected DocumentFactory createDocumentFactory(DOMImplementation domImpl,
  169. String parserClassname) {
  170. final FOPSAXSVGDocumentFactory factory
  171. = new FOPSAXSVGDocumentFactory(parserClassname);
  172. if (this.resolver != null) {
  173. factory.setAdditionalEntityResolver(this.resolver);
  174. }
  175. return factory;
  176. }
  177. /**
  178. * Indicates whether text should be stroked rather than painted using text operators. Stroking
  179. * text (also referred to as "painting as shapes") can used in situations where the quality of
  180. * text output is not satisfying. The downside of the work-around: The generated file will
  181. * likely become bigger and you will lose copy/paste functionality for certain output formats
  182. * such as PDF.
  183. * @return true if text should be stroked rather than painted using text operators
  184. */
  185. protected boolean isTextStroked() {
  186. boolean stroke = false;
  187. if (hints.containsKey(KEY_STROKE_TEXT)) {
  188. stroke = (Boolean) hints.get(KEY_STROKE_TEXT);
  189. }
  190. return stroke;
  191. }
  192. /**
  193. * Returns the device resolution that has been set up.
  194. * @return the device resolution (in dpi)
  195. */
  196. protected float getDeviceResolution() {
  197. if (hints.containsKey(KEY_DEVICE_RESOLUTION)) {
  198. return (Float) hints.get(KEY_DEVICE_RESOLUTION);
  199. } else {
  200. return GraphicsConstants.DEFAULT_DPI;
  201. }
  202. }
  203. /**
  204. * Returns the ImageManager to be used by the transcoder.
  205. * @return the image manager
  206. */
  207. protected ImageManager getImageManager() {
  208. return this.imageManager;
  209. }
  210. /**
  211. * Returns the ImageSessionContext to be used by the transcoder.
  212. * @return the image session context
  213. */
  214. protected ImageSessionContext getImageSessionContext() {
  215. return this.imageSessionContext;
  216. }
  217. /**
  218. * Sets up the image infrastructure (the image loading framework).
  219. * @param baseURI the base URI of the current document
  220. */
  221. protected void setupImageInfrastructure(final String baseURI) {
  222. final ImageContext imageContext = new ImageContext() {
  223. public float getSourceResolution() {
  224. return UnitConv.IN2MM / userAgent.getPixelUnitToMillimeter();
  225. }
  226. };
  227. this.imageManager = new ImageManager(imageContext);
  228. this.imageSessionContext = new AbstractImageSessionContext() {
  229. public ImageContext getParentContext() {
  230. return imageContext;
  231. }
  232. public float getTargetResolution() {
  233. return getDeviceResolution();
  234. }
  235. public Source resolveURI(String uri) {
  236. try {
  237. ParsedURL url = new ParsedURL(baseURI, uri);
  238. InputStream in = url.openStream();
  239. StreamSource source = new StreamSource(in, url.toString());
  240. return source;
  241. } catch (IOException ioe) {
  242. userAgent.displayError(ioe);
  243. return null;
  244. }
  245. }
  246. };
  247. }
  248. // --------------------------------------------------------------------
  249. // FOP's default error handler (for transcoders)
  250. // --------------------------------------------------------------------
  251. /**
  252. * This is the default transcoder error handler for FOP. It logs error
  253. * to an Commons Logger instead of to System.out. The remaining behaviour
  254. * is the same as Batik's DefaultErrorHandler.
  255. */
  256. protected class FOPErrorHandler implements ErrorHandler {
  257. /**
  258. * {@inheritDoc}
  259. */
  260. public void error(TranscoderException te)
  261. throws TranscoderException {
  262. getLogger().error(te.getMessage());
  263. }
  264. /**
  265. * {@inheritDoc}
  266. */
  267. public void fatalError(TranscoderException te)
  268. throws TranscoderException {
  269. throw te;
  270. }
  271. /**
  272. * {@inheritDoc}
  273. */
  274. public void warning(TranscoderException te)
  275. throws TranscoderException {
  276. getLogger().warn(te.getMessage());
  277. }
  278. }
  279. // --------------------------------------------------------------------
  280. // UserAgent implementation
  281. // --------------------------------------------------------------------
  282. /**
  283. * A user agent implementation for FOP's Transcoders.
  284. */
  285. protected class FOPTranscoderUserAgent extends SVGAbstractTranscoderUserAgent {
  286. private FOPFontFamilyResolver fontFamilyResolver;
  287. /**
  288. * Displays the specified error message using the {@link ErrorHandler}.
  289. * @param message the message to display
  290. */
  291. public void displayError(String message) {
  292. try {
  293. getErrorHandler().error(new TranscoderException(message));
  294. } catch (TranscoderException ex) {
  295. throw new RuntimeException();
  296. }
  297. }
  298. /**
  299. * Displays the specified error using the {@link ErrorHandler}.
  300. * @param e the exception to display
  301. */
  302. public void displayError(Exception e) {
  303. try {
  304. getErrorHandler().error(new TranscoderException(e));
  305. } catch (TranscoderException ex) {
  306. throw new RuntimeException();
  307. }
  308. }
  309. /**
  310. * Displays the specified message using the {@link ErrorHandler}.
  311. * @param message the message to display
  312. */
  313. public void displayMessage(String message) {
  314. getLogger().info(message);
  315. }
  316. /**
  317. * Returns the pixel to millimeter conversion factor specified in the
  318. * {@link TranscodingHints} or 0.3528 if any.
  319. * @return the pixel unit to millimeter factor
  320. */
  321. public float getPixelUnitToMillimeter() {
  322. Object key = ImageTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER;
  323. if (getTranscodingHints().containsKey(key)) {
  324. return (Float) getTranscodingHints().get(key);
  325. } else {
  326. // return 0.3528f; // 72 dpi
  327. return UnitConv.IN2MM / 96; //96dpi = 0.2645833333333333333f;
  328. }
  329. }
  330. /**
  331. * Get the media for this transcoder. Which is always print.
  332. * @return PDF media is "print"
  333. */
  334. public String getMedia() {
  335. return "print";
  336. }
  337. public void setFontFamilyResolver(FOPFontFamilyResolver resolver) {
  338. fontFamilyResolver = resolver;
  339. }
  340. @Override
  341. public FontFamilyResolver getFontFamilyResolver() {
  342. return fontFamilyResolver;
  343. }
  344. }
  345. }