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 27KB

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