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

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