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.svg.PDFAElementBridge;
  38. import org.apache.fop.svg.PDFBridgeContext;
  39. import org.apache.fop.svg.PDFGraphics2D;
  40. import org.apache.fop.svg.SVGEventProducer;
  41. import org.apache.fop.svg.SVGUserAgent;
  42. /**
  43. * Image Handler implementation which handles SVG images.
  44. */
  45. public class PDFImageHandlerSVG implements ImageHandler {
  46. /** logging instance */
  47. private static Log log = LogFactory.getLog(PDFImageHandlerSVG.class);
  48. /** {@inheritDoc} */
  49. public void handleImage(RenderingContext context, Image image, Rectangle pos)
  50. throws IOException {
  51. PDFRenderingContext pdfContext = (PDFRenderingContext)context;
  52. PDFContentGenerator generator = pdfContext.getGenerator();
  53. ImageXMLDOM imageSVG = (ImageXMLDOM)image;
  54. FOUserAgent userAgent = context.getUserAgent();
  55. final float deviceResolution = userAgent.getTargetResolution();
  56. if (log.isDebugEnabled()) {
  57. log.debug("Generating SVG at " + deviceResolution + "dpi.");
  58. }
  59. final float uaResolution = userAgent.getSourceResolution();
  60. SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());
  61. //Scale for higher resolution on-the-fly images from Batik
  62. double s = uaResolution / deviceResolution;
  63. AffineTransform resolutionScaling = new AffineTransform();
  64. resolutionScaling.scale(s, s);
  65. GVTBuilder builder = new GVTBuilder();
  66. //Controls whether text painted by Batik is generated using text or path operations
  67. boolean strokeText = false;
  68. //TODO connect with configuration elsewhere.
  69. BridgeContext ctx = new PDFBridgeContext(ua,
  70. (strokeText ? null : pdfContext.getFontInfo()),
  71. userAgent.getFactory().getImageManager(),
  72. userAgent.getImageSessionContext(),
  73. new AffineTransform());
  74. GraphicsNode root;
  75. try {
  76. root = builder.build(ctx, imageSVG.getDocument());
  77. builder = null;
  78. } catch (Exception e) {
  79. SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
  80. context.getUserAgent().getEventBroadcaster());
  81. eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
  82. return;
  83. }
  84. // get the 'width' and 'height' attributes of the SVG document
  85. float w = (float)ctx.getDocumentSize().getWidth() * 1000f;
  86. float h = (float)ctx.getDocumentSize().getHeight() * 1000f;
  87. float sx = pos.width / w;
  88. float sy = pos.height / h;
  89. //Scaling and translation for the bounding box of the image
  90. AffineTransform scaling = new AffineTransform(
  91. sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f);
  92. //Transformation matrix that establishes the local coordinate system for the SVG graphic
  93. //in relation to the current coordinate system
  94. AffineTransform imageTransform = new AffineTransform();
  95. imageTransform.concatenate(scaling);
  96. imageTransform.concatenate(resolutionScaling);
  97. /*
  98. * Clip to the svg area.
  99. * Note: To have the svg overlay (under) a text area then use
  100. * an fo:block-container
  101. */
  102. generator.comment("SVG setup");
  103. generator.saveGraphicsState();
  104. if (context.getUserAgent().isAccessibilityEnabled()) {
  105. String structElemType = pdfContext.getStructElemType();
  106. int sequenceNum = pdfContext.getSequenceNum();
  107. generator.startAccessSequence(structElemType, sequenceNum);
  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. }