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.

SVGDocumentHandler.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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.svg;
  19. import java.awt.Dimension;
  20. import java.io.IOException;
  21. import java.io.OutputStream;
  22. import javax.xml.parsers.DocumentBuilder;
  23. import javax.xml.parsers.DocumentBuilderFactory;
  24. import javax.xml.parsers.ParserConfigurationException;
  25. import javax.xml.transform.Result;
  26. import javax.xml.transform.Source;
  27. import javax.xml.transform.Transformer;
  28. import javax.xml.transform.TransformerConfigurationException;
  29. import javax.xml.transform.TransformerException;
  30. import javax.xml.transform.dom.DOMResult;
  31. import javax.xml.transform.dom.DOMSource;
  32. import javax.xml.transform.sax.SAXResult;
  33. import javax.xml.transform.sax.TransformerHandler;
  34. import javax.xml.transform.stream.StreamResult;
  35. import org.w3c.dom.Document;
  36. import org.xml.sax.ContentHandler;
  37. import org.xml.sax.SAXException;
  38. import org.xml.sax.helpers.AttributesImpl;
  39. import org.apache.commons.io.IOUtils;
  40. import org.apache.fop.render.bitmap.BitmapRendererEventProducer;
  41. import org.apache.fop.render.bitmap.MultiFileRenderingUtil;
  42. import org.apache.fop.render.intermediate.DelegatingFragmentContentHandler;
  43. import org.apache.fop.render.intermediate.IFContext;
  44. import org.apache.fop.render.intermediate.IFException;
  45. import org.apache.fop.render.intermediate.IFPainter;
  46. import org.apache.fop.util.GenerationHelperContentHandler;
  47. import org.apache.fop.util.XMLUtil;
  48. /**
  49. * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation
  50. * that writes SVG 1.1.
  51. */
  52. public class SVGDocumentHandler extends AbstractSVGDocumentHandler {
  53. /** Helper class for generating multiple files */
  54. private MultiFileRenderingUtil multiFileUtil;
  55. private StreamResult firstStream;
  56. private StreamResult currentStream;
  57. /** Used for single-page documents rendered to a DOM or SAX. */
  58. private Result simpleResult;
  59. private Document reusedParts;
  60. /**
  61. * Default constructor.
  62. */
  63. public SVGDocumentHandler(IFContext context) {
  64. super(context);
  65. this.multiFileUtil = null;
  66. this.reusedParts = null;
  67. }
  68. /** {@inheritDoc} */
  69. public boolean supportsPagesOutOfOrder() {
  70. return true;
  71. }
  72. /** {@inheritDoc} */
  73. public String getMimeType() {
  74. return MIME_TYPE;
  75. }
  76. /** {@inheritDoc} */
  77. public void setResult(Result result) throws IFException {
  78. if (result instanceof StreamResult) {
  79. multiFileUtil = new MultiFileRenderingUtil(FILE_EXTENSION_SVG,
  80. getUserAgent().getOutputFile());
  81. this.firstStream = (StreamResult)result;
  82. } else {
  83. this.simpleResult = result;
  84. }
  85. }
  86. /** {@inheritDoc} */
  87. public void startDocument() throws IFException {
  88. super.startDocument();
  89. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  90. builderFactory.setNamespaceAware(true);
  91. builderFactory.setValidating(false);
  92. try {
  93. DocumentBuilder builder = builderFactory.newDocumentBuilder();
  94. this.reusedParts = builder.newDocument();
  95. } catch (ParserConfigurationException e) {
  96. throw new IFException("Error while setting up a DOM for SVG generation", e);
  97. }
  98. try {
  99. TransformerHandler toDOMHandler = tFactory.newTransformerHandler();
  100. toDOMHandler.setResult(new DOMResult(this.reusedParts));
  101. this.handler = decorate(toDOMHandler);
  102. this.handler.startDocument();
  103. } catch (SAXException se) {
  104. throw new IFException("SAX error in startDocument()", se);
  105. } catch (TransformerConfigurationException e) {
  106. throw new IFException(
  107. "Error while setting up a TransformerHandler for SVG generation", e);
  108. }
  109. }
  110. /** {@inheritDoc} */
  111. public void endDocument() throws IFException {
  112. //nop
  113. }
  114. /** {@inheritDoc} */
  115. public void endDocumentHeader() throws IFException {
  116. super.endDocumentHeader();
  117. try {
  118. //Stop recording parts reused for each page
  119. this.handler.endDocument();
  120. this.handler = null;
  121. } catch (SAXException e) {
  122. throw new IFException("SAX error in endDocumentHeader()", e);
  123. }
  124. }
  125. /** {@inheritDoc} */
  126. public void startPageSequence(String id) throws IFException {
  127. //nop
  128. }
  129. /** {@inheritDoc} */
  130. public void endPageSequence() throws IFException {
  131. //nop
  132. }
  133. /** {@inheritDoc} */
  134. public void startPage(int index, String name, String pageMasterName, Dimension size)
  135. throws IFException {
  136. if (this.multiFileUtil != null) {
  137. prepareHandlerWithOutputStream(index);
  138. } else {
  139. if (this.simpleResult == null) {
  140. //Only one page is supported with this approach at the moment
  141. throw new IFException(
  142. "Only one page is supported for output with the given Result instance!",
  143. null);
  144. }
  145. super.setResult(this.simpleResult);
  146. this.simpleResult = null;
  147. }
  148. try {
  149. handler.startDocument();
  150. handler.startPrefixMapping("", NAMESPACE);
  151. handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE);
  152. AttributesImpl atts = new AttributesImpl();
  153. XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1
  154. /*
  155. XMLUtil.addAttribute(atts, "index", Integer.toString(index));
  156. XMLUtil.addAttribute(atts, "name", name);
  157. */
  158. XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt");
  159. XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt");
  160. XMLUtil.addAttribute(atts, "viewBox",
  161. "0 0 " + SVGUtil.formatMptToPt(size.width)
  162. + " " + SVGUtil.formatMptToPt(size.height));
  163. handler.startElement("svg", atts);
  164. try {
  165. Transformer transformer = tFactory.newTransformer();
  166. Source src = new DOMSource(this.reusedParts.getDocumentElement());
  167. Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler));
  168. transformer.transform(src, res);
  169. } catch (TransformerConfigurationException tce) {
  170. throw new IFException("Error setting up a Transformer", tce);
  171. } catch (TransformerException te) {
  172. Throwable t = te.getCause();
  173. if (t instanceof SAXException) {
  174. throw (SAXException) t;
  175. } else if (t instanceof Exception) {
  176. throw new IFException("Error while serializing reused parts", (Exception) t);
  177. } else {
  178. throw new RuntimeException(t);
  179. }
  180. }
  181. } catch (SAXException e) {
  182. throw new IFException("SAX error in startPage()", e);
  183. }
  184. }
  185. private void prepareHandlerWithOutputStream(int index) throws IFException {
  186. OutputStream out;
  187. try {
  188. if (index == 0) {
  189. out = null;
  190. } else {
  191. out = this.multiFileUtil.createOutputStream(index);
  192. if (out == null) {
  193. BitmapRendererEventProducer eventProducer
  194. = BitmapRendererEventProducer.Provider.get(
  195. getUserAgent().getEventBroadcaster());
  196. eventProducer.stoppingAfterFirstPageNoFilename(this);
  197. }
  198. }
  199. } catch (IOException ioe) {
  200. throw new IFException("I/O exception while setting up output file", ioe);
  201. }
  202. if (out == null) {
  203. this.handler = decorate(createContentHandler(this.firstStream));
  204. } else {
  205. this.currentStream = new StreamResult(out);
  206. this.handler = decorate(createContentHandler(this.currentStream));
  207. }
  208. }
  209. private GenerationHelperContentHandler decorate(ContentHandler contentHandler) {
  210. return new GenerationHelperContentHandler(contentHandler, getMainNamespace(), getContext());
  211. }
  212. private void closeCurrentStream() {
  213. if (this.currentStream != null) {
  214. IOUtils.closeQuietly(currentStream.getOutputStream());
  215. currentStream.setOutputStream(null);
  216. IOUtils.closeQuietly(currentStream.getWriter());
  217. currentStream.setWriter(null);
  218. this.currentStream = null;
  219. }
  220. }
  221. /** {@inheritDoc} */
  222. public IFPainter startPageContent() throws IFException {
  223. try {
  224. handler.startElement("g");
  225. } catch (SAXException e) {
  226. throw new IFException("SAX error in startPageContent()", e);
  227. }
  228. return new SVGPainter(this, handler);
  229. }
  230. /** {@inheritDoc} */
  231. public void endPageContent() throws IFException {
  232. try {
  233. handler.endElement("g");
  234. } catch (SAXException e) {
  235. throw new IFException("SAX error in endPageContent()", e);
  236. }
  237. }
  238. /** {@inheritDoc} */
  239. public void endPage() throws IFException {
  240. try {
  241. handler.endElement("svg");
  242. this.handler.endDocument();
  243. } catch (SAXException e) {
  244. throw new IFException("SAX error in endPage()", e);
  245. }
  246. closeCurrentStream();
  247. }
  248. }