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

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