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

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