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.

PDFImageHandlerSVG.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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.render.pdf;
  19. import java.awt.Color;
  20. import java.awt.Rectangle;
  21. import java.awt.geom.AffineTransform;
  22. import java.io.IOException;
  23. import org.w3c.dom.Document;
  24. import org.apache.batik.bridge.BridgeContext;
  25. import org.apache.batik.bridge.GVTBuilder;
  26. import org.apache.batik.dom.svg.SVGDOMImplementation;
  27. import org.apache.batik.gvt.GraphicsNode;
  28. import org.apache.batik.util.SVGConstants;
  29. import org.apache.commons.logging.Log;
  30. import org.apache.commons.logging.LogFactory;
  31. import org.apache.xmlgraphics.image.loader.Image;
  32. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  33. import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM;
  34. import org.apache.xmlgraphics.util.UnitConv;
  35. import org.apache.fop.apps.FOUserAgent;
  36. import org.apache.fop.image.loader.batik.BatikImageFlavors;
  37. import org.apache.fop.image.loader.batik.BatikUtil;
  38. import org.apache.fop.render.ImageHandler;
  39. import org.apache.fop.render.ImageHandlerUtil;
  40. import org.apache.fop.render.RenderingContext;
  41. import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo;
  42. import org.apache.fop.svg.PDFAElementBridge;
  43. import org.apache.fop.svg.PDFBridgeContext;
  44. import org.apache.fop.svg.PDFGraphics2D;
  45. import org.apache.fop.svg.SVGEventProducer;
  46. import org.apache.fop.svg.SVGUserAgent;
  47. /**
  48. * Image Handler implementation which handles SVG images.
  49. */
  50. public class PDFImageHandlerSVG implements ImageHandler {
  51. /** logging instance */
  52. private static Log log = LogFactory.getLog(PDFImageHandlerSVG.class);
  53. /** {@inheritDoc} */
  54. public void handleImage(RenderingContext context, // CSOK: MethodLength
  55. Image image, Rectangle pos)
  56. throws IOException {
  57. PDFRenderingContext pdfContext = (PDFRenderingContext)context;
  58. PDFContentGenerator generator = pdfContext.getGenerator();
  59. ImageXMLDOM imageSVG = (ImageXMLDOM)image;
  60. FOUserAgent userAgent = context.getUserAgent();
  61. final float deviceResolution = userAgent.getTargetResolution();
  62. if (log.isDebugEnabled()) {
  63. log.debug("Generating SVG at " + deviceResolution + "dpi.");
  64. }
  65. final float uaResolution = userAgent.getSourceResolution();
  66. SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());
  67. GVTBuilder builder = new GVTBuilder();
  68. //Controls whether text painted by Batik is generated using text or path operations
  69. boolean strokeText = false;
  70. //TODO connect with configuration elsewhere.
  71. BridgeContext ctx = new PDFBridgeContext(ua,
  72. (strokeText ? null : pdfContext.getFontInfo()),
  73. userAgent.getFactory().getImageManager(),
  74. userAgent.getImageSessionContext(),
  75. new AffineTransform());
  76. //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
  77. //to it.
  78. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument());
  79. GraphicsNode root;
  80. try {
  81. root = builder.build(ctx, clonedDoc);
  82. builder = null;
  83. } catch (Exception e) {
  84. SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
  85. context.getUserAgent().getEventBroadcaster());
  86. eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
  87. return;
  88. }
  89. // get the 'width' and 'height' attributes of the SVG document
  90. float w = image.getSize().getWidthMpt();
  91. float h = image.getSize().getHeightMpt();
  92. float sx = pos.width / w;
  93. float sy = pos.height / h;
  94. //Scaling and translation for the bounding box of the image
  95. AffineTransform scaling = new AffineTransform(
  96. sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f);
  97. double sourceScale = UnitConv.IN2PT / uaResolution;
  98. scaling.scale(sourceScale, sourceScale);
  99. //Scale for higher resolution on-the-fly images from Batik
  100. AffineTransform resolutionScaling = new AffineTransform();
  101. double targetScale = uaResolution / deviceResolution;
  102. resolutionScaling.scale(targetScale, targetScale);
  103. resolutionScaling.scale(1.0 / sx, 1.0 / sy);
  104. //Transformation matrix that establishes the local coordinate system for the SVG graphic
  105. //in relation to the current coordinate system
  106. AffineTransform imageTransform = new AffineTransform();
  107. imageTransform.concatenate(scaling);
  108. imageTransform.concatenate(resolutionScaling);
  109. if (log.isTraceEnabled()) {
  110. log.trace("nat size: " + w + "/" + h);
  111. log.trace("req size: " + pos.width + "/" + pos.height);
  112. log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution
  113. + " --> target scaling: " + targetScale);
  114. log.trace(image.getSize());
  115. log.trace("sx: " + sx + ", sy: " + sy);
  116. log.trace("scaling: " + scaling);
  117. log.trace("resolution scaling: " + resolutionScaling);
  118. log.trace("image transform: " + resolutionScaling);
  119. }
  120. /*
  121. * Clip to the svg area.
  122. * Note: To have the svg overlay (under) a text area then use
  123. * an fo:block-container
  124. */
  125. if (log.isTraceEnabled()) {
  126. generator.comment("SVG setup");
  127. }
  128. generator.saveGraphicsState();
  129. if (context.getUserAgent().isAccessibilityEnabled()) {
  130. MarkedContentInfo mci = pdfContext.getMarkedContentInfo();
  131. generator.beginMarkedContentSequence(mci.tag, mci.mcid);
  132. }
  133. generator.setColor(Color.black, false);
  134. generator.setColor(Color.black, true);
  135. if (!scaling.isIdentity()) {
  136. if (log.isTraceEnabled()) {
  137. generator.comment("viewbox");
  138. }
  139. generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n");
  140. }
  141. //SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
  142. PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(),
  143. generator.getDocument(),
  144. generator.getResourceContext(), pdfContext.getPage().referencePDF(),
  145. "", 0);
  146. graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
  147. if (!resolutionScaling.isIdentity()) {
  148. if (log.isTraceEnabled()) {
  149. generator.comment("resolution scaling for " + uaResolution
  150. + " -> " + deviceResolution);
  151. }
  152. generator.add(
  153. CTMHelper.toPDFString(resolutionScaling, false) + " cm\n");
  154. graphics.scale(
  155. 1.0 / resolutionScaling.getScaleX(),
  156. 1.0 / resolutionScaling.getScaleY());
  157. }
  158. if (log.isTraceEnabled()) {
  159. generator.comment("SVG start");
  160. }
  161. //Save state and update coordinate system for the SVG image
  162. generator.getState().save();
  163. generator.getState().concatenate(imageTransform);
  164. //Now that we have the complete transformation matrix for the image, we can update the
  165. //transformation matrix for the AElementBridge.
  166. PDFAElementBridge aBridge = (PDFAElementBridge)ctx.getBridge(
  167. SVGDOMImplementation.SVG_NAMESPACE_URI, SVGConstants.SVG_A_TAG);
  168. aBridge.getCurrentTransform().setTransform(generator.getState().getTransform());
  169. graphics.setPaintingState(generator.getState());
  170. graphics.setOutputStream(generator.getOutputStream());
  171. try {
  172. root.paint(graphics);
  173. ctx.dispose();
  174. generator.add(graphics.getString());
  175. } catch (Exception e) {
  176. SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
  177. context.getUserAgent().getEventBroadcaster());
  178. eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI());
  179. }
  180. generator.getState().restore();
  181. if (context.getUserAgent().isAccessibilityEnabled()) {
  182. generator.restoreGraphicsStateAccess();
  183. } else {
  184. generator.restoreGraphicsState();
  185. }
  186. if (log.isTraceEnabled()) {
  187. generator.comment("SVG end");
  188. }
  189. }
  190. /** {@inheritDoc} */
  191. public int getPriority() {
  192. return 400;
  193. }
  194. /** {@inheritDoc} */
  195. public Class getSupportedImageClass() {
  196. return ImageXMLDOM.class;
  197. }
  198. /** {@inheritDoc} */
  199. public ImageFlavor[] getSupportedImageFlavors() {
  200. return new ImageFlavor[] {
  201. BatikImageFlavors.SVG_DOM
  202. };
  203. }
  204. /** {@inheritDoc} */
  205. public boolean isCompatible(RenderingContext targetContext, Image image) {
  206. boolean supported = (image == null
  207. || (image instanceof ImageXMLDOM
  208. && image.getFlavor().isCompatible(BatikImageFlavors.SVG_DOM)))
  209. && targetContext instanceof PDFRenderingContext;
  210. if (supported) {
  211. String mode = (String)targetContext.getHint(ImageHandlerUtil.CONVERSION_MODE);
  212. if (ImageHandlerUtil.isConversionModeBitmap(mode)) {
  213. //Disabling this image handler automatically causes a bitmap to be generated
  214. return false;
  215. }
  216. }
  217. return supported;
  218. }
  219. }