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.

SVGPainter.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Paint;
  22. import java.awt.Point;
  23. import java.awt.Rectangle;
  24. import java.awt.geom.AffineTransform;
  25. import java.io.FileNotFoundException;
  26. import java.io.IOException;
  27. import java.util.Map;
  28. import org.w3c.dom.Document;
  29. import org.xml.sax.SAXException;
  30. import org.xml.sax.helpers.AttributesImpl;
  31. import org.apache.xmlgraphics.image.loader.ImageException;
  32. import org.apache.xmlgraphics.image.loader.ImageInfo;
  33. import org.apache.xmlgraphics.image.loader.ImageManager;
  34. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  35. import org.apache.xmlgraphics.xmp.Metadata;
  36. import org.apache.fop.ResourceEventProducer;
  37. import org.apache.fop.apps.MimeConstants;
  38. import org.apache.fop.render.ImageHandlerUtil;
  39. import org.apache.fop.render.RenderingContext;
  40. import org.apache.fop.render.intermediate.AbstractIFPainter;
  41. import org.apache.fop.render.intermediate.IFConstants;
  42. import org.apache.fop.render.intermediate.IFException;
  43. import org.apache.fop.render.intermediate.IFState;
  44. import org.apache.fop.render.intermediate.IFUtil;
  45. import org.apache.fop.traits.BorderProps;
  46. import org.apache.fop.traits.RuleStyle;
  47. import org.apache.fop.util.ColorUtil;
  48. import org.apache.fop.util.GenerationHelperContentHandler;
  49. import org.apache.fop.util.XMLConstants;
  50. import org.apache.fop.util.XMLUtil;
  51. /**
  52. * IFPainter implementation that writes SVG.
  53. */
  54. public class SVGPainter extends AbstractIFPainter<AbstractSVGDocumentHandler>
  55. implements SVGConstants {
  56. /** The SAX content handler that receives the generated XML events. */
  57. private GenerationHelperContentHandler handler;
  58. private static final int MODE_NORMAL = 0;
  59. private static final int MODE_TEXT = 1;
  60. private int mode = MODE_NORMAL;
  61. /**
  62. * Main constructor.
  63. * @param parent the parent document handler
  64. * @param contentHandler the target SAX content handler
  65. */
  66. public SVGPainter(AbstractSVGDocumentHandler parent,
  67. GenerationHelperContentHandler contentHandler) {
  68. super(parent);
  69. this.handler = contentHandler;
  70. this.state = IFState.create();
  71. }
  72. /** {@inheritDoc} */
  73. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  74. throws IFException {
  75. startViewport(SVGUtil.formatAffineTransformMptToPt(transform), size, clipRect);
  76. }
  77. /** {@inheritDoc} */
  78. public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect)
  79. throws IFException {
  80. startViewport(SVGUtil.formatAffineTransformsMptToPt(transforms), size, clipRect);
  81. }
  82. private void startViewport(String transform, Dimension size, Rectangle clipRect)
  83. throws IFException {
  84. try {
  85. establish(MODE_NORMAL);
  86. AttributesImpl atts = new AttributesImpl();
  87. if (transform != null && transform.length() > 0) {
  88. XMLUtil.addAttribute(atts, "transform", transform);
  89. }
  90. handler.startElement("g", atts);
  91. atts.clear();
  92. XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width));
  93. XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height));
  94. if (clipRect != null) {
  95. int[] v = new int[] {
  96. clipRect.y,
  97. -clipRect.x + size.width - clipRect.width,
  98. -clipRect.y + size.height - clipRect.height,
  99. clipRect.x};
  100. int sum = 0;
  101. for (int i = 0; i < 4; i++) {
  102. sum += Math.abs(v[i]);
  103. }
  104. if (sum != 0) {
  105. StringBuffer sb = new StringBuffer("rect(");
  106. sb.append(SVGUtil.formatMptToPt(v[0])).append(',');
  107. sb.append(SVGUtil.formatMptToPt(v[1])).append(',');
  108. sb.append(SVGUtil.formatMptToPt(v[2])).append(',');
  109. sb.append(SVGUtil.formatMptToPt(v[3])).append(')');
  110. XMLUtil.addAttribute(atts, "clip", sb.toString());
  111. }
  112. XMLUtil.addAttribute(atts, "overflow", "hidden");
  113. } else {
  114. XMLUtil.addAttribute(atts, "overflow", "visible");
  115. }
  116. handler.startElement("svg", atts);
  117. } catch (SAXException e) {
  118. throw new IFException("SAX error in startBox()", e);
  119. }
  120. }
  121. /** {@inheritDoc} */
  122. public void endViewport() throws IFException {
  123. try {
  124. establish(MODE_NORMAL);
  125. handler.endElement("svg");
  126. handler.endElement("g");
  127. } catch (SAXException e) {
  128. throw new IFException("SAX error in endBox()", e);
  129. }
  130. }
  131. /** {@inheritDoc} */
  132. public void startGroup(AffineTransform[] transforms) throws IFException {
  133. startGroup(SVGUtil.formatAffineTransformsMptToPt(transforms));
  134. }
  135. /** {@inheritDoc} */
  136. public void startGroup(AffineTransform transform) throws IFException {
  137. startGroup(SVGUtil.formatAffineTransformMptToPt(transform));
  138. }
  139. private void startGroup(String transform) throws IFException {
  140. try {
  141. AttributesImpl atts = new AttributesImpl();
  142. if (transform != null && transform.length() > 0) {
  143. XMLUtil.addAttribute(atts, "transform", transform);
  144. }
  145. handler.startElement("g", atts);
  146. } catch (SAXException e) {
  147. throw new IFException("SAX error in startGroup()", e);
  148. }
  149. }
  150. /** {@inheritDoc} */
  151. public void endGroup() throws IFException {
  152. try {
  153. establish(MODE_NORMAL);
  154. handler.endElement("g");
  155. } catch (SAXException e) {
  156. throw new IFException("SAX error in endGroup()", e);
  157. }
  158. }
  159. /** {@inheritDoc} */
  160. public void drawImage(String uri, Rectangle rect) throws IFException {
  161. try {
  162. establish(MODE_NORMAL);
  163. ImageManager manager = getUserAgent().getFactory().getImageManager();
  164. ImageInfo info = null;
  165. try {
  166. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  167. info = manager.getImageInfo(uri, sessionContext);
  168. String mime = info.getMimeType();
  169. Map foreignAttributes = getContext().getForeignAttributes();
  170. String conversionMode = (String)foreignAttributes.get(
  171. ImageHandlerUtil.CONVERSION_MODE);
  172. if ("reference".equals(conversionMode)
  173. && (MimeConstants.MIME_GIF.equals(mime)
  174. || MimeConstants.MIME_JPEG.equals(mime)
  175. || MimeConstants.MIME_PNG.equals(mime)
  176. || MimeConstants.MIME_SVG.equals(mime))) {
  177. //Just reference the image
  178. //TODO Some additional URI rewriting might be necessary
  179. AttributesImpl atts = new AttributesImpl();
  180. XMLUtil.addAttribute(atts, IFConstants.XLINK_HREF, uri);
  181. XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x));
  182. XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y));
  183. XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width));
  184. XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height));
  185. handler.element("image", atts);
  186. } else {
  187. drawImageUsingImageHandler(info, rect);
  188. }
  189. } catch (ImageException ie) {
  190. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  191. getUserAgent().getEventBroadcaster());
  192. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  193. } catch (FileNotFoundException fe) {
  194. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  195. getUserAgent().getEventBroadcaster());
  196. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  197. } catch (IOException ioe) {
  198. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  199. getUserAgent().getEventBroadcaster());
  200. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  201. }
  202. } catch (SAXException e) {
  203. throw new IFException("SAX error in drawImage()", e);
  204. }
  205. }
  206. /** {@inheritDoc} */
  207. public void drawImage(Document doc, Rectangle rect) throws IFException {
  208. try {
  209. establish(MODE_NORMAL);
  210. drawImageUsingDocument(doc, rect);
  211. } catch (SAXException e) {
  212. throw new IFException("SAX error in drawImage()", e);
  213. }
  214. }
  215. /** {@inheritDoc} */
  216. protected RenderingContext createRenderingContext() {
  217. SVGRenderingContext svgContext = new SVGRenderingContext(
  218. getUserAgent(), handler);
  219. return svgContext;
  220. }
  221. private static String toString(Paint paint) {
  222. //TODO Paint serialization: Fine-tune and extend!
  223. if (paint instanceof Color) {
  224. return ColorUtil.colorToString((Color)paint);
  225. } else {
  226. throw new UnsupportedOperationException("Paint not supported: " + paint);
  227. }
  228. }
  229. /** {@inheritDoc} */
  230. public void clipRect(Rectangle rect) throws IFException {
  231. //TODO Implement me!!!
  232. }
  233. /** {@inheritDoc} */
  234. public void fillRect(Rectangle rect, Paint fill) throws IFException {
  235. if (fill == null) {
  236. return;
  237. }
  238. try {
  239. establish(MODE_NORMAL);
  240. AttributesImpl atts = new AttributesImpl();
  241. XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x));
  242. XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y));
  243. XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width));
  244. XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height));
  245. if (fill != null) {
  246. XMLUtil.addAttribute(atts, "fill", toString(fill));
  247. }
  248. /* disabled
  249. if (stroke != null) {
  250. XMLUtil.addAttribute(atts, "stroke", toString(stroke));
  251. }*/
  252. handler.element("rect", atts);
  253. } catch (SAXException e) {
  254. throw new IFException("SAX error in fillRect()", e);
  255. }
  256. }
  257. /** {@inheritDoc} */
  258. public void drawBorderRect(Rectangle rect, BorderProps before, BorderProps after,
  259. BorderProps start, BorderProps end) throws IFException {
  260. // TODO Auto-generated method stub
  261. }
  262. /** {@inheritDoc} */
  263. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  264. throws IFException {
  265. try {
  266. establish(MODE_NORMAL);
  267. AttributesImpl atts = new AttributesImpl();
  268. XMLUtil.addAttribute(atts, "x1", SVGUtil.formatMptToPt(start.x));
  269. XMLUtil.addAttribute(atts, "y1", SVGUtil.formatMptToPt(start.y));
  270. XMLUtil.addAttribute(atts, "x2", SVGUtil.formatMptToPt(end.x));
  271. XMLUtil.addAttribute(atts, "y2", SVGUtil.formatMptToPt(end.y));
  272. XMLUtil.addAttribute(atts, "stroke-width", toString(color));
  273. XMLUtil.addAttribute(atts, "fill", toString(color));
  274. //TODO Handle style parameter
  275. handler.element("line", atts);
  276. } catch (SAXException e) {
  277. throw new IFException("SAX error in drawLine()", e);
  278. }
  279. }
  280. /** {@inheritDoc} */
  281. public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp,
  282. String text) throws IFException {
  283. try {
  284. establish(MODE_TEXT);
  285. AttributesImpl atts = new AttributesImpl();
  286. XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve");
  287. XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(x));
  288. XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(y));
  289. if (letterSpacing != 0) {
  290. XMLUtil.addAttribute(atts, "letter-spacing", SVGUtil.formatMptToPt(letterSpacing));
  291. }
  292. if (wordSpacing != 0) {
  293. XMLUtil.addAttribute(atts, "word-spacing", SVGUtil.formatMptToPt(wordSpacing));
  294. }
  295. if (dp != null) {
  296. int[] dx = IFUtil.convertDPToDX(dp);
  297. XMLUtil.addAttribute(atts, "dx", SVGUtil.formatMptArrayToPt(dx));
  298. }
  299. handler.startElement("text", atts);
  300. char[] chars = text.toCharArray();
  301. handler.characters(chars, 0, chars.length);
  302. handler.endElement("text");
  303. } catch (SAXException e) {
  304. throw new IFException("SAX error in setFont()", e);
  305. }
  306. }
  307. private void leaveTextMode() throws SAXException {
  308. assert this.mode == MODE_TEXT;
  309. handler.endElement("g");
  310. this.mode = MODE_NORMAL;
  311. }
  312. private void establish(int newMode) throws SAXException {
  313. switch (newMode) {
  314. case MODE_TEXT:
  315. enterTextMode();
  316. break;
  317. default:
  318. if (this.mode == MODE_TEXT) {
  319. leaveTextMode();
  320. }
  321. }
  322. }
  323. private void enterTextMode() throws SAXException {
  324. if (state.isFontChanged() && this.mode == MODE_TEXT) {
  325. leaveTextMode();
  326. }
  327. if (this.mode != MODE_TEXT) {
  328. startTextGroup();
  329. this.mode = MODE_TEXT;
  330. }
  331. }
  332. private void startTextGroup() throws SAXException {
  333. AttributesImpl atts = new AttributesImpl();
  334. XMLUtil.addAttribute(atts, "font-family", "'" + state.getFontFamily() + "'");
  335. XMLUtil.addAttribute(atts, "font-style", state.getFontStyle());
  336. XMLUtil.addAttribute(atts, "font-weight", Integer.toString(state.getFontWeight()));
  337. XMLUtil.addAttribute(atts, "font-variant", state.getFontVariant());
  338. XMLUtil.addAttribute(atts, "font-size", SVGUtil.formatMptToPt(state.getFontSize()));
  339. XMLUtil.addAttribute(atts, "fill", toString(state.getTextColor()));
  340. handler.startElement("g", atts);
  341. state.resetFontChanged();
  342. }
  343. /**
  344. * @param extension an extension object
  345. * @throws IFException if not caught
  346. */
  347. public void handleExtensionObject(Object extension) throws IFException {
  348. if (extension instanceof Metadata) {
  349. Metadata meta = (Metadata)extension;
  350. try {
  351. establish(MODE_NORMAL);
  352. handler.startElement("metadata");
  353. meta.toSAX(this.handler);
  354. handler.endElement("metadata");
  355. } catch (SAXException e) {
  356. throw new IFException("SAX error while handling extension object", e);
  357. }
  358. } else {
  359. throw new UnsupportedOperationException(
  360. "Don't know how to handle extension object: " + extension);
  361. }
  362. }
  363. }