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

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