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 8.5KB

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