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.

XSSFDrawing.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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.xssf.usermodel;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.ArrayList;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import javax.xml.namespace.QName;
  24. import org.apache.poi.ooxml.POIXMLDocumentPart;
  25. import org.apache.poi.ooxml.POIXMLException;
  26. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  27. import org.apache.poi.openxml4j.opc.PackagePart;
  28. import org.apache.poi.openxml4j.opc.PackagePartName;
  29. import org.apache.poi.openxml4j.opc.PackageRelationship;
  30. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  31. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  32. import org.apache.poi.openxml4j.opc.TargetMode;
  33. import org.apache.poi.ss.usermodel.ClientAnchor;
  34. import org.apache.poi.ss.usermodel.Drawing;
  35. import org.apache.poi.ss.util.CellAddress;
  36. import org.apache.poi.ss.util.ImageUtils;
  37. import org.apache.poi.util.Internal;
  38. import org.apache.poi.util.POILogFactory;
  39. import org.apache.poi.util.POILogger;
  40. import org.apache.poi.util.Units;
  41. import org.apache.poi.xssf.model.CommentsTable;
  42. import org.apache.xmlbeans.XmlCursor;
  43. import org.apache.xmlbeans.XmlException;
  44. import org.apache.xmlbeans.XmlObject;
  45. import org.apache.xmlbeans.XmlOptions;
  46. import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
  47. import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;
  48. import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D;
  49. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
  50. import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;
  51. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
  52. import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
  53. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTAbsoluteAnchor;
  54. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTConnector;
  55. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing;
  56. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGraphicalObjectFrame;
  57. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGroupShape;
  58. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  59. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTOneCellAnchor;
  60. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture;
  61. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape;
  62. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;
  63. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.STEditAs;
  64. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObject;
  65. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObjects;
  66. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  67. /**
  68. * Represents a SpreadsheetML drawing
  69. */
  70. public final class XSSFDrawing extends POIXMLDocumentPart implements Drawing<XSSFShape> {
  71. private static final POILogger LOG = POILogFactory.getLogger(XSSFDrawing.class);
  72. /**
  73. * Root element of the SpreadsheetML Drawing part
  74. */
  75. private CTDrawing drawing;
  76. private long numOfGraphicFrames;
  77. protected static final String NAMESPACE_A = XSSFRelation.NS_DRAWINGML;
  78. protected static final String NAMESPACE_C = XSSFRelation.NS_CHART;
  79. /**
  80. * Create a new SpreadsheetML drawing
  81. *
  82. * @see org.apache.poi.xssf.usermodel.XSSFSheet#createDrawingPatriarch()
  83. */
  84. protected XSSFDrawing() {
  85. super();
  86. drawing = newDrawing();
  87. }
  88. /**
  89. * Construct a SpreadsheetML drawing from a package part
  90. *
  91. * @param part
  92. * the package part holding the drawing data, the content type
  93. * must be
  94. * <code>application/vnd.openxmlformats-officedocument.drawing+xml</code>
  95. *
  96. * @since POI 3.14-Beta1
  97. */
  98. public XSSFDrawing(PackagePart part) throws IOException, XmlException {
  99. super(part);
  100. XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS);
  101. // Removing root element
  102. options.setLoadReplaceDocumentElement(null);
  103. try (InputStream is = part.getInputStream()) {
  104. drawing = CTDrawing.Factory.parse(is, options);
  105. }
  106. }
  107. /**
  108. * Construct a new CTDrawing bean. By default, it's just an empty
  109. * placeholder for drawing objects
  110. *
  111. * @return a new CTDrawing bean
  112. */
  113. private static CTDrawing newDrawing() {
  114. return CTDrawing.Factory.newInstance();
  115. }
  116. /**
  117. * Return the underlying CTDrawing bean, the root element of the
  118. * SpreadsheetML Drawing part.
  119. *
  120. * @return the underlying CTDrawing bean
  121. */
  122. @Internal
  123. public CTDrawing getCTDrawing() {
  124. return drawing;
  125. }
  126. @Override
  127. protected void commit() throws IOException {
  128. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  129. /*
  130. * Saved drawings must have the following namespaces set: <xdr:wsDr
  131. * xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
  132. * xmlns:xdr=
  133. * "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing">
  134. */
  135. xmlOptions
  136. .setSaveSyntheticDocumentElement(new QName(CTDrawing.type.getName().getNamespaceURI(), "wsDr", "xdr"));
  137. PackagePart part = getPackagePart();
  138. OutputStream out = part.getOutputStream();
  139. drawing.save(out, xmlOptions);
  140. out.close();
  141. }
  142. @Override
  143. public XSSFClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {
  144. return new XSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
  145. }
  146. /**
  147. * Constructs a textbox under the drawing.
  148. *
  149. * @param anchor
  150. * the client anchor describes how this group is attached to the
  151. * sheet.
  152. * @return the newly created textbox.
  153. */
  154. public XSSFTextBox createTextbox(XSSFClientAnchor anchor) {
  155. long shapeId = newShapeId();
  156. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  157. CTShape ctShape = ctAnchor.addNewSp();
  158. ctShape.set(XSSFSimpleShape.prototype());
  159. ctShape.getNvSpPr().getCNvPr().setId(shapeId);
  160. XSSFTextBox shape = new XSSFTextBox(this, ctShape);
  161. shape.anchor = anchor;
  162. return shape;
  163. }
  164. /**
  165. * Creates a picture.
  166. *
  167. * @param anchor
  168. * the client anchor describes how this picture is attached to
  169. * the sheet.
  170. * @param pictureIndex
  171. * the index of the picture in the workbook collection of
  172. * pictures,
  173. * {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()}
  174. * .
  175. *
  176. * @return the newly created picture shape.
  177. */
  178. public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex) {
  179. PackageRelationship rel = addPictureReference(pictureIndex);
  180. long shapeId = newShapeId();
  181. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  182. CTPicture ctShape = ctAnchor.addNewPic();
  183. ctShape.set(XSSFPicture.prototype());
  184. ctShape.getNvPicPr().getCNvPr().setId(shapeId);
  185. XSSFPicture shape = new XSSFPicture(this, ctShape);
  186. shape.anchor = anchor;
  187. shape.setPictureReference(rel);
  188. ctShape.getSpPr().setXfrm(createXfrm(anchor));
  189. return shape;
  190. }
  191. @Override
  192. public XSSFPicture createPicture(ClientAnchor anchor, int pictureIndex) {
  193. return createPicture((XSSFClientAnchor) anchor, pictureIndex);
  194. }
  195. /**
  196. * Creates a chart.
  197. *
  198. * @param anchor
  199. * the client anchor describes how this chart is attached to the
  200. * sheet.
  201. * @return the newly created chart
  202. * @see org.apache.poi.xssf.usermodel.XSSFDrawing#createChart(ClientAnchor)
  203. */
  204. public XSSFChart createChart(XSSFClientAnchor anchor) {
  205. int chartNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.CHART.getContentType())
  206. .size() + 1;
  207. RelationPart rp = createRelationship(XSSFRelation.CHART, XSSFFactory.getInstance(), chartNumber, false);
  208. XSSFChart chart = rp.getDocumentPart();
  209. String chartRelId = rp.getRelationship().getId();
  210. XSSFGraphicFrame frame = createGraphicFrame(anchor);
  211. frame.setChart(chart, chartRelId);
  212. frame.getCTGraphicalObjectFrame().setXfrm(createXfrm(anchor));
  213. return chart;
  214. }
  215. /**
  216. * Creates a chart.
  217. *
  218. * @param anchor
  219. * the client anchor describes how this chart is attached to the
  220. * sheet.
  221. * @return the newly created chart
  222. */
  223. public XSSFChart createChart(ClientAnchor anchor) {
  224. return createChart((XSSFClientAnchor) anchor);
  225. }
  226. /**
  227. * Imports the chart from the <code>srcChart</code> into this drawing.
  228. *
  229. * @param srcChart
  230. * the source chart to be cloned into this drawing.
  231. * @return the newly created chart.
  232. * @since 4.0.0
  233. */
  234. public XSSFChart importChart(XSSFChart srcChart) {
  235. CTTwoCellAnchor anchor = ((XSSFDrawing) srcChart.getParent()).getCTDrawing().getTwoCellAnchorArray(0);
  236. CTMarker from = (CTMarker) anchor.getFrom().copy();
  237. CTMarker to = (CTMarker) anchor.getTo().copy();
  238. XSSFClientAnchor destAnchor = new XSSFClientAnchor(from, to);
  239. destAnchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
  240. XSSFChart destChart = createChart(destAnchor);
  241. destChart.getCTChartSpace().set(srcChart.getCTChartSpace().copy());
  242. destChart.getCTChart().set(destChart.getCTChartSpace().getChart());
  243. return destChart;
  244. }
  245. /**
  246. * Add the indexed picture to this drawing relations
  247. *
  248. * @param pictureIndex the index of the picture in the workbook collection of pictures,
  249. * {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} .
  250. */
  251. protected PackageRelationship addPictureReference(int pictureIndex) {
  252. XSSFWorkbook wb = (XSSFWorkbook) getParent().getParent();
  253. XSSFPictureData data = wb.getAllPictures().get(pictureIndex);
  254. XSSFPictureData pic = new XSSFPictureData(data.getPackagePart());
  255. RelationPart rp = addRelation(null, XSSFRelation.IMAGES, pic);
  256. return rp.getRelationship();
  257. }
  258. /**
  259. * Creates a simple shape. This includes such shapes as lines, rectangles,
  260. * and ovals.
  261. *
  262. * @param anchor
  263. * the client anchor describes how this group is attached to the
  264. * sheet.
  265. * @return the newly created shape.
  266. */
  267. public XSSFSimpleShape createSimpleShape(XSSFClientAnchor anchor) {
  268. long shapeId = newShapeId();
  269. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  270. CTShape ctShape = ctAnchor.addNewSp();
  271. ctShape.set(XSSFSimpleShape.prototype());
  272. ctShape.getNvSpPr().getCNvPr().setId(shapeId);
  273. ctShape.getSpPr().setXfrm(createXfrm(anchor));
  274. XSSFSimpleShape shape = new XSSFSimpleShape(this, ctShape);
  275. shape.anchor = anchor;
  276. return shape;
  277. }
  278. /**
  279. * Creates a simple shape. This includes such shapes as lines, rectangles,
  280. * and ovals.
  281. *
  282. * @param anchor
  283. * the client anchor describes how this group is attached to the
  284. * sheet.
  285. * @return the newly created shape.
  286. */
  287. public XSSFConnector createConnector(XSSFClientAnchor anchor) {
  288. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  289. CTConnector ctShape = ctAnchor.addNewCxnSp();
  290. ctShape.set(XSSFConnector.prototype());
  291. XSSFConnector shape = new XSSFConnector(this, ctShape);
  292. shape.anchor = anchor;
  293. return shape;
  294. }
  295. /**
  296. * Creates a simple shape. This includes such shapes as lines, rectangles,
  297. * and ovals.
  298. *
  299. * @param anchor
  300. * the client anchor describes how this group is attached to the
  301. * sheet.
  302. * @return the newly created shape.
  303. */
  304. public XSSFShapeGroup createGroup(XSSFClientAnchor anchor) {
  305. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  306. CTGroupShape ctGroup = ctAnchor.addNewGrpSp();
  307. ctGroup.set(XSSFShapeGroup.prototype());
  308. CTTransform2D xfrm = createXfrm(anchor);
  309. CTGroupTransform2D grpXfrm = ctGroup.getGrpSpPr().getXfrm();
  310. grpXfrm.setOff(xfrm.getOff());
  311. grpXfrm.setExt(xfrm.getExt());
  312. grpXfrm.setChExt(xfrm.getExt());
  313. XSSFShapeGroup shape = new XSSFShapeGroup(this, ctGroup);
  314. shape.anchor = anchor;
  315. return shape;
  316. }
  317. /**
  318. * Creates a comment.
  319. *
  320. * @param anchor
  321. * the client anchor describes how this comment is attached to
  322. * the sheet.
  323. * @return the newly created comment.
  324. */
  325. @Override
  326. public XSSFComment createCellComment(ClientAnchor anchor) {
  327. XSSFClientAnchor ca = (XSSFClientAnchor) anchor;
  328. XSSFSheet sheet = getSheet();
  329. // create comments and vmlDrawing parts if they don't exist
  330. CommentsTable comments = sheet.getCommentsTable(true);
  331. XSSFVMLDrawing vml = sheet.getVMLDrawing(true);
  332. com.microsoft.schemas.vml.CTShape vmlShape = vml.newCommentShape();
  333. if (ca.isSet()) {
  334. // convert offsets from emus to pixels since we get a
  335. // DrawingML-anchor
  336. // but create a VML Drawing
  337. int dx1Pixels = ca.getDx1() / Units.EMU_PER_PIXEL;
  338. int dy1Pixels = ca.getDy1() / Units.EMU_PER_PIXEL;
  339. int dx2Pixels = ca.getDx2() / Units.EMU_PER_PIXEL;
  340. int dy2Pixels = ca.getDy2() / Units.EMU_PER_PIXEL;
  341. String position = ca.getCol1() + ", " + dx1Pixels + ", " + ca.getRow1() + ", " + dy1Pixels + ", " + ca
  342. .getCol2() + ", " + dx2Pixels + ", " + ca.getRow2() + ", " + dy2Pixels;
  343. vmlShape.getClientDataArray(0).setAnchorArray(0, position);
  344. }
  345. CellAddress ref = new CellAddress(ca.getRow1(), ca.getCol1());
  346. if (comments.findCellComment(ref) != null) {
  347. throw new IllegalArgumentException("Multiple cell comments in one cell are not allowed, cell: " + ref);
  348. }
  349. return new XSSFComment(comments, comments.newComment(ref), vmlShape);
  350. }
  351. /**
  352. * Creates a new graphic frame.
  353. *
  354. * @param anchor
  355. * the client anchor describes how this frame is attached to the
  356. * sheet
  357. * @return the newly created graphic frame
  358. */
  359. private XSSFGraphicFrame createGraphicFrame(XSSFClientAnchor anchor) {
  360. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  361. CTGraphicalObjectFrame ctGraphicFrame = ctAnchor.addNewGraphicFrame();
  362. ctGraphicFrame.set(XSSFGraphicFrame.prototype());
  363. ctGraphicFrame.setXfrm(createXfrm(anchor));
  364. long frameId = numOfGraphicFrames++;
  365. XSSFGraphicFrame graphicFrame = new XSSFGraphicFrame(this, ctGraphicFrame);
  366. graphicFrame.setAnchor(anchor);
  367. graphicFrame.setId(frameId);
  368. graphicFrame.setName("Diagramm" + frameId);
  369. return graphicFrame;
  370. }
  371. @Override
  372. public XSSFObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex) {
  373. XSSFSheet sh = getSheet();
  374. PackagePart sheetPart = sh.getPackagePart();
  375. /*
  376. * The shape id of the ole object seems to be a legacy shape id.
  377. *
  378. * see 5.3.2.1 legacyDrawing (Legacy Drawing Object): Legacy Shape ID
  379. * that is unique throughout the entire document. Legacy shape IDs
  380. * should be assigned based on which portion of the document the drawing
  381. * resides on. The assignment of these ids is broken down into clusters
  382. * of 1024 values. The first cluster is 1-1024, the second 1025-2048 and
  383. * so on.
  384. *
  385. * Ole shapes seem to start with 1025 on the first sheet ... and not
  386. * sure, if the ids need to be reindexed when sheets are removed or more
  387. * than 1024 shapes are on a given sheet (see #51332 for a similar
  388. * issue)
  389. */
  390. XSSFSheet sheet = getSheet();
  391. XSSFWorkbook wb = sheet.getWorkbook();
  392. int sheetIndex = wb.getSheetIndex(sheet);
  393. long shapeId = (sheetIndex + 1L) * 1024 + newShapeId();
  394. // add reference to OLE part
  395. final XSSFRelation rel = XSSFRelation.OLEEMBEDDINGS;
  396. PackagePartName olePN;
  397. try {
  398. olePN = PackagingURIHelper.createPartName(rel.getFileName(storageId));
  399. } catch (InvalidFormatException e) {
  400. throw new POIXMLException(e);
  401. }
  402. PackageRelationship olePR = sheetPart.addRelationship(olePN, TargetMode.INTERNAL, rel.getRelation());
  403. // add reference to image part
  404. XSSFPictureData imgPD = sh.getWorkbook().getAllPictures().get(pictureIndex);
  405. PackagePartName imgPN = imgPD.getPackagePart().getPartName();
  406. PackageRelationship imgSheetPR = sheetPart.addRelationship(imgPN, TargetMode.INTERNAL,
  407. PackageRelationshipTypes.IMAGE_PART);
  408. PackageRelationship imgDrawPR = getPackagePart().addRelationship(imgPN, TargetMode.INTERNAL,
  409. PackageRelationshipTypes.IMAGE_PART);
  410. // add OLE part metadata to sheet
  411. CTWorksheet cwb = sh.getCTWorksheet();
  412. CTOleObjects oo = cwb.isSetOleObjects() ? cwb.getOleObjects() : cwb.addNewOleObjects();
  413. CTOleObject ole1 = oo.addNewOleObject();
  414. ole1.setProgId("Package");
  415. ole1.setShapeId(shapeId);
  416. ole1.setId(olePR.getId());
  417. XmlCursor cur1 = ole1.newCursor();
  418. cur1.toEndToken();
  419. cur1.beginElement("objectPr", XSSFRelation.NS_SPREADSHEETML);
  420. cur1.insertAttributeWithValue("id", PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS, imgSheetPR.getId());
  421. cur1.insertAttributeWithValue("defaultSize", "0");
  422. cur1.beginElement("anchor", XSSFRelation.NS_SPREADSHEETML);
  423. cur1.insertAttributeWithValue("moveWithCells", "1");
  424. CTTwoCellAnchor ctAnchor = createTwoCellAnchor((XSSFClientAnchor) anchor);
  425. XmlCursor cur2 = ctAnchor.newCursor();
  426. cur2.copyXmlContents(cur1);
  427. cur2.dispose();
  428. cur1.toParent();
  429. cur1.toFirstChild();
  430. cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "from"));
  431. cur1.toNextSibling();
  432. cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "to"));
  433. cur1.dispose();
  434. // add a new shape and link OLE & image part
  435. CTShape ctShape = ctAnchor.addNewSp();
  436. ctShape.set(XSSFObjectData.prototype());
  437. ctShape.getSpPr().setXfrm(createXfrm((XSSFClientAnchor) anchor));
  438. // workaround for not having the vmlDrawing filled
  439. CTBlipFillProperties blipFill = ctShape.getSpPr().addNewBlipFill();
  440. blipFill.addNewBlip().setEmbed(imgDrawPR.getId());
  441. blipFill.addNewStretch().addNewFillRect();
  442. CTNonVisualDrawingProps cNvPr = ctShape.getNvSpPr().getCNvPr();
  443. cNvPr.setId(shapeId);
  444. cNvPr.setName("Object " + shapeId);
  445. XmlCursor extCur = cNvPr.getExtLst().getExtArray(0).newCursor();
  446. extCur.toFirstChild();
  447. extCur.setAttributeText(new QName("spid"), "_x0000_s" + shapeId);
  448. extCur.dispose();
  449. XSSFObjectData shape = new XSSFObjectData(this, ctShape);
  450. shape.anchor = (XSSFClientAnchor) anchor;
  451. return shape;
  452. }
  453. /**
  454. * Returns all charts in this drawing.
  455. */
  456. public List<XSSFChart> getCharts() {
  457. List<XSSFChart> charts = new ArrayList<>();
  458. for (POIXMLDocumentPart part : getRelations()) {
  459. if (part instanceof XSSFChart) {
  460. charts.add((XSSFChart) part);
  461. }
  462. }
  463. return charts;
  464. }
  465. /**
  466. * Create and initialize a CTTwoCellAnchor that anchors a shape against
  467. * top-left and bottom-right cells.
  468. *
  469. * @return a new CTTwoCellAnchor
  470. */
  471. private CTTwoCellAnchor createTwoCellAnchor(XSSFClientAnchor anchor) {
  472. CTTwoCellAnchor ctAnchor = drawing.addNewTwoCellAnchor();
  473. ctAnchor.setFrom(anchor.getFrom());
  474. ctAnchor.setTo(anchor.getTo());
  475. ctAnchor.addNewClientData();
  476. anchor.setTo(ctAnchor.getTo());
  477. anchor.setFrom(ctAnchor.getFrom());
  478. STEditAs.Enum editAs;
  479. switch (anchor.getAnchorType()) {
  480. case DONT_MOVE_AND_RESIZE:
  481. editAs = STEditAs.ABSOLUTE;
  482. break;
  483. case MOVE_AND_RESIZE:
  484. editAs = STEditAs.TWO_CELL;
  485. break;
  486. case MOVE_DONT_RESIZE:
  487. editAs = STEditAs.ONE_CELL;
  488. break;
  489. default:
  490. editAs = STEditAs.ONE_CELL;
  491. }
  492. ctAnchor.setEditAs(editAs);
  493. return ctAnchor;
  494. }
  495. private CTTransform2D createXfrm(XSSFClientAnchor anchor) {
  496. CTTransform2D xfrm = CTTransform2D.Factory.newInstance();
  497. CTPoint2D off = xfrm.addNewOff();
  498. off.setX(anchor.getDx1());
  499. off.setY(anchor.getDy1());
  500. XSSFSheet sheet = getSheet();
  501. double widthPx = 0;
  502. for (int col = anchor.getCol1(); col < anchor.getCol2(); col++) {
  503. widthPx += sheet.getColumnWidthInPixels(col);
  504. }
  505. double heightPx = 0;
  506. for (int row = anchor.getRow1(); row < anchor.getRow2(); row++) {
  507. heightPx += ImageUtils.getRowHeightInPixels(sheet, row);
  508. }
  509. long width = Units.pixelToEMU((int) widthPx);
  510. long height = Units.pixelToEMU((int) heightPx);
  511. CTPositiveSize2D ext = xfrm.addNewExt();
  512. ext.setCx(width - anchor.getDx1() + anchor.getDx2());
  513. ext.setCy(height - anchor.getDy1() + anchor.getDy2());
  514. // TODO: handle vflip/hflip
  515. return xfrm;
  516. }
  517. private long newShapeId() {
  518. return 1L + drawing.sizeOfAbsoluteAnchorArray() + drawing.sizeOfOneCellAnchorArray() + drawing
  519. .sizeOfTwoCellAnchorArray();
  520. }
  521. /**
  522. * @return list of shapes in this drawing
  523. */
  524. public List<XSSFShape> getShapes() {
  525. List<XSSFShape> lst = new ArrayList<>();
  526. XmlCursor cur = drawing.newCursor();
  527. try {
  528. if (cur.toFirstChild()) {
  529. addShapes(cur, lst);
  530. }
  531. } finally {
  532. cur.dispose();
  533. }
  534. return lst;
  535. }
  536. /**
  537. * @return list of shapes in this shape group
  538. */
  539. public List<XSSFShape> getShapes(XSSFShapeGroup groupshape) {
  540. List<XSSFShape> lst = new ArrayList<>();
  541. XmlCursor cur = groupshape.getCTGroupShape().newCursor();
  542. try {
  543. addShapes(cur, lst);
  544. } finally {
  545. cur.dispose();
  546. }
  547. return lst;
  548. }
  549. private void addShapes(XmlCursor cur, List<XSSFShape> lst) {
  550. try {
  551. do {
  552. cur.push();
  553. if (cur.toFirstChild()) {
  554. do {
  555. XmlObject obj = cur.getObject();
  556. XSSFShape shape;
  557. if (obj instanceof CTMarker) {
  558. // ignore anchor elements
  559. continue;
  560. } else if (obj instanceof CTPicture) {
  561. shape = new XSSFPicture(this, (CTPicture) obj);
  562. } else if (obj instanceof CTConnector) {
  563. shape = new XSSFConnector(this, (CTConnector) obj);
  564. } else if (obj instanceof CTShape) {
  565. shape = hasOleLink(obj) ? new XSSFObjectData(this, (CTShape) obj)
  566. : new XSSFSimpleShape(this, (CTShape) obj);
  567. } else if (obj instanceof CTGraphicalObjectFrame) {
  568. shape = new XSSFGraphicFrame(this, (CTGraphicalObjectFrame) obj);
  569. } else if (obj instanceof CTGroupShape) {
  570. shape = new XSSFShapeGroup(this, (CTGroupShape) obj);
  571. } else if (obj instanceof XmlAnyTypeImpl) {
  572. LOG.log(POILogger.WARN,
  573. "trying to parse AlternateContent, " + "this unlinks the returned Shapes from the underlying xml content, " + "so those shapes can't be used to modify the drawing, " + "i.e. modifications will be ignored!");
  574. // XmlAnyTypeImpl is returned for AlternateContent
  575. // parts, which might contain a CTDrawing
  576. cur.push();
  577. cur.toFirstChild();
  578. XmlCursor cur2 = null;
  579. try {
  580. // need to parse AlternateContent again,
  581. // otherwise the child elements aren't typed,
  582. // but also XmlAnyTypes
  583. CTDrawing alterWS = CTDrawing.Factory.parse(cur.newXMLStreamReader());
  584. cur2 = alterWS.newCursor();
  585. if (cur2.toFirstChild()) {
  586. addShapes(cur2, lst);
  587. }
  588. } catch (XmlException e) {
  589. LOG.log(POILogger.WARN, "unable to parse CTDrawing in alternate content.", e);
  590. } finally {
  591. if (cur2 != null) {
  592. cur2.dispose();
  593. }
  594. cur.pop();
  595. }
  596. continue;
  597. } else {
  598. // ignore anything else
  599. continue;
  600. }
  601. assert (shape != null);
  602. shape.anchor = getAnchorFromParent(obj);
  603. lst.add(shape);
  604. } while (cur.toNextSibling());
  605. }
  606. cur.pop();
  607. } while (cur.toNextSibling());
  608. } finally {
  609. cur.dispose();
  610. }
  611. }
  612. private boolean hasOleLink(XmlObject shape) {
  613. QName uriName = new QName(null, "uri");
  614. String xquery = "declare namespace a='" + XSSFRelation.NS_DRAWINGML + "' .//a:extLst/a:ext";
  615. XmlCursor cur = shape.newCursor();
  616. cur.selectPath(xquery);
  617. try {
  618. while (cur.toNextSelection()) {
  619. String uri = cur.getAttributeText(uriName);
  620. if ("{63B3BB69-23CF-44E3-9099-C40C66FF867C}".equals(uri)) {
  621. return true;
  622. }
  623. }
  624. } finally {
  625. cur.dispose();
  626. }
  627. return false;
  628. }
  629. private XSSFAnchor getAnchorFromParent(XmlObject obj) {
  630. XSSFAnchor anchor = null;
  631. XmlObject parentXbean = null;
  632. XmlCursor cursor = obj.newCursor();
  633. if (cursor.toParent()) {
  634. parentXbean = cursor.getObject();
  635. }
  636. cursor.dispose();
  637. if (parentXbean != null) {
  638. if (parentXbean instanceof CTTwoCellAnchor) {
  639. CTTwoCellAnchor ct = (CTTwoCellAnchor) parentXbean;
  640. anchor = new XSSFClientAnchor(ct.getFrom(), ct.getTo());
  641. } else if (parentXbean instanceof CTOneCellAnchor) {
  642. CTOneCellAnchor ct = (CTOneCellAnchor) parentXbean;
  643. anchor = new XSSFClientAnchor(getSheet(), ct.getFrom(), ct.getExt());
  644. } else if (parentXbean instanceof CTAbsoluteAnchor) {
  645. CTAbsoluteAnchor ct = (CTAbsoluteAnchor) parentXbean;
  646. anchor = new XSSFClientAnchor(getSheet(), ct.getPos(), ct.getExt());
  647. }
  648. }
  649. return anchor;
  650. }
  651. @Override
  652. public Iterator<XSSFShape> iterator() {
  653. return getShapes().iterator();
  654. }
  655. /**
  656. * @return the sheet associated with the drawing
  657. */
  658. public XSSFSheet getSheet() {
  659. return (XSSFSheet) getParent();
  660. }
  661. }