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

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