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.

SVGRenderExtension.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xslf.draw;
  16. import static java.awt.MultipleGradientPaint.ColorSpaceType.LINEAR_RGB;
  17. import static org.apache.batik.svggen.SVGSyntax.ID_PREFIX_IMAGE;
  18. import static org.apache.batik.svggen.SVGSyntax.ID_PREFIX_PATTERN;
  19. import static org.apache.batik.svggen.SVGSyntax.SIGN_POUND;
  20. import static org.apache.batik.svggen.SVGSyntax.URL_PREFIX;
  21. import static org.apache.batik.svggen.SVGSyntax.URL_SUFFIX;
  22. import static org.apache.batik.util.SVGConstants.*;
  23. import static org.apache.poi.sl.usermodel.PictureData.PictureType.GIF;
  24. import static org.apache.poi.sl.usermodel.PictureData.PictureType.JPEG;
  25. import static org.apache.poi.sl.usermodel.PictureData.PictureType.PNG;
  26. import java.awt.Color;
  27. import java.awt.LinearGradientPaint;
  28. import java.awt.MultipleGradientPaint;
  29. import java.awt.Paint;
  30. import java.awt.RadialGradientPaint;
  31. import java.awt.RenderingHints;
  32. import java.awt.Shape;
  33. import java.awt.TexturePaint;
  34. import java.awt.geom.AffineTransform;
  35. import java.awt.geom.Dimension2D;
  36. import java.awt.geom.Point2D;
  37. import java.awt.geom.Rectangle2D;
  38. import java.awt.image.BufferedImage;
  39. import java.awt.image.ColorModel;
  40. import java.awt.image.WritableRaster;
  41. import java.io.IOException;
  42. import java.lang.ref.WeakReference;
  43. import java.nio.charset.StandardCharsets;
  44. import java.util.Base64;
  45. import java.util.HashMap;
  46. import java.util.Map;
  47. import java.util.zip.CRC32;
  48. import javax.imageio.ImageIO;
  49. import org.apache.batik.svggen.DefaultExtensionHandler;
  50. import org.apache.batik.svggen.SVGColor;
  51. import org.apache.batik.svggen.SVGGeneratorContext;
  52. import org.apache.batik.svggen.SVGGraphics2D;
  53. import org.apache.batik.svggen.SVGPaintDescriptor;
  54. import org.apache.batik.svggen.SVGTexturePaint;
  55. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
  56. import org.apache.poi.sl.draw.BitmapImageRenderer;
  57. import org.apache.poi.sl.draw.DrawTexturePaint;
  58. import org.apache.poi.sl.draw.Drawable;
  59. import org.apache.poi.sl.draw.ImageRenderer;
  60. import org.apache.poi.sl.draw.PathGradientPaint;
  61. import org.apache.poi.sl.draw.PathGradientPaint.PathGradientContext;
  62. import org.apache.poi.sl.usermodel.Insets2D;
  63. import org.apache.poi.sl.usermodel.PaintStyle;
  64. import org.apache.poi.sl.usermodel.SimpleShape;
  65. import org.apache.poi.util.Dimension2DDouble;
  66. import org.apache.poi.util.Internal;
  67. import org.w3c.dom.Document;
  68. import org.w3c.dom.Element;
  69. /**
  70. * Extension of Batik's DefaultExtensionHandler which handles different kinds of Paint objects
  71. * <p>
  72. * Taken (with permission) from https://gist.github.com/msteiger/4509119,
  73. * including the fixes that are discussed in the comments
  74. *
  75. * @see <a href="https://issues.apache.org/jira/browse/BATIK-1032">BATIK-1032</a>
  76. */
  77. @Internal
  78. public class SVGRenderExtension extends DefaultExtensionHandler {
  79. private static final int LINE_LENGTH = 65;
  80. private static final String XLINK_NS = "http://www.w3.org/1999/xlink";
  81. private final Map<Long, String> imageMap = new HashMap<>();
  82. private WeakReference<SVGGraphics2D> svgGraphics2D = null;
  83. public SVGGraphics2D getSvgGraphics2D() {
  84. return (svgGraphics2D != null) ? svgGraphics2D.get() : null;
  85. }
  86. public void setSvgGraphics2D(SVGGraphics2D svgGraphics2D) {
  87. this.svgGraphics2D = new WeakReference<>(svgGraphics2D);
  88. }
  89. @Override
  90. public SVGPaintDescriptor handlePaint(Paint paint, SVGGeneratorContext generatorContext) {
  91. if (paint instanceof LinearGradientPaint) {
  92. return getLgpDescriptor((LinearGradientPaint)paint, generatorContext);
  93. }
  94. if (paint instanceof RadialGradientPaint) {
  95. return getRgpDescriptor((RadialGradientPaint)paint, generatorContext);
  96. }
  97. if (paint instanceof PathGradientPaint) {
  98. return getPathDescriptor((PathGradientPaint)paint, generatorContext);
  99. }
  100. if (paint instanceof DrawTexturePaint) {
  101. return getDtpDescriptor((DrawTexturePaint)paint, generatorContext);
  102. }
  103. return super.handlePaint(paint, generatorContext);
  104. }
  105. private SVGPaintDescriptor getPathDescriptor(PathGradientPaint gradient, SVGGeneratorContext genCtx) {
  106. RenderingHints hints = genCtx.getGraphicContextDefaults().getRenderingHints();
  107. Shape shape = (Shape)hints.get(Drawable.GRADIENT_SHAPE);
  108. if (shape == null) {
  109. return null;
  110. }
  111. PathGradientContext context = gradient.createContext(ColorModel.getRGBdefault(), shape.getBounds(), shape.getBounds2D(), new AffineTransform(), hints);
  112. WritableRaster raster = context.createRaster();
  113. BufferedImage img = new BufferedImage(context.getColorModel(), raster, false, null);
  114. SVGTexturePaint texturePaint = new SVGTexturePaint(genCtx);
  115. TexturePaint tp = new TexturePaint(img, shape.getBounds2D());
  116. return texturePaint.toSVG(tp);
  117. }
  118. private SVGPaintDescriptor getRgpDescriptor(RadialGradientPaint gradient, SVGGeneratorContext genCtx) {
  119. Element gradElem = genCtx.getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_RADIAL_GRADIENT_TAG);
  120. // Create and set unique XML id
  121. String id = genCtx.getIDGenerator().generateID("gradient");
  122. gradElem.setAttribute(SVG_ID_ATTRIBUTE, id);
  123. // Set x,y pairs
  124. setPoint(gradElem, gradient.getCenterPoint(), "cx", "cy");
  125. setPoint(gradElem, gradient.getFocusPoint(), "fx", "fy");
  126. gradElem.setAttribute("r", String.valueOf(gradient.getRadius()));
  127. addMgpAttributes(gradElem, genCtx, gradient);
  128. return new SVGPaintDescriptor("url(#" + id + ")", SVG_OPAQUE_VALUE, gradElem);
  129. }
  130. private SVGPaintDescriptor getLgpDescriptor(LinearGradientPaint gradient, SVGGeneratorContext genCtx) {
  131. Element gradElem = genCtx.getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_LINEAR_GRADIENT_TAG);
  132. // Create and set unique XML id
  133. String id = genCtx.getIDGenerator().generateID("gradient");
  134. gradElem.setAttribute(SVG_ID_ATTRIBUTE, id);
  135. // Set x,y pairs
  136. setPoint(gradElem, gradient.getStartPoint(), "x1", "y1");
  137. setPoint(gradElem, gradient.getEndPoint(), "x2", "y2");
  138. addMgpAttributes(gradElem, genCtx, gradient);
  139. return new SVGPaintDescriptor("url(#" + id + ")", SVG_OPAQUE_VALUE, gradElem);
  140. }
  141. private void addMgpAttributes(Element gradElem, SVGGeneratorContext genCtx, MultipleGradientPaint gradient) {
  142. gradElem.setAttribute(SVG_GRADIENT_UNITS_ATTRIBUTE, SVG_USER_SPACE_ON_USE_VALUE);
  143. // Set cycle method
  144. final String cycleVal;
  145. switch (gradient.getCycleMethod()) {
  146. case REFLECT:
  147. cycleVal = SVG_REFLECT_VALUE;
  148. break;
  149. case REPEAT:
  150. cycleVal = SVG_REPEAT_VALUE;
  151. break;
  152. case NO_CYCLE:
  153. default:
  154. cycleVal = SVG_PAD_VALUE;
  155. break;
  156. }
  157. gradElem.setAttribute(SVG_SPREAD_METHOD_ATTRIBUTE, cycleVal);
  158. // Set color space
  159. final String colorSpace = (gradient.getColorSpace() == LINEAR_RGB) ? SVG_LINEAR_RGB_VALUE : SVG_SRGB_VALUE;
  160. gradElem.setAttribute(SVG_COLOR_INTERPOLATION_ATTRIBUTE, colorSpace);
  161. // Set transform matrix if not identity
  162. AffineTransform tf = gradient.getTransform();
  163. if (!tf.isIdentity()) {
  164. String matrix = "matrix(" + tf.getScaleX() + " " + tf.getShearY()
  165. + " " + tf.getShearX() + " " + tf.getScaleY() + " "
  166. + tf.getTranslateX() + " " + tf.getTranslateY() + ")";
  167. gradElem.setAttribute(SVG_GRADIENT_TRANSFORM_ATTRIBUTE, matrix);
  168. }
  169. // Convert gradient stops
  170. final Color[] colors = gradient.getColors();
  171. final float[] fracs = gradient.getFractions();
  172. for (int i = 0; i < colors.length; i++) {
  173. Element stop = genCtx.getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_STOP_TAG);
  174. SVGPaintDescriptor pd = SVGColor.toSVG(colors[i], genCtx);
  175. stop.setAttribute(SVG_OFFSET_ATTRIBUTE, (int) (fracs[i] * 100.0f) + "%");
  176. stop.setAttribute(SVG_STOP_COLOR_ATTRIBUTE, pd.getPaintValue());
  177. if (colors[i].getAlpha() != 255) {
  178. stop.setAttribute(SVG_STOP_OPACITY_ATTRIBUTE, pd.getOpacityValue());
  179. }
  180. gradElem.appendChild(stop);
  181. }
  182. }
  183. private static void setPoint(Element gradElem, Point2D point, String x, String y) {
  184. gradElem.setAttribute(x, Double.toString(point.getX()));
  185. gradElem.setAttribute(y, Double.toString(point.getY()));
  186. }
  187. private SVGPaintDescriptor getDtpDescriptor(DrawTexturePaint tdp, SVGGeneratorContext genCtx) {
  188. String imgID = getImageID(tdp, genCtx);
  189. Document domFactory = genCtx.getDOMFactory();
  190. Element patternDef = domFactory.createElementNS(SVG_NAMESPACE_URI, SVG_PATTERN_TAG);
  191. String patID = genCtx.getIDGenerator().generateID(ID_PREFIX_PATTERN);
  192. PaintStyle.TexturePaint fill = tdp.getFill();
  193. Insets2D stretch = fill.getStretch();
  194. if (stretch == null) {
  195. stretch = new Insets2D(0,0,0,0);
  196. }
  197. Rectangle2D anchorRect = tdp.getAnchorRect();
  198. String x = genCtx.doubleString(-stretch.left/100_000 * anchorRect.getWidth());
  199. String y = genCtx.doubleString(-stretch.top/100_000 * anchorRect.getHeight());
  200. String w = genCtx.doubleString((100_000+stretch.left+stretch.right)/100_000 * anchorRect.getWidth());
  201. String h = genCtx.doubleString((100_000+stretch.top+stretch.bottom)/100_000 * anchorRect.getHeight());
  202. Dimension2D scale = fill.getScale();
  203. if (scale == null) {
  204. scale = new Dimension2DDouble(1,1);
  205. }
  206. Point2D offset = fill.getOffset();
  207. if (offset == null) {
  208. offset = new Point2D.Double(0,0);
  209. }
  210. PaintStyle.FlipMode flipMode = fill.getFlipMode();
  211. if (flipMode == null) {
  212. flipMode = PaintStyle.FlipMode.NONE;
  213. }
  214. setAttribute(genCtx, patternDef,
  215. null, SVG_PATTERN_UNITS_ATTRIBUTE, SVG_OBJECT_BOUNDING_BOX_VALUE,
  216. null, SVG_ID_ATTRIBUTE, patID,
  217. null, SVG_X_ATTRIBUTE, offset.getX(),
  218. null, SVG_Y_ATTRIBUTE, offset.getY(),
  219. null, SVG_WIDTH_ATTRIBUTE, genCtx.doubleString(scale.getWidth()*100)+"%",
  220. null, SVG_HEIGHT_ATTRIBUTE, genCtx.doubleString(scale.getHeight()*100)+"%",
  221. null, SVG_PRESERVE_ASPECT_RATIO_ATTRIBUTE, SVG_NONE_VALUE,
  222. null, SVG_VIEW_BOX_ATTRIBUTE, x+" "+ y+" "+ w+" "+h
  223. );
  224. org.apache.poi.sl.usermodel.Shape<?,?> slShape = fill.getShape();
  225. // TODO: the rotation handling is incomplete and the scale handling is missing
  226. // see DrawTexturePaint on how to do it for AWT
  227. if (!fill.isRotatedWithShape() && slShape instanceof SimpleShape) {
  228. double rot = ((SimpleShape<?,?>)slShape).getRotation();
  229. if (rot != 0) {
  230. setAttribute(genCtx, patternDef,
  231. null, SVG_PATTERN_TRANSFORM_ATTRIBUTE, "rotate(" + genCtx.doubleString(-rot) + ")");
  232. }
  233. }
  234. Element useImageEl = domFactory.createElementNS(SVG_NAMESPACE_URI, SVG_USE_TAG);
  235. useImageEl.setAttributeNS(null, "href", "#"+imgID);
  236. patternDef.appendChild(useImageEl);
  237. String patternAttrBuf = URL_PREFIX + SIGN_POUND + patID + URL_SUFFIX;
  238. return new SVGPaintDescriptor(patternAttrBuf, SVG_OPAQUE_VALUE, patternDef);
  239. }
  240. private String getImageID(DrawTexturePaint tdp, SVGGeneratorContext genCtx) {
  241. final ImageRenderer imgRdr = tdp.getImageRenderer();
  242. byte[] imgData = null;
  243. String contentType = null;
  244. if (imgRdr instanceof BitmapImageRenderer) {
  245. BitmapImageRenderer bir = (BitmapImageRenderer)imgRdr;
  246. String ct = bir.getCachedContentType();
  247. if (PNG.contentType.equals(ct) ||
  248. JPEG.contentType.equals(ct) ||
  249. GIF.contentType.equals(ct)) {
  250. contentType = ct;
  251. imgData = bir.getCachedImage();
  252. }
  253. }
  254. if (imgData == null) {
  255. BufferedImage bi = imgRdr.getImage();
  256. UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
  257. try {
  258. ImageIO.write(bi, "PNG", bos);
  259. } catch (IOException e) {
  260. return null;
  261. }
  262. imgData = bos.toByteArray();
  263. contentType = PNG.contentType;
  264. }
  265. CRC32 crc = new CRC32();
  266. crc.update(imgData);
  267. Long imageCrc = crc.getValue();
  268. String imgID = imageMap.get(imageCrc);
  269. if (imgID != null) {
  270. return imgID;
  271. }
  272. Document domFactory = genCtx.getDOMFactory();
  273. Rectangle2D anchorRect = tdp.getAnchorRect();
  274. imgID = genCtx.getIDGenerator().generateID(ID_PREFIX_IMAGE);
  275. imageMap.put(imageCrc, imgID);
  276. // length of a base64 string
  277. int sbLen = ((4 * imgData.length / 3) + 3) & ~3;
  278. // add line breaks every 65 chars and a few more padding chars
  279. sbLen += sbLen / LINE_LENGTH + 30;
  280. StringBuilder sb = new StringBuilder(sbLen);
  281. sb.append("data:");
  282. sb.append(contentType);
  283. sb.append(";base64,\n");
  284. sb.append(Base64.getMimeEncoder(LINE_LENGTH, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(imgData));
  285. Element imageEl = domFactory.createElementNS(SVG_NAMESPACE_URI, SVG_IMAGE_TAG);
  286. setAttribute(genCtx, imageEl,
  287. null, SVG_ID_ATTRIBUTE, imgID,
  288. null, SVG_PRESERVE_ASPECT_RATIO_ATTRIBUTE, SVG_NONE_VALUE,
  289. null, SVG_X_ATTRIBUTE, anchorRect.getX(),
  290. null, SVG_Y_ATTRIBUTE, anchorRect.getY(),
  291. null, SVG_WIDTH_ATTRIBUTE, anchorRect.getWidth(),
  292. null, SVG_HEIGHT_ATTRIBUTE, anchorRect.getHeight(),
  293. XLINK_NS, "xlink:href", sb.toString()
  294. );
  295. getSvgGraphics2D().getDOMTreeManager().addOtherDef(imageEl);
  296. return imgID;
  297. }
  298. private static void setAttribute(SVGGeneratorContext genCtx, Element el, Object... params) {
  299. for (int i=0; i<params.length; i+=3) {
  300. String ns = (String)params[i];
  301. String name = (String)params[i+1];
  302. Object oval = params[i+2];
  303. String val;
  304. if (oval instanceof String) {
  305. val = (String)oval;
  306. } else if (oval instanceof Number) {
  307. val = genCtx.doubleString(((Number) oval).doubleValue());
  308. } else if (oval == null) {
  309. val = "";
  310. } else {
  311. val = oval.toString();
  312. }
  313. el.setAttributeNS(ns, name, val);
  314. }
  315. }
  316. }