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.

EscherGraphics.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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.hssf.usermodel;
  16. import org.apache.logging.log4j.LogManager;
  17. import org.apache.logging.log4j.Logger;
  18. import org.apache.poi.hssf.util.HSSFColor;
  19. import org.apache.poi.util.NotImplemented;
  20. import org.apache.poi.util.SuppressForbidden;
  21. import java.awt.*;
  22. import java.awt.image.ImageObserver;
  23. import java.text.AttributedCharacterIterator;
  24. /**
  25. * Translates Graphics calls into escher calls. The translation is lossy so
  26. * many features are not supported and some just aren't implemented yet. If
  27. * in doubt test the specific calls you wish to make. Graphics calls are
  28. * always performed into an EscherGroup so one will need to be created.
  29. * <p>
  30. * <b>Important:</b>
  31. * <blockquote>
  32. * One important concept worth considering is that of font size. One of the
  33. * difficulties in converting Graphics calls into escher drawing calls is that
  34. * Excel does not have the concept of absolute pixel positions. It measures
  35. * it's cell widths in 'characters' and the cell heights in points.
  36. * Unfortunately it's not defined exactly what a type of character it's
  37. * measuring. Presumably this is due to the fact that the Excel will be
  38. * using different fonts on different platforms or even within the same
  39. * platform.
  40. * <p>
  41. * Because of this constraint we've had to calculate the
  42. * verticalPointsPerPixel. This the amount the font should be scaled by when
  43. * you issue commands such as drawString(). A good way to calculate this
  44. * is to use the follow formula:
  45. * <p>
  46. * <pre>
  47. * multipler = groupHeightInPoints / heightOfGroup
  48. * </pre>
  49. * <p>
  50. * The height of the group is calculated fairly simply by calculating the
  51. * difference between the y coordinates of the bounding box of the shape. The
  52. * height of the group can be calculated by using a convenience called
  53. * <code>HSSFClientAnchor.getAnchorHeightInPoints()</code>.
  54. * </blockquote>
  55. */
  56. public class EscherGraphics extends Graphics {
  57. private static final Logger LOG = LogManager.getLogger(EscherGraphics.class);
  58. private final HSSFShapeGroup escherGroup;
  59. private final HSSFWorkbook workbook;
  60. private float verticalPointsPerPixel = 1.0f;
  61. private final float verticalPixelsPerPoint;
  62. private Color foreground;
  63. private Color background = Color.white;
  64. private Font font;
  65. /**
  66. * Construct an escher graphics object.
  67. *
  68. * @param escherGroup The escher group to write the graphics calls into.
  69. * @param workbook The workbook we are using.
  70. * @param forecolor The foreground color to use as default.
  71. * @param verticalPointsPerPixel The font multiplier. (See class description for information on how this works.).
  72. */
  73. public EscherGraphics(HSSFShapeGroup escherGroup, HSSFWorkbook workbook, Color forecolor, float verticalPointsPerPixel )
  74. {
  75. this.escherGroup = escherGroup;
  76. this.workbook = workbook;
  77. this.verticalPointsPerPixel = verticalPointsPerPixel;
  78. this.verticalPixelsPerPoint = 1 / verticalPointsPerPixel;
  79. this.font = new Font("Arial", 0, 10);
  80. this.foreground = forecolor;
  81. // background = backcolor;
  82. }
  83. /**
  84. * Constructs an escher graphics object.
  85. *
  86. * @param escherGroup The escher group to write the graphics calls into.
  87. * @param workbook The workbook we are using.
  88. * @param foreground The foreground color to use as default.
  89. * @param verticalPointsPerPixel The font multiplier. (See class description for information on how this works.).
  90. * @param font The font to use.
  91. */
  92. EscherGraphics( HSSFShapeGroup escherGroup, HSSFWorkbook workbook, Color foreground, Font font, float verticalPointsPerPixel )
  93. {
  94. this.escherGroup = escherGroup;
  95. this.workbook = workbook;
  96. this.foreground = foreground;
  97. // this.background = background;
  98. this.font = font;
  99. this.verticalPointsPerPixel = verticalPointsPerPixel;
  100. this.verticalPixelsPerPoint = 1 / verticalPointsPerPixel;
  101. }
  102. // /**
  103. // * Constructs an escher graphics object.
  104. // *
  105. // * @param escherGroup The escher group to write the graphics calls into.
  106. // * @param workbook The workbook we are using.
  107. // * @param forecolor The default foreground color.
  108. // */
  109. // public EscherGraphics( HSSFShapeGroup escherGroup, HSSFWorkbook workbook, Color forecolor)
  110. // {
  111. // this(escherGroup, workbook, forecolor, 1.0f);
  112. // }
  113. @Override
  114. public void clearRect(int x, int y, int width, int height)
  115. {
  116. Color color = foreground;
  117. setColor(background);
  118. fillRect(x,y,width,height);
  119. setColor(color);
  120. }
  121. @Override
  122. @NotImplemented
  123. public void clipRect(int x, int y, int width, int height)
  124. {
  125. LOG.atWarn().log("clipRect not supported");
  126. }
  127. @Override
  128. @NotImplemented
  129. public void copyArea(int x, int y, int width, int height, int dx, int dy)
  130. {
  131. LOG.atWarn().log("copyArea not supported");
  132. }
  133. @Override
  134. public Graphics create()
  135. {
  136. return new EscherGraphics(escherGroup, workbook,
  137. foreground, font, verticalPointsPerPixel );
  138. }
  139. @Override
  140. public void dispose()
  141. {
  142. }
  143. @Override
  144. @NotImplemented
  145. public void drawArc(int x, int y, int width, int height,
  146. int startAngle, int arcAngle)
  147. {
  148. LOG.atWarn().log("drawArc not supported");
  149. }
  150. @Override
  151. @NotImplemented
  152. public boolean drawImage(Image img,
  153. int dx1, int dy1, int dx2, int dy2,
  154. int sx1, int sy1, int sx2, int sy2,
  155. Color bgcolor,
  156. ImageObserver observer)
  157. {
  158. LOG.atWarn().log("drawImage not supported");
  159. return true;
  160. }
  161. @Override
  162. @NotImplemented
  163. public boolean drawImage(Image img,
  164. int dx1, int dy1, int dx2, int dy2,
  165. int sx1, int sy1, int sx2, int sy2,
  166. ImageObserver observer)
  167. {
  168. LOG.atWarn().log("drawImage not supported");
  169. return true;
  170. }
  171. @Override
  172. public boolean drawImage(Image image, int i, int j, int k, int l, Color color, ImageObserver imageobserver)
  173. {
  174. return drawImage(image, i, j, i + k, j + l, 0, 0, image.getWidth(imageobserver), image.getHeight(imageobserver), color, imageobserver);
  175. }
  176. @Override
  177. public boolean drawImage(Image image, int i, int j, int k, int l, ImageObserver imageobserver)
  178. {
  179. return drawImage(image, i, j, i + k, j + l, 0, 0, image.getWidth(imageobserver), image.getHeight(imageobserver), imageobserver);
  180. }
  181. @Override
  182. public boolean drawImage(Image image, int i, int j, Color color, ImageObserver imageobserver)
  183. {
  184. return drawImage(image, i, j, image.getWidth(imageobserver), image.getHeight(imageobserver), color, imageobserver);
  185. }
  186. @Override
  187. public boolean drawImage(Image image, int i, int j, ImageObserver imageobserver)
  188. {
  189. return drawImage(image, i, j, image.getWidth(imageobserver), image.getHeight(imageobserver), imageobserver);
  190. }
  191. @Override
  192. public void drawLine(int x1, int y1, int x2, int y2)
  193. {
  194. drawLine(x1,y1,x2,y2,0);
  195. }
  196. public void drawLine(int x1, int y1, int x2, int y2, int width)
  197. {
  198. HSSFSimpleShape shape = escherGroup.createShape(new HSSFChildAnchor(x1, y1, x2, y2) );
  199. shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
  200. shape.setLineWidth(width);
  201. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  202. }
  203. @Override
  204. public void drawOval(int x, int y, int width, int height)
  205. {
  206. HSSFSimpleShape shape = escherGroup.createShape(new HSSFChildAnchor(x,y,x+width,y+height) );
  207. shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
  208. shape.setLineWidth(0);
  209. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  210. shape.setNoFill(true);
  211. }
  212. @Override
  213. public void drawPolygon(int[] xPoints, int[] yPoints,
  214. int nPoints)
  215. {
  216. int right = findBiggest(xPoints);
  217. int bottom = findBiggest(yPoints);
  218. int left = findSmallest(xPoints);
  219. int top = findSmallest(yPoints);
  220. HSSFPolygon shape = escherGroup.createPolygon(new HSSFChildAnchor(left,top,right,bottom) );
  221. shape.setPolygonDrawArea(right - left, bottom - top);
  222. shape.setPoints(addToAll(xPoints, -left), addToAll(yPoints, -top));
  223. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  224. shape.setLineWidth(0);
  225. shape.setNoFill(true);
  226. }
  227. private int[] addToAll( int[] values, int amount )
  228. {
  229. int[] result = new int[values.length];
  230. for ( int i = 0; i < values.length; i++ )
  231. result[i] = values[i] + amount;
  232. return result;
  233. }
  234. @Override
  235. @NotImplemented
  236. public void drawPolyline(int[] xPoints, int[] yPoints,
  237. int nPoints)
  238. {
  239. LOG.atWarn().log("drawPolyline not supported");
  240. }
  241. @Override
  242. @NotImplemented
  243. public void drawRect(int x, int y, int width, int height)
  244. {
  245. LOG.atWarn().log("drawRect not supported");
  246. }
  247. @Override
  248. @NotImplemented
  249. public void drawRoundRect(int x, int y, int width, int height,
  250. int arcWidth, int arcHeight)
  251. {
  252. LOG.atWarn().log("drawRoundRect not supported");
  253. }
  254. @Override
  255. public void drawString(String str, int x, int y)
  256. {
  257. if (str == null || str.isEmpty())
  258. return;
  259. Font excelFont = font;
  260. if ( font.getName().equals( "SansSerif" ) )
  261. {
  262. excelFont = new Font( "Arial", font.getStyle(), (int) ( font.getSize() / verticalPixelsPerPoint ) );
  263. }
  264. else
  265. {
  266. excelFont = new Font( font.getName(), font.getStyle(), (int) ( font.getSize() / verticalPixelsPerPoint ));
  267. }
  268. FontDetails d = StaticFontMetrics.getFontDetails( excelFont );
  269. int width = d.getStringWidth( str ) * 8 + 12;
  270. int height = (int) ( ( font.getSize() / verticalPixelsPerPoint ) + 6 ) * 2;
  271. y -= ( font.getSize() / verticalPixelsPerPoint ) + 2 * verticalPixelsPerPoint; // we want to draw the shape from the top-left
  272. HSSFTextbox textbox = escherGroup.createTextbox( new HSSFChildAnchor( x, y, x + width, y + height ) );
  273. textbox.setNoFill( true );
  274. textbox.setLineStyle( HSSFShape.LINESTYLE_NONE );
  275. HSSFRichTextString s = new HSSFRichTextString( str );
  276. HSSFFont hssfFont = matchFont( excelFont );
  277. s.applyFont( hssfFont );
  278. textbox.setString( s );
  279. }
  280. private HSSFFont matchFont( Font matchFont )
  281. {
  282. HSSFColor hssfColor = workbook.getCustomPalette()
  283. .findColor((byte)foreground.getRed(), (byte)foreground.getGreen(), (byte)foreground.getBlue());
  284. if (hssfColor == null)
  285. hssfColor = workbook.getCustomPalette().findSimilarColor((byte)foreground.getRed(), (byte)foreground.getGreen(), (byte)foreground.getBlue());
  286. boolean bold = (matchFont.getStyle() & Font.BOLD) != 0;
  287. boolean italic = (matchFont.getStyle() & Font.ITALIC) != 0;
  288. HSSFFont hssfFont = workbook.findFont(bold,
  289. hssfColor.getIndex(),
  290. (short)(matchFont.getSize() * 20),
  291. matchFont.getName(),
  292. italic,
  293. false,
  294. (short)0,
  295. (byte)0);
  296. if (hssfFont == null)
  297. {
  298. hssfFont = workbook.createFont();
  299. hssfFont.setBold(bold);
  300. hssfFont.setColor(hssfColor.getIndex());
  301. hssfFont.setFontHeight((short)(matchFont.getSize() * 20));
  302. hssfFont.setFontName(matchFont.getName());
  303. hssfFont.setItalic(italic);
  304. hssfFont.setStrikeout(false);
  305. hssfFont.setTypeOffset((short) 0);
  306. hssfFont.setUnderline((byte) 0);
  307. }
  308. return hssfFont;
  309. }
  310. @Override
  311. public void drawString(AttributedCharacterIterator iterator,
  312. int x, int y)
  313. {
  314. LOG.atWarn().log("drawString not supported");
  315. }
  316. @Override
  317. public void fillArc(int x, int y, int width, int height,
  318. int startAngle, int arcAngle)
  319. {
  320. LOG.atWarn().log("fillArc not supported");
  321. }
  322. @Override
  323. public void fillOval(int x, int y, int width, int height)
  324. {
  325. HSSFSimpleShape shape = escherGroup.createShape(new HSSFChildAnchor( x, y, x + width, y + height ) );
  326. shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
  327. shape.setLineStyle(HSSFShape.LINESTYLE_NONE);
  328. shape.setFillColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  329. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  330. shape.setNoFill(false);
  331. }
  332. /**
  333. * Fills a (closed) polygon, as defined by a pair of arrays, which
  334. * hold the <i>x</i> and <i>y</i> coordinates.
  335. * <p>
  336. * This draws the polygon, with <code>nPoint</code> line segments.
  337. * The first <code>nPoint&nbsp;-&nbsp;1</code> line segments are
  338. * drawn between sequential points
  339. * (<code>xPoints[i],yPoints[i],xPoints[i+1],yPoints[i+1]</code>).
  340. * The final line segment is a closing one, from the last point to
  341. * the first (assuming they are different).
  342. * <p>
  343. * The area inside of the polygon is defined by using an
  344. * even-odd fill rule (also known as the alternating rule), and
  345. * the area inside of it is filled.
  346. * @param xPoints array of the <code>x</code> coordinates.
  347. * @param yPoints array of the <code>y</code> coordinates.
  348. * @param nPoints the total number of points in the polygon.
  349. * @see Graphics#drawPolygon(int[], int[], int)
  350. */
  351. @Override
  352. public void fillPolygon(int[] xPoints, int[] yPoints,
  353. int nPoints)
  354. {
  355. int right = findBiggest(xPoints);
  356. int bottom = findBiggest(yPoints);
  357. int left = findSmallest(xPoints);
  358. int top = findSmallest(yPoints);
  359. HSSFPolygon shape = escherGroup.createPolygon(new HSSFChildAnchor(left,top,right,bottom) );
  360. shape.setPolygonDrawArea(right - left, bottom - top);
  361. shape.setPoints(addToAll(xPoints, -left), addToAll(yPoints, -top));
  362. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  363. shape.setFillColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  364. }
  365. private int findBiggest( int[] values )
  366. {
  367. int result = Integer.MIN_VALUE;
  368. for ( int i = 0; i < values.length; i++ )
  369. {
  370. if (values[i] > result)
  371. result = values[i];
  372. }
  373. return result;
  374. }
  375. private int findSmallest( int[] values )
  376. {
  377. int result = Integer.MAX_VALUE;
  378. for ( int i = 0; i < values.length; i++ )
  379. {
  380. if (values[i] < result)
  381. result = values[i];
  382. }
  383. return result;
  384. }
  385. @Override
  386. public void fillRect(int x, int y, int width, int height)
  387. {
  388. HSSFSimpleShape shape = escherGroup.createShape(new HSSFChildAnchor( x, y, x + width, y + height ) );
  389. shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
  390. shape.setLineStyle(HSSFShape.LINESTYLE_NONE);
  391. shape.setFillColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  392. shape.setLineStyleColor(foreground.getRed(), foreground.getGreen(), foreground.getBlue());
  393. }
  394. @Override
  395. public void fillRoundRect(int x, int y, int width, int height,
  396. int arcWidth, int arcHeight)
  397. {
  398. LOG.atWarn().log("fillRoundRect not supported");
  399. }
  400. @Override
  401. public Shape getClip()
  402. {
  403. return getClipBounds();
  404. }
  405. @Override
  406. public Rectangle getClipBounds()
  407. {
  408. return null;
  409. }
  410. @Override
  411. public Color getColor()
  412. {
  413. return foreground;
  414. }
  415. @Override
  416. public Font getFont()
  417. {
  418. return font;
  419. }
  420. @Override
  421. @SuppressWarnings("deprecation")
  422. @SuppressForbidden
  423. public FontMetrics getFontMetrics(Font f)
  424. {
  425. return Toolkit.getDefaultToolkit().getFontMetrics(f);
  426. }
  427. @Override
  428. public void setClip(int x, int y, int width, int height)
  429. {
  430. setClip(new Rectangle(x,y,width,height));
  431. }
  432. @Override
  433. @NotImplemented
  434. public void setClip(Shape shape)
  435. {
  436. LOG.atWarn().log("setClip not supported");
  437. }
  438. @Override
  439. public void setColor(Color color)
  440. {
  441. foreground = color;
  442. }
  443. @Override
  444. public void setFont(Font f)
  445. {
  446. font = f;
  447. }
  448. @Override
  449. @NotImplemented
  450. public void setPaintMode()
  451. {
  452. LOG.atWarn().log("setPaintMode not supported");
  453. }
  454. @Override
  455. @NotImplemented
  456. public void setXORMode(Color color)
  457. {
  458. LOG.atWarn().log("setXORMode not supported");
  459. }
  460. @Override
  461. @NotImplemented
  462. public void translate(int x, int y)
  463. {
  464. LOG.atWarn().log("translate not supported");
  465. }
  466. public Color getBackground()
  467. {
  468. return background;
  469. }
  470. public void setBackground( Color background )
  471. {
  472. this.background = background;
  473. }
  474. HSSFShapeGroup getEscherGraphics()
  475. {
  476. return escherGroup;
  477. }
  478. }