Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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