Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

XSSFDrawing.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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.logging.log4j.LogManager;
  25. import org.apache.logging.log4j.Logger;
  26. import org.apache.poi.ooxml.POIXMLDocumentPart;
  27. import org.apache.poi.ooxml.POIXMLException;
  28. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  29. import org.apache.poi.openxml4j.opc.OPCPackage;
  30. import org.apache.poi.openxml4j.opc.PackagePart;
  31. import org.apache.poi.openxml4j.opc.PackagePartName;
  32. import org.apache.poi.openxml4j.opc.PackageRelationship;
  33. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  34. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  35. import org.apache.poi.openxml4j.opc.TargetMode;
  36. import org.apache.poi.ss.usermodel.ClientAnchor;
  37. import org.apache.poi.ss.usermodel.Drawing;
  38. import org.apache.poi.ss.util.ImageUtils;
  39. import org.apache.poi.util.Internal;
  40. import org.apache.poi.util.Units;
  41. import org.apache.poi.xssf.model.Comments;
  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 Logger LOG = LogManager.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 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. try (OutputStream out = part.getOutputStream()) {
  139. drawing.save(out, xmlOptions);
  140. }
  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 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 XSSFDrawing#createChart(ClientAnchor)
  203. */
  204. public XSSFChart createChart(XSSFClientAnchor anchor) {
  205. RelationPart rp = createChartRelationPart();
  206. XSSFChart chart = rp.getDocumentPart();
  207. String chartRelId = rp.getRelationship().getId();
  208. XSSFGraphicFrame frame = createGraphicFrame(anchor);
  209. frame.setChart(chart, chartRelId);
  210. frame.getCTGraphicalObjectFrame().setXfrm(createXfrm(anchor));
  211. return chart;
  212. }
  213. protected RelationPart createChartRelationPart() {
  214. XSSFWorkbook wb = getSheet().getWorkbook();
  215. XSSFFactory factory = wb == null ? XSSFFactory.getInstance() : wb.getXssfFactory();
  216. OPCPackage pkg = getPackagePart().getPackage();
  217. int chartNumber = pkg.getPartsByContentType(XSSFRelation.CHART.getContentType())
  218. .size() + 1;
  219. // some broken files have incorrectly named package parts,
  220. // so we need to avoid duplicates here by checking and increasing
  221. // the part-number
  222. try {
  223. while (pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.CHART.getFileName(chartNumber))) != null) {
  224. chartNumber++;
  225. }
  226. } catch (InvalidFormatException e) {
  227. throw new IllegalStateException("Failed for " + chartNumber, e);
  228. }
  229. return createRelationship(XSSFRelation.CHART, factory, chartNumber, false);
  230. }
  231. /**
  232. * Creates a chart.
  233. *
  234. * @param anchor
  235. * the client anchor describes how this chart is attached to the
  236. * sheet.
  237. * @return the newly created chart
  238. */
  239. public XSSFChart createChart(ClientAnchor anchor) {
  240. return createChart((XSSFClientAnchor) anchor);
  241. }
  242. /**
  243. * Imports the chart from the <code>srcChart</code> into this drawing.
  244. *
  245. * @param srcChart
  246. * the source chart to be cloned into this drawing.
  247. * @return the newly created chart.
  248. * @since 4.0.0
  249. */
  250. public XSSFChart importChart(XSSFChart srcChart) {
  251. CTTwoCellAnchor anchor = ((XSSFDrawing) srcChart.getParent()).getCTDrawing().getTwoCellAnchorArray(0);
  252. CTMarker from = (CTMarker) anchor.getFrom().copy();
  253. CTMarker to = (CTMarker) anchor.getTo().copy();
  254. XSSFClientAnchor destAnchor = new XSSFClientAnchor(from, to);
  255. destAnchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
  256. XSSFChart destChart = createChart(destAnchor);
  257. destChart.getCTChartSpace().set(srcChart.getCTChartSpace().copy());
  258. return destChart;
  259. }
  260. /**
  261. * Add the indexed picture to this drawing relations
  262. *
  263. * @param pictureIndex the index of the picture in the workbook collection of pictures,
  264. * {@link XSSFWorkbook#getAllPictures()} .
  265. */
  266. protected PackageRelationship addPictureReference(int pictureIndex) {
  267. XSSFPictureData data = getSheet().getWorkbook().getAllPictures().get(pictureIndex);
  268. XSSFPictureData pic = new XSSFPictureData(data.getPackagePart());
  269. RelationPart rp = addRelation(null, XSSFRelation.IMAGES, pic);
  270. return rp.getRelationship();
  271. }
  272. /**
  273. * Creates a simple shape. This includes such shapes as lines, rectangles,
  274. * and ovals.
  275. *
  276. * @param anchor
  277. * the client anchor describes how this group is attached to the
  278. * sheet.
  279. * @return the newly created shape.
  280. */
  281. public XSSFSimpleShape createSimpleShape(XSSFClientAnchor anchor) {
  282. long shapeId = newShapeId();
  283. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  284. CTShape ctShape = ctAnchor.addNewSp();
  285. ctShape.set(XSSFSimpleShape.prototype());
  286. ctShape.getNvSpPr().getCNvPr().setId(shapeId);
  287. ctShape.getSpPr().setXfrm(createXfrm(anchor));
  288. XSSFSimpleShape shape = new XSSFSimpleShape(this, ctShape);
  289. shape.anchor = anchor;
  290. return shape;
  291. }
  292. /**
  293. * Creates a simple shape. This includes such shapes as lines, rectangles,
  294. * and ovals.
  295. *
  296. * @param anchor
  297. * the client anchor describes how this group is attached to the
  298. * sheet.
  299. * @return the newly created shape.
  300. */
  301. public XSSFConnector createConnector(XSSFClientAnchor anchor) {
  302. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  303. CTConnector ctShape = ctAnchor.addNewCxnSp();
  304. ctShape.set(XSSFConnector.prototype());
  305. XSSFConnector shape = new XSSFConnector(this, ctShape);
  306. shape.anchor = anchor;
  307. return shape;
  308. }
  309. /**
  310. * Creates a simple shape. This includes such shapes as lines, rectangles,
  311. * and ovals.
  312. *
  313. * @param anchor
  314. * the client anchor describes how this group is attached to the
  315. * sheet.
  316. * @return the newly created shape.
  317. */
  318. public XSSFShapeGroup createGroup(XSSFClientAnchor anchor) {
  319. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  320. CTGroupShape ctGroup = ctAnchor.addNewGrpSp();
  321. ctGroup.set(XSSFShapeGroup.prototype());
  322. CTTransform2D xfrm = createXfrm(anchor);
  323. CTGroupTransform2D grpXfrm = ctGroup.getGrpSpPr().getXfrm();
  324. grpXfrm.setOff(xfrm.getOff());
  325. grpXfrm.setExt(xfrm.getExt());
  326. grpXfrm.setChExt(xfrm.getExt());
  327. XSSFShapeGroup shape = new XSSFShapeGroup(this, ctGroup);
  328. shape.anchor = anchor;
  329. return shape;
  330. }
  331. /**
  332. * Creates a comment.
  333. *
  334. * @param anchor
  335. * the client anchor describes how this comment is attached to
  336. * the sheet.
  337. * @return the newly created comment.
  338. */
  339. @Override
  340. public XSSFComment createCellComment(ClientAnchor anchor) {
  341. XSSFSheet sheet = getSheet();
  342. Comments comments = sheet.getCommentsTable(true);
  343. return comments.createNewComment(anchor);
  344. }
  345. /**
  346. * Creates a new graphic frame.
  347. *
  348. * @param anchor
  349. * the client anchor describes how this frame is attached to the
  350. * sheet
  351. * @return the newly created graphic frame
  352. */
  353. private XSSFGraphicFrame createGraphicFrame(XSSFClientAnchor anchor) {
  354. CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
  355. CTGraphicalObjectFrame ctGraphicFrame = ctAnchor.addNewGraphicFrame();
  356. ctGraphicFrame.set(XSSFGraphicFrame.prototype());
  357. ctGraphicFrame.setXfrm(createXfrm(anchor));
  358. long frameId = numOfGraphicFrames++;
  359. XSSFGraphicFrame graphicFrame = new XSSFGraphicFrame(this, ctGraphicFrame);
  360. graphicFrame.setAnchor(anchor);
  361. graphicFrame.setId(frameId);
  362. graphicFrame.setName("Diagramm" + frameId);
  363. return graphicFrame;
  364. }
  365. @Override
  366. public XSSFObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex) {
  367. XSSFSheet sh = getSheet();
  368. PackagePart sheetPart = sh.getPackagePart();
  369. /*
  370. * The shape id of the ole object seems to be a legacy shape id.
  371. *
  372. * see 5.3.2.1 legacyDrawing (Legacy Drawing Object): Legacy Shape ID
  373. * that is unique throughout the entire document. Legacy shape IDs
  374. * should be assigned based on which portion of the document the drawing
  375. * resides on. The assignment of these ids is broken down into clusters
  376. * of 1024 values. The first cluster is 1-1024, the second 1025-2048 and
  377. * so on.
  378. *
  379. * Ole shapes seem to start with 1025 on the first sheet ... and not
  380. * sure, if the ids need to be reindexed when sheets are removed or more
  381. * than 1024 shapes are on a given sheet (see #51332 for a similar
  382. * issue)
  383. */
  384. XSSFSheet sheet = getSheet();
  385. XSSFWorkbook wb = sheet.getWorkbook();
  386. int sheetIndex = wb.getSheetIndex(sheet);
  387. long shapeId = (sheetIndex + 1L) * 1024 + newShapeId();
  388. // add reference to OLE part
  389. final XSSFRelation rel = XSSFRelation.OLEEMBEDDINGS;
  390. PackagePartName olePN;
  391. try {
  392. olePN = PackagingURIHelper.createPartName(rel.getFileName(storageId));
  393. } catch (InvalidFormatException e) {
  394. throw new POIXMLException(e);
  395. }
  396. PackageRelationship olePR = sheetPart.addRelationship(olePN, TargetMode.INTERNAL, rel.getRelation());
  397. // add reference to image part
  398. XSSFPictureData imgPD = sh.getWorkbook().getAllPictures().get(pictureIndex);
  399. PackagePartName imgPN = imgPD.getPackagePart().getPartName();
  400. PackageRelationship imgSheetPR = sheetPart.addRelationship(imgPN, TargetMode.INTERNAL,
  401. PackageRelationshipTypes.IMAGE_PART);
  402. PackageRelationship imgDrawPR = getPackagePart().addRelationship(imgPN, TargetMode.INTERNAL,
  403. PackageRelationshipTypes.IMAGE_PART);
  404. // add OLE part metadata to sheet
  405. CTWorksheet cwb = sh.getCTWorksheet();
  406. CTOleObjects oo = cwb.isSetOleObjects() ? cwb.getOleObjects() : cwb.addNewOleObjects();
  407. CTOleObject ole1 = oo.addNewOleObject();
  408. ole1.setProgId("Package");
  409. ole1.setShapeId(shapeId);
  410. ole1.setId(olePR.getId());
  411. XmlCursor cur1 = ole1.newCursor();
  412. cur1.toEndToken();
  413. cur1.beginElement("objectPr", XSSFRelation.NS_SPREADSHEETML);
  414. cur1.insertAttributeWithValue("id", PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS, imgSheetPR.getId());
  415. cur1.insertAttributeWithValue("defaultSize", "0");
  416. cur1.beginElement("anchor", XSSFRelation.NS_SPREADSHEETML);
  417. cur1.insertAttributeWithValue("moveWithCells", "1");
  418. CTTwoCellAnchor ctAnchor = createTwoCellAnchor((XSSFClientAnchor) anchor);
  419. XmlCursor cur2 = ctAnchor.newCursor();
  420. cur2.copyXmlContents(cur1);
  421. cur2.dispose();
  422. cur1.toParent();
  423. cur1.toFirstChild();
  424. cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "from"));
  425. cur1.toNextSibling();
  426. cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "to"));
  427. cur1.dispose();
  428. // add a new shape and link OLE & image part
  429. CTShape ctShape = ctAnchor.addNewSp();
  430. ctShape.set(XSSFObjectData.prototype());
  431. ctShape.getSpPr().setXfrm(createXfrm((XSSFClientAnchor) anchor));
  432. // workaround for not having the vmlDrawing filled
  433. CTBlipFillProperties blipFill = ctShape.getSpPr().addNewBlipFill();
  434. blipFill.addNewBlip().setEmbed(imgDrawPR.getId());
  435. blipFill.addNewStretch().addNewFillRect();
  436. CTNonVisualDrawingProps cNvPr = ctShape.getNvSpPr().getCNvPr();
  437. cNvPr.setId(shapeId);
  438. cNvPr.setName("Object " + shapeId);
  439. XmlCursor extCur = cNvPr.getExtLst().getExtArray(0).newCursor();
  440. extCur.toFirstChild();
  441. extCur.setAttributeText(new QName("spid"), "_x0000_s" + shapeId);
  442. extCur.dispose();
  443. XSSFObjectData shape = new XSSFObjectData(this, ctShape);
  444. shape.anchor = (XSSFClientAnchor) anchor;
  445. return shape;
  446. }
  447. /**
  448. * Returns all charts in this drawing.
  449. */
  450. public List<XSSFChart> getCharts() {
  451. List<XSSFChart> charts = new ArrayList<>();
  452. for (POIXMLDocumentPart part : getRelations()) {
  453. if (part instanceof XSSFChart) {
  454. charts.add((XSSFChart) part);
  455. }
  456. }
  457. return charts;
  458. }
  459. /**
  460. * Create and initialize a CTTwoCellAnchor that anchors a shape against
  461. * top-left and bottom-right cells.
  462. *
  463. * @return a new CTTwoCellAnchor
  464. */
  465. private CTTwoCellAnchor createTwoCellAnchor(XSSFClientAnchor anchor) {
  466. CTTwoCellAnchor ctAnchor = drawing.addNewTwoCellAnchor();
  467. ctAnchor.setFrom(anchor.getFrom());
  468. ctAnchor.setTo(anchor.getTo());
  469. ctAnchor.addNewClientData();
  470. anchor.setTo(ctAnchor.getTo());
  471. anchor.setFrom(ctAnchor.getFrom());
  472. STEditAs.Enum editAs;
  473. switch (anchor.getAnchorType()) {
  474. case DONT_MOVE_AND_RESIZE:
  475. editAs = STEditAs.ABSOLUTE;
  476. break;
  477. case MOVE_AND_RESIZE:
  478. editAs = STEditAs.TWO_CELL;
  479. break;
  480. case MOVE_DONT_RESIZE:
  481. editAs = STEditAs.ONE_CELL;
  482. break;
  483. default:
  484. editAs = STEditAs.ONE_CELL;
  485. }
  486. ctAnchor.setEditAs(editAs);
  487. return ctAnchor;
  488. }
  489. private CTTransform2D createXfrm(XSSFClientAnchor anchor) {
  490. CTTransform2D xfrm = CTTransform2D.Factory.newInstance();
  491. CTPoint2D off = xfrm.addNewOff();
  492. off.setX(anchor.getDx1());
  493. off.setY(anchor.getDy1());
  494. XSSFSheet sheet = getSheet();
  495. double widthPx = 0;
  496. for (int col = anchor.getCol1(); col < anchor.getCol2(); col++) {
  497. widthPx += sheet.getColumnWidthInPixels(col);
  498. }
  499. double heightPx = 0;
  500. for (int row = anchor.getRow1(); row < anchor.getRow2(); row++) {
  501. heightPx += ImageUtils.getRowHeightInPixels(sheet, row);
  502. }
  503. long width = Units.pixelToEMU((int) widthPx);
  504. long height = Units.pixelToEMU((int) heightPx);
  505. CTPositiveSize2D ext = xfrm.addNewExt();
  506. ext.setCx(width - anchor.getDx1() + anchor.getDx2());
  507. ext.setCy(height - anchor.getDy1() + anchor.getDy2());
  508. // TODO: handle vflip/hflip
  509. return xfrm;
  510. }
  511. private long newShapeId() {
  512. return 1L + drawing.sizeOfAbsoluteAnchorArray() + drawing.sizeOfOneCellAnchorArray() + drawing
  513. .sizeOfTwoCellAnchorArray();
  514. }
  515. /**
  516. * @return list of shapes in this drawing
  517. */
  518. public List<XSSFShape> getShapes() {
  519. List<XSSFShape> lst = new ArrayList<>();
  520. XmlCursor cur = drawing.newCursor();
  521. try {
  522. if (cur.toFirstChild()) {
  523. addShapes(cur, lst);
  524. }
  525. } finally {
  526. cur.dispose();
  527. }
  528. return lst;
  529. }
  530. /**
  531. * @return list of shapes in this shape group
  532. */
  533. public List<XSSFShape> getShapes(XSSFShapeGroup groupshape) {
  534. List<XSSFShape> lst = new ArrayList<>();
  535. XmlCursor cur = groupshape.getCTGroupShape().newCursor();
  536. try {
  537. addShapes(cur, lst);
  538. } finally {
  539. cur.dispose();
  540. }
  541. return lst;
  542. }
  543. private void addShapes(XmlCursor cur, List<XSSFShape> lst) {
  544. try {
  545. do {
  546. cur.push();
  547. if (cur.toFirstChild()) {
  548. do {
  549. XmlObject obj = cur.getObject();
  550. XSSFShape shape;
  551. if (obj instanceof CTMarker) {
  552. // ignore anchor elements
  553. continue;
  554. } else if (obj instanceof CTPicture) {
  555. shape = new XSSFPicture(this, (CTPicture) obj);
  556. } else if (obj instanceof CTConnector) {
  557. shape = new XSSFConnector(this, (CTConnector) obj);
  558. } else if (obj instanceof CTShape) {
  559. shape = hasOleLink(obj) ? new XSSFObjectData(this, (CTShape) obj)
  560. : new XSSFSimpleShape(this, (CTShape) obj);
  561. } else if (obj instanceof CTGraphicalObjectFrame) {
  562. shape = new XSSFGraphicFrame(this, (CTGraphicalObjectFrame) obj);
  563. } else if (obj instanceof CTGroupShape) {
  564. shape = new XSSFShapeGroup(this, (CTGroupShape) obj);
  565. } else if (obj instanceof XmlAnyTypeImpl) {
  566. LOG.atWarn().log("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!");
  567. // XmlAnyTypeImpl is returned for AlternateContent
  568. // parts, which might contain a CTDrawing
  569. cur.push();
  570. cur.toFirstChild();
  571. XmlCursor cur2 = null;
  572. try {
  573. // need to parse AlternateContent again,
  574. // otherwise the child elements aren't typed,
  575. // but also XmlAnyTypes
  576. CTDrawing alterWS = CTDrawing.Factory.parse(cur.newXMLStreamReader());
  577. cur2 = alterWS.newCursor();
  578. if (cur2.toFirstChild()) {
  579. addShapes(cur2, lst);
  580. }
  581. } catch (XmlException e) {
  582. LOG.atWarn().withThrowable(e).log("unable to parse CTDrawing in alternate content.");
  583. } finally {
  584. if (cur2 != null) {
  585. cur2.dispose();
  586. }
  587. cur.pop();
  588. }
  589. continue;
  590. } else {
  591. // ignore anything else
  592. continue;
  593. }
  594. assert (shape != null);
  595. shape.anchor = getAnchorFromParent(obj);
  596. lst.add(shape);
  597. } while (cur.toNextSibling());
  598. }
  599. cur.pop();
  600. } while (cur.toNextSibling());
  601. } finally {
  602. cur.dispose();
  603. }
  604. }
  605. private boolean hasOleLink(XmlObject shape) {
  606. QName uriName = new QName(null, "uri");
  607. String xquery = "declare namespace a='" + XSSFRelation.NS_DRAWINGML + "' .//a:extLst/a:ext";
  608. XmlCursor cur = shape.newCursor();
  609. cur.selectPath(xquery);
  610. try {
  611. while (cur.toNextSelection()) {
  612. String uri = cur.getAttributeText(uriName);
  613. if ("{63B3BB69-23CF-44E3-9099-C40C66FF867C}".equals(uri)) {
  614. return true;
  615. }
  616. }
  617. } finally {
  618. cur.dispose();
  619. }
  620. return false;
  621. }
  622. private XSSFAnchor getAnchorFromParent(XmlObject obj) {
  623. XSSFAnchor anchor = null;
  624. XmlObject parentXbean = null;
  625. XmlCursor cursor = obj.newCursor();
  626. if (cursor.toParent()) {
  627. parentXbean = cursor.getObject();
  628. }
  629. cursor.dispose();
  630. if (parentXbean != null) {
  631. if (parentXbean instanceof CTTwoCellAnchor) {
  632. CTTwoCellAnchor ct = (CTTwoCellAnchor) parentXbean;
  633. anchor = new XSSFClientAnchor(ct.getFrom(), ct.getTo());
  634. } else if (parentXbean instanceof CTOneCellAnchor) {
  635. CTOneCellAnchor ct = (CTOneCellAnchor) parentXbean;
  636. anchor = new XSSFClientAnchor(getSheet(), ct.getFrom(), ct.getExt());
  637. } else if (parentXbean instanceof CTAbsoluteAnchor) {
  638. CTAbsoluteAnchor ct = (CTAbsoluteAnchor) parentXbean;
  639. anchor = new XSSFClientAnchor(getSheet(), ct.getPos(), ct.getExt());
  640. }
  641. }
  642. return anchor;
  643. }
  644. @Override
  645. public Iterator<XSSFShape> iterator() {
  646. return getShapes().iterator();
  647. }
  648. /**
  649. * @return the sheet associated with the drawing
  650. */
  651. public XSSFSheet getSheet() {
  652. return (XSSFSheet) getParent();
  653. }
  654. }