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.3KB

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