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.

PreloaderSVG.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.image.loader.batik;
  19. import java.awt.geom.AffineTransform;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import javax.xml.parsers.SAXParserFactory;
  23. import javax.xml.transform.Source;
  24. import javax.xml.transform.dom.DOMSource;
  25. import org.w3c.dom.Element;
  26. import org.w3c.dom.svg.SVGDocument;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.apache.batik.bridge.BridgeContext;
  30. import org.apache.batik.bridge.UnitProcessor;
  31. import org.apache.batik.bridge.UserAgent;
  32. import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
  33. import org.apache.batik.dom.svg.SVGOMDocument;
  34. import org.apache.xmlgraphics.image.loader.ImageContext;
  35. import org.apache.xmlgraphics.image.loader.ImageInfo;
  36. import org.apache.xmlgraphics.image.loader.ImageSize;
  37. import org.apache.xmlgraphics.image.loader.impl.AbstractImagePreloader;
  38. import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
  39. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  40. import org.apache.xmlgraphics.io.XmlSourceUtil;
  41. import org.apache.xmlgraphics.util.MimeConstants;
  42. import org.apache.xmlgraphics.util.UnitConv;
  43. import org.apache.fop.svg.SimpleSVGUserAgent;
  44. import org.apache.fop.util.UnclosableInputStream;
  45. /**
  46. * Image preloader for SVG images.
  47. */
  48. public class PreloaderSVG extends AbstractImagePreloader {
  49. /** Logger instance */
  50. private static Log log = LogFactory.getLog(PreloaderSVG.class);
  51. private boolean batikAvailable = true;
  52. /** {@inheritDoc} */
  53. public ImageInfo preloadImage(String uri, Source src, ImageContext context)
  54. throws IOException {
  55. ImageInfo info = null;
  56. if (batikAvailable) {
  57. try {
  58. Loader loader = new Loader();
  59. if (!loader.isSupportedSource(src)) {
  60. return null;
  61. }
  62. info = loader.getImage(uri, src, context);
  63. } catch (NoClassDefFoundError e) {
  64. batikAvailable = false;
  65. log.warn("Batik not in class path", e);
  66. return null;
  67. }
  68. }
  69. if (info != null) {
  70. XmlSourceUtil.closeQuietly(src); //Image is fully read
  71. }
  72. return info;
  73. }
  74. /**
  75. * Returns the fully qualified classname of an XML parser for
  76. * Batik classes that apparently need it (error messages, perhaps)
  77. * @return an XML parser classname
  78. */
  79. public static String getParserName() {
  80. try {
  81. SAXParserFactory factory = SAXParserFactory.newInstance();
  82. return factory.newSAXParser().getXMLReader().getClass().getName();
  83. } catch (Exception e) {
  84. return null;
  85. }
  86. }
  87. /**
  88. * This method is put in another class so that the class loader does not
  89. * attempt to load Batik related classes when constructing the SVGPreloader
  90. * class.
  91. */
  92. private final class Loader {
  93. private Loader() {
  94. }
  95. private ImageInfo getImage(String uri, Source src,
  96. ImageContext context) {
  97. // parse document and get the size attributes of the svg element
  98. InputStream in = null;
  99. try {
  100. SVGDocument doc;
  101. if (src instanceof DOMSource) {
  102. DOMSource domSrc = (DOMSource)src;
  103. doc = (SVGDocument)domSrc.getNode();
  104. } else {
  105. in = new UnclosableInputStream(XmlSourceUtil.needInputStream(src));
  106. int length = in.available();
  107. in.mark(length + 1);
  108. SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(
  109. getParserName());
  110. doc = factory.createSVGDocument(src.getSystemId(), in);
  111. }
  112. ImageInfo info = createImageInfo(uri, context, doc);
  113. return info;
  114. } catch (NoClassDefFoundError ncdfe) {
  115. if (in != null) {
  116. try {
  117. in.reset();
  118. } catch (IOException ioe) {
  119. // we're more interested in the original exception
  120. }
  121. }
  122. batikAvailable = false;
  123. log.warn("Batik not in class path", ncdfe);
  124. return null;
  125. } catch (IOException e) {
  126. // If the svg is invalid then it throws an IOException
  127. // so there is no way of knowing if it is an svg document
  128. log.debug("Error while trying to load stream as an SVG file: "
  129. + e.getMessage());
  130. // assuming any exception means this document is not svg
  131. // or could not be loaded for some reason
  132. try {
  133. in.reset();
  134. } catch (IOException ioe) {
  135. // we're more interested in the original exception
  136. }
  137. return null;
  138. }
  139. }
  140. private ImageInfo createImageInfo(String uri, ImageContext context, SVGDocument doc) {
  141. Element e = doc.getRootElement();
  142. float pxUnitToMillimeter = UnitConv.IN2MM / context.getSourceResolution();
  143. UserAgent userAg = new SimpleSVGUserAgent(pxUnitToMillimeter,
  144. new AffineTransform()) {
  145. /** {@inheritDoc} */
  146. public void displayMessage(String message) {
  147. log.debug(message);
  148. }
  149. };
  150. BridgeContext ctx = new BridgeContext(userAg);
  151. UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, e);
  152. String s;
  153. // 'width' attribute - default is 100%
  154. s = e.getAttributeNS(null, SVGOMDocument.SVG_WIDTH_ATTRIBUTE);
  155. if (s.length() == 0) {
  156. s = SVGOMDocument.SVG_SVG_WIDTH_DEFAULT_VALUE;
  157. }
  158. float width = UnitProcessor.svgHorizontalLengthToUserSpace(
  159. s, SVGOMDocument.SVG_WIDTH_ATTRIBUTE, uctx);
  160. // 'height' attribute - default is 100%
  161. s = e.getAttributeNS(null, SVGOMDocument.SVG_HEIGHT_ATTRIBUTE);
  162. if (s.length() == 0) {
  163. s = SVGOMDocument.SVG_SVG_HEIGHT_DEFAULT_VALUE;
  164. }
  165. float height = UnitProcessor.svgVerticalLengthToUserSpace(
  166. s, SVGOMDocument.SVG_HEIGHT_ATTRIBUTE, uctx);
  167. int widthMpt = (int)Math.round(px2mpt(width, context.getSourceResolution()));
  168. int heightMpt = (int)Math.round(px2mpt(height, context.getSourceResolution()));
  169. ImageInfo info = new ImageInfo(uri, MimeConstants.MIME_SVG);
  170. ImageSize size = new ImageSize();
  171. size.setSizeInMillipoints(widthMpt, heightMpt);
  172. //Set the resolution to that of the FOUserAgent
  173. size.setResolution(context.getSourceResolution());
  174. size.calcPixelsFromSize();
  175. info.setSize(size);
  176. //The whole image had to be loaded for this, so keep it
  177. ImageXMLDOM xmlImage = new ImageXMLDOM(info,
  178. doc, BatikImageFlavors.SVG_DOM);
  179. info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, xmlImage);
  180. return info;
  181. }
  182. private boolean isSupportedSource(Source src) {
  183. if (src instanceof DOMSource) {
  184. DOMSource domSrc = (DOMSource)src;
  185. return (domSrc.getNode() instanceof SVGDocument);
  186. } else {
  187. return ImageUtil.hasInputStream(src);
  188. }
  189. }
  190. }
  191. private static double px2mpt(double px, double resolution) {
  192. return px * 1000 * UnitConv.IN2PT / resolution;
  193. }
  194. }