Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

XSLFSheet.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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.xslf.usermodel;
  16. import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.awt.Graphics2D;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Map;
  26. import javax.xml.namespace.QName;
  27. import org.apache.poi.POIXMLDocumentPart;
  28. import org.apache.poi.POIXMLException;
  29. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.openxml4j.opc.PackageNamespaces;
  32. import org.apache.poi.openxml4j.opc.PackagePart;
  33. import org.apache.poi.openxml4j.opc.PackagePartName;
  34. import org.apache.poi.openxml4j.opc.PackageRelationship;
  35. import org.apache.poi.openxml4j.opc.TargetMode;
  36. import org.apache.poi.sl.draw.DrawFactory;
  37. import org.apache.poi.sl.draw.DrawPictureShape;
  38. import org.apache.poi.sl.draw.Drawable;
  39. import org.apache.poi.sl.usermodel.PictureData;
  40. import org.apache.poi.sl.usermodel.Placeholder;
  41. import org.apache.poi.sl.usermodel.Sheet;
  42. import org.apache.poi.util.*;
  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.presentationml.x2006.main.*;
  49. @Beta
  50. public abstract class XSLFSheet extends POIXMLDocumentPart
  51. implements XSLFShapeContainer, Sheet<XSLFShape,XSLFTextParagraph> {
  52. private static POILogger LOG = POILogFactory.getLogger(XSLFSheet.class);
  53. private XSLFDrawing _drawing;
  54. private List<XSLFShape> _shapes;
  55. private CTGroupShape _spTree;
  56. private List<XSLFTextShape>_placeholders;
  57. private Map<Integer, XSLFSimpleShape> _placeholderByIdMap;
  58. private Map<Integer, XSLFSimpleShape> _placeholderByTypeMap;
  59. public XSLFSheet() {
  60. super();
  61. }
  62. /**
  63. * @since POI 3.14-Beta1
  64. */
  65. public XSLFSheet(PackagePart part) {
  66. super(part);
  67. }
  68. /**
  69. * @return the XMLSlideShow this sheet belongs to
  70. */
  71. @Override
  72. public XMLSlideShow getSlideShow() {
  73. POIXMLDocumentPart p = getParent();
  74. while(p != null) {
  75. if(p instanceof XMLSlideShow){
  76. return (XMLSlideShow)p;
  77. }
  78. p = p.getParent();
  79. }
  80. throw new IllegalStateException("SlideShow was not found");
  81. }
  82. protected static List<XSLFShape> buildShapes(CTGroupShape spTree, XSLFSheet sheet){
  83. List<XSLFShape> shapes = new ArrayList<>();
  84. XmlCursor cur = spTree.newCursor();
  85. try {
  86. for (boolean b=cur.toFirstChild();b;b=cur.toNextSibling()) {
  87. XmlObject ch = cur.getObject();
  88. if(ch instanceof CTShape){
  89. // simple shape
  90. XSLFAutoShape shape = XSLFAutoShape.create((CTShape)ch, sheet);
  91. shapes.add(shape);
  92. } else if (ch instanceof CTGroupShape){
  93. shapes.add(new XSLFGroupShape((CTGroupShape)ch, sheet));
  94. } else if (ch instanceof CTConnector){
  95. shapes.add(new XSLFConnectorShape((CTConnector)ch, sheet));
  96. } else if (ch instanceof CTPicture){
  97. shapes.add(new XSLFPictureShape((CTPicture)ch, sheet));
  98. } else if (ch instanceof CTGraphicalObjectFrame){
  99. XSLFGraphicFrame shape = XSLFGraphicFrame.create((CTGraphicalObjectFrame)ch, sheet);
  100. shapes.add(shape);
  101. } else if (ch instanceof XmlAnyTypeImpl) {
  102. // TODO: the link of the XLSF classes to the xml beans objects will
  103. // be broken, when the elements are parsed a second time.
  104. // Unfortunately, the xml schema type can't be set of the alternate
  105. // content element
  106. cur.push();
  107. if (cur.toChild(PackageNamespaces.MARKUP_COMPATIBILITY, "Choice") && cur.toFirstChild()) {
  108. try {
  109. CTGroupShape grp = CTGroupShape.Factory.parse(cur.newXMLStreamReader());
  110. shapes.addAll(buildShapes(grp, sheet));
  111. } catch (XmlException e) {
  112. LOG.log(POILogger.DEBUG, "unparsable alternate content", e);
  113. }
  114. }
  115. cur.pop();
  116. }
  117. }
  118. } finally {
  119. cur.dispose();
  120. }
  121. return shapes;
  122. }
  123. /**
  124. * @return top-level Xml bean representing this sheet
  125. */
  126. public abstract XmlObject getXmlObject();
  127. private XSLFDrawing getDrawing(){
  128. initDrawingAndShapes();
  129. return _drawing;
  130. }
  131. /**
  132. * Returns an array containing all of the shapes in this sheet
  133. *
  134. * @return an array of all shapes in this sheet
  135. */
  136. @Override
  137. public List<XSLFShape> getShapes(){
  138. initDrawingAndShapes();
  139. return _shapes;
  140. }
  141. /**
  142. * Helper method for initializing drawing and shapes in one go.
  143. * If they are initialized separately, there's a risk that shapes
  144. * get added twice, e.g. a shape is added to the drawing, then
  145. * buildShapes is called and at last the shape is added to shape list
  146. */
  147. private void initDrawingAndShapes() {
  148. CTGroupShape cgs = getSpTree();
  149. if(_drawing == null) {
  150. _drawing = new XSLFDrawing(this, cgs);
  151. }
  152. if (_shapes == null) {
  153. _shapes = buildShapes(cgs, this);
  154. }
  155. }
  156. // shape factory methods
  157. @Override
  158. public XSLFAutoShape createAutoShape(){
  159. XSLFAutoShape sh = getDrawing().createAutoShape();
  160. getShapes().add(sh);
  161. sh.setParent(this);
  162. return sh;
  163. }
  164. @Override
  165. public XSLFFreeformShape createFreeform(){
  166. XSLFFreeformShape sh = getDrawing().createFreeform();
  167. getShapes().add(sh);
  168. sh.setParent(this);
  169. return sh;
  170. }
  171. @Override
  172. public XSLFTextBox createTextBox(){
  173. XSLFTextBox sh = getDrawing().createTextBox();
  174. getShapes().add(sh);
  175. sh.setParent(this);
  176. return sh;
  177. }
  178. @Override
  179. public XSLFConnectorShape createConnector(){
  180. XSLFConnectorShape sh = getDrawing().createConnector();
  181. getShapes().add(sh);
  182. sh.setParent(this);
  183. return sh;
  184. }
  185. @Override
  186. public XSLFGroupShape createGroup(){
  187. XSLFGroupShape sh = getDrawing().createGroup();
  188. getShapes().add(sh);
  189. sh.setParent(this);
  190. return sh;
  191. }
  192. @Override
  193. public XSLFPictureShape createPicture(PictureData pictureData){
  194. if (!(pictureData instanceof XSLFPictureData)) {
  195. throw new IllegalArgumentException("pictureData needs to be of type XSLFPictureData");
  196. }
  197. XSLFPictureData xPictureData = (XSLFPictureData)pictureData;
  198. PackagePart pic = xPictureData.getPackagePart();
  199. RelationPart rp = addRelation(null, XSLFRelation.IMAGES, new XSLFPictureData(pic));
  200. XSLFPictureShape sh = getDrawing().createPicture(rp.getRelationship().getId());
  201. new DrawPictureShape(sh).resize();
  202. getShapes().add(sh);
  203. sh.setParent(this);
  204. return sh;
  205. }
  206. public XSLFTable createTable(){
  207. XSLFTable sh = getDrawing().createTable();
  208. getShapes().add(sh);
  209. sh.setParent(this);
  210. return sh;
  211. }
  212. @Override
  213. public XSLFTable createTable(int numRows, int numCols){
  214. if (numRows < 1 || numCols < 1) {
  215. throw new IllegalArgumentException("numRows and numCols must be greater than 0");
  216. }
  217. XSLFTable sh = getDrawing().createTable();
  218. getShapes().add(sh);
  219. sh.setParent(this);
  220. for (int r=0; r<numRows; r++) {
  221. XSLFTableRow row = sh.addRow();
  222. for (int c=0; c<numCols; c++) {
  223. row.addCell();
  224. }
  225. }
  226. return sh;
  227. }
  228. /**
  229. * Returns an iterator over the shapes in this sheet
  230. *
  231. * @return an iterator over the shapes in this sheet
  232. */
  233. @Override
  234. public Iterator<XSLFShape> iterator(){
  235. return getShapes().iterator();
  236. }
  237. @Override
  238. public void addShape(XSLFShape shape) {
  239. throw new UnsupportedOperationException(
  240. "Adding a shape from a different container is not supported -"
  241. + " create it from scratch witht XSLFSheet.create* methods");
  242. }
  243. /**
  244. * Removes the specified shape from this sheet, if it is present
  245. * (optional operation). If this sheet does not contain the element,
  246. * it is unchanged.
  247. *
  248. * @param xShape shape to be removed from this sheet, if present
  249. * @return <tt>true</tt> if this sheet contained the specified element
  250. * @throws IllegalArgumentException if the type of the specified shape
  251. * is incompatible with this sheet (optional)
  252. */
  253. @Override
  254. public boolean removeShape(XSLFShape xShape) {
  255. XmlObject obj = xShape.getXmlObject();
  256. CTGroupShape spTree = getSpTree();
  257. if(obj instanceof CTShape){
  258. spTree.getSpList().remove(obj);
  259. } else if (obj instanceof CTGroupShape) {
  260. spTree.getGrpSpList().remove(obj);
  261. } else if (obj instanceof CTConnector) {
  262. spTree.getCxnSpList().remove(obj);
  263. } else if (obj instanceof CTGraphicalObjectFrame) {
  264. spTree.getGraphicFrameList().remove(obj);
  265. } else if (obj instanceof CTPicture) {
  266. XSLFPictureShape ps = (XSLFPictureShape)xShape;
  267. removePictureRelation(ps);
  268. spTree.getPicList().remove(obj);
  269. } else {
  270. throw new IllegalArgumentException("Unsupported shape: " + xShape);
  271. }
  272. return getShapes().remove(xShape);
  273. }
  274. /**
  275. * Removes all of the elements from this container (optional operation).
  276. * The container will be empty after this call returns.
  277. */
  278. @Override
  279. public void clear() {
  280. List<XSLFShape> shapes = new ArrayList<>(getShapes());
  281. for(XSLFShape shape : shapes){
  282. removeShape(shape);
  283. }
  284. }
  285. protected abstract String getRootElementName();
  286. protected CTGroupShape getSpTree(){
  287. if(_spTree == null) {
  288. XmlObject root = getXmlObject();
  289. XmlObject[] sp = root.selectPath(
  290. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:spTree");
  291. if(sp.length == 0) {
  292. throw new IllegalStateException("CTGroupShape was not found");
  293. }
  294. _spTree = (CTGroupShape)sp[0];
  295. }
  296. return _spTree;
  297. }
  298. @Override
  299. protected final void commit() throws IOException {
  300. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  301. String docName = getRootElementName();
  302. if(docName != null) {
  303. xmlOptions.setSaveSyntheticDocumentElement(
  304. new QName("http://schemas.openxmlformats.org/presentationml/2006/main", docName));
  305. }
  306. PackagePart part = getPackagePart();
  307. OutputStream out = part.getOutputStream();
  308. getXmlObject().save(out, xmlOptions);
  309. out.close();
  310. }
  311. /**
  312. * Set the contents of this sheet to be a copy of the source sheet.
  313. * This method erases any existing shapes and replaces them with
  314. * object from the source sheet.
  315. *
  316. * @param src the source sheet to copy data from
  317. * @return modified 'this'
  318. */
  319. public XSLFSheet importContent(XSLFSheet src){
  320. _spTree = null;
  321. // first copy the source xml
  322. getSpTree().set(src.getSpTree().copy());
  323. wipeAndReinitialize(src, 0);
  324. return this;
  325. }
  326. private void wipeAndReinitialize(XSLFSheet src, int offset) {
  327. // explicitly initialize drawing and shapes from _spTree
  328. _shapes = null;
  329. _drawing = null;
  330. initDrawingAndShapes();
  331. // placeholders will be implicitly initialized when requested
  332. _placeholders = null;
  333. // update each shape according to its own additional copy rules
  334. List<XSLFShape> tgtShapes = getShapes();
  335. List<XSLFShape> srcShapes = src.getShapes();
  336. for(int i = 0; i < srcShapes.size(); i++){
  337. XSLFShape s1 = srcShapes.get(i);
  338. XSLFShape s2 = tgtShapes.get(offset + i);
  339. s2.copy(s1);
  340. }
  341. }
  342. /**
  343. * Append content to this sheet.
  344. *
  345. * @param src the source sheet
  346. * @return modified <code>this</code>.
  347. */
  348. public XSLFSheet appendContent(XSLFSheet src){
  349. int numShapes = getShapes().size();
  350. CTGroupShape spTree = getSpTree();
  351. CTGroupShape srcTree = src.getSpTree();
  352. for(XmlObject ch : srcTree.selectPath("*")){
  353. if(ch instanceof CTShape){ // simple shape
  354. spTree.addNewSp().set(ch.copy());
  355. } else if (ch instanceof CTGroupShape){
  356. spTree.addNewGrpSp().set(ch.copy());
  357. } else if (ch instanceof CTConnector){
  358. spTree.addNewCxnSp().set(ch.copy());
  359. } else if (ch instanceof CTPicture){
  360. spTree.addNewPic().set(ch.copy());
  361. } else if (ch instanceof CTGraphicalObjectFrame){
  362. spTree.addNewGraphicFrame().set(ch.copy());
  363. }
  364. }
  365. wipeAndReinitialize(src, numShapes);
  366. return this;
  367. }
  368. /**
  369. * @return theme (shared styles) associated with this theme.
  370. * By default returns <code>null</code> which means that this sheet is theme-less.
  371. * Sheets that support the notion of themes (slides, masters, layouts, etc.) should override this
  372. * method and return the corresponding package part.
  373. */
  374. XSLFTheme getTheme(){
  375. return null;
  376. }
  377. protected XSLFTextShape getTextShapeByType(Placeholder type){
  378. for(XSLFShape shape : this.getShapes()){
  379. if(shape instanceof XSLFTextShape) {
  380. XSLFTextShape txt = (XSLFTextShape)shape;
  381. if(txt.getTextType() == type) {
  382. return txt;
  383. }
  384. }
  385. }
  386. return null;
  387. }
  388. XSLFSimpleShape getPlaceholder(CTPlaceholder ph) {
  389. XSLFSimpleShape shape = null;
  390. if(ph.isSetIdx()) {
  391. shape = getPlaceholderById((int)ph.getIdx());
  392. }
  393. if (shape == null && ph.isSetType()) {
  394. shape = getPlaceholderByType(ph.getType().intValue());
  395. }
  396. return shape;
  397. }
  398. void initPlaceholders() {
  399. if(_placeholders == null) {
  400. _placeholders = new ArrayList<>();
  401. _placeholderByIdMap = new HashMap<>();
  402. _placeholderByTypeMap = new HashMap<>();
  403. for(XSLFShape sh : getShapes()){
  404. if(sh instanceof XSLFTextShape){
  405. XSLFTextShape sShape = (XSLFTextShape)sh;
  406. CTPlaceholder ph = sShape.getCTPlaceholder();
  407. if(ph != null) {
  408. _placeholders.add(sShape);
  409. if(ph.isSetIdx()) {
  410. int idx = (int)ph.getIdx();
  411. _placeholderByIdMap.put(idx, sShape);
  412. }
  413. if(ph.isSetType()){
  414. _placeholderByTypeMap.put(ph.getType().intValue(), sShape);
  415. }
  416. }
  417. }
  418. }
  419. }
  420. }
  421. XSLFSimpleShape getPlaceholderById(int id) {
  422. initPlaceholders();
  423. return _placeholderByIdMap.get(id);
  424. }
  425. XSLFSimpleShape getPlaceholderByType(int ordinal) {
  426. initPlaceholders();
  427. return _placeholderByTypeMap.get(ordinal);
  428. }
  429. /**
  430. *
  431. * @param idx 0-based index of a placeholder in the sheet
  432. * @return placeholder
  433. */
  434. public XSLFTextShape getPlaceholder(int idx) {
  435. initPlaceholders();
  436. return _placeholders.get(idx);
  437. }
  438. /**
  439. *
  440. * @return all placeholder shapes in this sheet
  441. */
  442. public XSLFTextShape[] getPlaceholders() {
  443. initPlaceholders();
  444. return _placeholders.toArray(new XSLFTextShape[_placeholders.size()]);
  445. }
  446. /**
  447. * Checks if this <code>sheet</code> displays the specified shape.
  448. *
  449. * Subclasses can override it and skip certain shapes from drawings,
  450. * for instance, slide masters and layouts don't display placeholders
  451. */
  452. protected boolean canDraw(XSLFShape shape){
  453. return true;
  454. }
  455. /**
  456. *
  457. * @return whether shapes on the master sheet should be shown. By default master graphics is turned off.
  458. * Sheets that support the notion of master (slide, slideLayout) should override it and
  459. * check this setting in the sheet XML
  460. */
  461. @Override
  462. public boolean getFollowMasterGraphics(){
  463. return false;
  464. }
  465. /**
  466. * @return background for this sheet
  467. */
  468. @Override
  469. public XSLFBackground getBackground() {
  470. return null;
  471. }
  472. /**
  473. * Render this sheet into the supplied graphics object
  474. *
  475. * @param graphics
  476. */
  477. @Override
  478. public void draw(Graphics2D graphics){
  479. DrawFactory drawFact = DrawFactory.getInstance(graphics);
  480. Drawable draw = drawFact.getDrawable(this);
  481. draw.draw(graphics);
  482. }
  483. /**
  484. * Import a picture data from another document.
  485. *
  486. * @param blipId ID of the package relationship to retrieve.
  487. * @param packagePart package part containing the data to import
  488. * @return ID of the created relationship
  489. */
  490. String importBlip(String blipId, PackagePart packagePart) {
  491. PackageRelationship blipRel = packagePart.getRelationship(blipId);
  492. PackagePart blipPart;
  493. try {
  494. blipPart = packagePart.getRelatedPart(blipRel);
  495. } catch (InvalidFormatException e){
  496. throw new POIXMLException(e);
  497. }
  498. XSLFPictureData data = new XSLFPictureData(blipPart);
  499. XMLSlideShow ppt = getSlideShow();
  500. XSLFPictureData pictureData = ppt.addPicture(data.getData(), data.getType());
  501. PackagePart pic = pictureData.getPackagePart();
  502. RelationPart rp = addRelation(blipId, XSLFRelation.IMAGES, new XSLFPictureData(pic));
  503. return rp.getRelationship().getId();
  504. }
  505. /**
  506. * Import a package part into this sheet.
  507. */
  508. PackagePart importPart(PackageRelationship srcRel, PackagePart srcPafrt) {
  509. PackagePart destPP = getPackagePart();
  510. PackagePartName srcPPName = srcPafrt.getPartName();
  511. OPCPackage pkg = destPP.getPackage();
  512. if(pkg.containPart(srcPPName)){
  513. // already exists
  514. return pkg.getPart(srcPPName);
  515. }
  516. destPP.addRelationship(srcPPName, TargetMode.INTERNAL, srcRel.getRelationshipType());
  517. PackagePart part = pkg.createPart(srcPPName, srcPafrt.getContentType());
  518. try {
  519. OutputStream out = part.getOutputStream();
  520. InputStream is = srcPafrt.getInputStream();
  521. IOUtils.copy(is, out);
  522. is.close();
  523. out.close();
  524. } catch (IOException e){
  525. throw new POIXMLException(e);
  526. }
  527. return part;
  528. }
  529. /**
  530. * Helper method for sheet and group shapes
  531. *
  532. * @param pictureShape the picture shapes whose relation is to be removed
  533. */
  534. void removePictureRelation(XSLFPictureShape pictureShape) {
  535. removeRelation(pictureShape.getBlipId());
  536. }
  537. }