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.

XSLFSheet.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 org.apache.poi.POIXMLDocumentPart;
  17. import org.apache.poi.POIXMLException;
  18. import org.apache.poi.openxml4j.opc.PackagePart;
  19. import org.apache.poi.openxml4j.opc.PackageRelationship;
  20. import org.apache.poi.openxml4j.opc.TargetMode;
  21. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  22. import org.apache.poi.util.Beta;
  23. import org.apache.poi.util.Internal;
  24. import org.apache.xmlbeans.XmlObject;
  25. import org.apache.xmlbeans.XmlOptions;
  26. import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
  27. import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData;
  28. import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector;
  29. import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame;
  30. import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape;
  31. import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture;
  32. import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder;
  33. import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
  34. import javax.xml.namespace.QName;
  35. import java.awt.Graphics2D;
  36. import java.awt.geom.AffineTransform;
  37. import java.io.IOException;
  38. import java.io.OutputStream;
  39. import java.util.ArrayList;
  40. import java.util.HashMap;
  41. import java.util.Iterator;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.regex.Pattern;
  45. @Beta
  46. public abstract class XSLFSheet extends POIXMLDocumentPart implements Iterable<XSLFShape> {
  47. private XSLFCommonSlideData _commonSlideData;
  48. private XSLFDrawing _drawing;
  49. private List<XSLFShape> _shapes;
  50. private CTGroupShape _spTree;
  51. private List<XSLFTextShape>_placeholders;
  52. private Map<Integer, XSLFSimpleShape> _placeholderByIdMap;
  53. private Map<Integer, XSLFSimpleShape> _placeholderByTypeMap;
  54. public XSLFSheet() {
  55. super();
  56. }
  57. public XSLFSheet(PackagePart part, PackageRelationship rel){
  58. super(part, rel);
  59. }
  60. /**
  61. *
  62. * @return the XMLSlideShow this sheet belongs to
  63. */
  64. public XMLSlideShow getSlideShow() {
  65. POIXMLDocumentPart p = getParent();
  66. while(p != null) {
  67. if(p instanceof XMLSlideShow){
  68. return (XMLSlideShow)p;
  69. }
  70. p = p.getParent();
  71. }
  72. throw new IllegalStateException("SlideShow was not found");
  73. }
  74. protected List<XSLFShape> buildShapes(CTGroupShape spTree){
  75. List<XSLFShape> shapes = new ArrayList<XSLFShape>();
  76. for(XmlObject ch : spTree.selectPath("*")){
  77. if(ch instanceof CTShape){ // simple shape
  78. XSLFAutoShape shape = XSLFAutoShape.create((CTShape)ch, this);
  79. shapes.add(shape);
  80. } else if (ch instanceof CTGroupShape){
  81. shapes.add(new XSLFGroupShape((CTGroupShape)ch, this));
  82. } else if (ch instanceof CTConnector){
  83. shapes.add(new XSLFConnectorShape((CTConnector)ch, this));
  84. } else if (ch instanceof CTPicture){
  85. shapes.add(new XSLFPictureShape((CTPicture)ch, this));
  86. } else if (ch instanceof CTGraphicalObjectFrame){
  87. XSLFGraphicFrame shape = XSLFGraphicFrame.create((CTGraphicalObjectFrame)ch, this);
  88. shapes.add(shape);
  89. }
  90. }
  91. return shapes;
  92. }
  93. /**
  94. * @return top-level Xml bean representing this sheet
  95. */
  96. public abstract XmlObject getXmlObject();
  97. @Internal
  98. public XSLFCommonSlideData getCommonSlideData() {
  99. return _commonSlideData;
  100. }
  101. protected void setCommonSlideData(CTCommonSlideData data) {
  102. if(data == null) {
  103. _commonSlideData = null;
  104. } else {
  105. _commonSlideData = new XSLFCommonSlideData(data);
  106. }
  107. }
  108. private XSLFDrawing getDrawing(){
  109. if(_drawing == null) {
  110. _drawing = new XSLFDrawing(this, getSpTree());
  111. }
  112. return _drawing;
  113. }
  114. private List<XSLFShape> getShapeList(){
  115. if(_shapes == null){
  116. _shapes = buildShapes(getSpTree());
  117. }
  118. return _shapes;
  119. }
  120. // shape factory methods
  121. public XSLFAutoShape createAutoShape(){
  122. List<XSLFShape> shapes = getShapeList();
  123. XSLFAutoShape sh = getDrawing().createAutoShape();
  124. shapes.add(sh);
  125. return sh;
  126. }
  127. public XSLFFreeformShape createFreeform(){
  128. List<XSLFShape> shapes = getShapeList();
  129. XSLFFreeformShape sh = getDrawing().createFreeform();
  130. shapes.add(sh);
  131. return sh;
  132. }
  133. public XSLFTextBox createTextBox(){
  134. List<XSLFShape> shapes = getShapeList();
  135. XSLFTextBox sh = getDrawing().createTextBox();
  136. shapes.add(sh);
  137. return sh;
  138. }
  139. public XSLFConnectorShape createConnector(){
  140. List<XSLFShape> shapes = getShapeList();
  141. XSLFConnectorShape sh = getDrawing().createConnector();
  142. shapes.add(sh);
  143. return sh;
  144. }
  145. public XSLFGroupShape createGroup(){
  146. List<XSLFShape> shapes = getShapeList();
  147. XSLFGroupShape sh = getDrawing().createGroup();
  148. shapes.add(sh);
  149. return sh;
  150. }
  151. public XSLFPictureShape createPicture(int pictureIndex){
  152. List<PackagePart> pics = getPackagePart().getPackage()
  153. .getPartsByName(Pattern.compile("/ppt/media/image" + (pictureIndex + 1) + ".*?"));
  154. if(pics.size() == 0) {
  155. throw new IllegalArgumentException("Picture with index=" + pictureIndex + " was not found");
  156. }
  157. PackagePart pic = pics.get(0);
  158. PackageRelationship rel = getPackagePart().addRelationship(
  159. pic.getPartName(), TargetMode.INTERNAL, XSLFRelation.IMAGES.getRelation());
  160. addRelation(rel.getId(), new XSLFPictureData(pic, rel));
  161. XSLFPictureShape sh = getDrawing().createPicture(rel.getId());
  162. sh.resize();
  163. getShapeList().add(sh);
  164. return sh;
  165. }
  166. public XSLFTable createTable(){
  167. List<XSLFShape> shapes = getShapeList();
  168. XSLFTable sh = getDrawing().createTable();
  169. shapes.add(sh);
  170. return sh;
  171. }
  172. /**
  173. * Returns an array containing all of the shapes in this sheet
  174. *
  175. * @return an array of all shapes in this sheet
  176. */
  177. public XSLFShape[] getShapes(){
  178. return getShapeList().toArray(new XSLFShape[_shapes.size()]);
  179. }
  180. /**
  181. * Returns an iterator over the shapes in this sheet
  182. *
  183. * @return an iterator over the shapes in this sheet
  184. */
  185. public Iterator<XSLFShape> iterator(){
  186. return getShapeList().iterator();
  187. }
  188. /**
  189. * Removes the specified shape from this sheet, if it is present
  190. * (optional operation). If this sheet does not contain the element,
  191. * it is unchanged.
  192. *
  193. * @param xShape shape to be removed from this sheet, if present
  194. * @return <tt>true</tt> if this sheet contained the specified element
  195. * @throws IllegalArgumentException if the type of the specified shape
  196. * is incompatible with this sheet (optional)
  197. */
  198. public boolean removeShape(XSLFShape xShape) {
  199. XmlObject obj = xShape.getXmlObject();
  200. CTGroupShape spTree = getSpTree();
  201. if(obj instanceof CTShape){
  202. spTree.getSpList().remove(obj);
  203. } else if (obj instanceof CTGroupShape){
  204. spTree.getGrpSpList().remove(obj);
  205. } else if (obj instanceof CTConnector){
  206. spTree.getCxnSpList().remove(obj);
  207. } else {
  208. throw new IllegalArgumentException("Unsupported shape: " + xShape);
  209. }
  210. return getShapeList().remove(xShape);
  211. }
  212. protected abstract String getRootElementName();
  213. protected CTGroupShape getSpTree(){
  214. if(_spTree == null) {
  215. XmlObject root = getXmlObject();
  216. XmlObject[] sp = root.selectPath(
  217. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:spTree");
  218. if(sp.length == 0) throw new IllegalStateException("CTGroupShape was not found");
  219. _spTree = (CTGroupShape)sp[0];
  220. }
  221. return _spTree;
  222. }
  223. protected final void commit() throws IOException {
  224. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  225. Map<String, String> map = new HashMap<String, String>();
  226. map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
  227. map.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a");
  228. map.put("http://schemas.openxmlformats.org/presentationml/2006/main", "p");
  229. xmlOptions.setSaveSuggestedPrefixes(map);
  230. String docName = getRootElementName();
  231. if(docName != null) {
  232. xmlOptions.setSaveSyntheticDocumentElement(
  233. new QName("http://schemas.openxmlformats.org/presentationml/2006/main", docName));
  234. }
  235. PackagePart part = getPackagePart();
  236. OutputStream out = part.getOutputStream();
  237. getXmlObject().save(out, xmlOptions);
  238. out.close();
  239. }
  240. /**
  241. * Set the contents of this sheet to be a copy of the source sheet.
  242. * This method erases any existing shapes and replaces them with
  243. * object from the source sheet.
  244. *
  245. * @param src the source sheet to copy data from
  246. * @return modified 'this'
  247. */
  248. public XSLFSheet importContent(XSLFSheet src){
  249. _shapes = null;
  250. _spTree = null;
  251. _drawing = null;
  252. // first copy the source xml
  253. getXmlObject().set(src.getXmlObject());
  254. // recursively update each shape
  255. List<XSLFShape> tgtShapes = getShapeList();
  256. List<XSLFShape> srcShapes = src.getShapeList();
  257. for(int i = 0; i < tgtShapes.size(); i++){
  258. XSLFShape s1 = srcShapes.get(i);
  259. XSLFShape s2 = tgtShapes.get(i);
  260. s2.copy(s1);
  261. }
  262. return this;
  263. }
  264. /**
  265. * @return theme (shared styles) associated with this theme.
  266. * By default returns <code>null</code> which means that this sheet is theme-less.
  267. * Sheets that support the notion of themes (slides, masters, layouts, etc.) should override this
  268. * method and return the corresposnding package part.
  269. */
  270. XSLFTheme getTheme(){
  271. return null;
  272. }
  273. /**
  274. *
  275. * @return master of this sheet.
  276. */
  277. public abstract XSLFSheet getMasterSheet();
  278. protected XSLFTextShape getTextShapeByType(Placeholder type){
  279. for(XSLFShape shape : this.getShapes()){
  280. if(shape instanceof XSLFTextShape) {
  281. XSLFTextShape txt = (XSLFTextShape)shape;
  282. if(txt.getTextType() == type) {
  283. return txt;
  284. }
  285. }
  286. }
  287. return null;
  288. }
  289. XSLFSimpleShape getPlaceholder(CTPlaceholder ph) {
  290. XSLFSimpleShape shape = null;
  291. if(ph.isSetIdx()) shape = getPlaceholderById((int)ph.getIdx());
  292. if (shape == null && ph.isSetType()) {
  293. shape = getPlaceholderByType(ph.getType().intValue());
  294. }
  295. return shape;
  296. }
  297. void initPlaceholders() {
  298. if(_placeholders == null) {
  299. _placeholders = new ArrayList<XSLFTextShape>();
  300. _placeholderByIdMap = new HashMap<Integer, XSLFSimpleShape>();
  301. _placeholderByTypeMap = new HashMap<Integer, XSLFSimpleShape>();
  302. for(XSLFShape sh : getShapes()){
  303. if(sh instanceof XSLFTextShape){
  304. XSLFTextShape sShape = (XSLFTextShape)sh;
  305. CTPlaceholder ph = sShape.getCTPlaceholder();
  306. if(ph != null) {
  307. _placeholders.add(sShape);
  308. if(ph.isSetIdx()) {
  309. int idx = (int)ph.getIdx();
  310. _placeholderByIdMap.put(idx, sShape);
  311. }
  312. if(ph.isSetType()){
  313. _placeholderByTypeMap.put(ph.getType().intValue(), sShape);
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. XSLFSimpleShape getPlaceholderById(int id) {
  321. initPlaceholders();
  322. return _placeholderByIdMap.get(id);
  323. }
  324. XSLFSimpleShape getPlaceholderByType(int ordinal) {
  325. initPlaceholders();
  326. return _placeholderByTypeMap.get(ordinal);
  327. }
  328. /**
  329. *
  330. * @param idx 0-based index of a placeholder in the sheet
  331. * @return placeholder
  332. */
  333. public XSLFTextShape getPlaceholder(int idx) {
  334. initPlaceholders();
  335. return _placeholders.get(idx);
  336. }
  337. /**
  338. *
  339. * @return all placeholder shapes in this sheet
  340. */
  341. public XSLFTextShape[] getPlaceholders() {
  342. initPlaceholders();
  343. return _placeholders.toArray(new XSLFTextShape[_placeholders.size()]);
  344. }
  345. /**
  346. * Checks if this <code>sheet</code> displays the specified shape.
  347. *
  348. * Subclasses can override it and skip certain shapes from drawings,
  349. * for instance, slide masters and layouts don't display placeholders
  350. */
  351. protected boolean canDraw(XSLFShape shape){
  352. return true;
  353. }
  354. /**
  355. *
  356. * @return whether shapes on the master sheet should be shown. By default master graphics is turned off.
  357. * Sheets that support the notion of master (slide, slideLayout) should override it and
  358. * check this setting in the sheet XML
  359. */
  360. public boolean getFollowMasterGraphics(){
  361. return false;
  362. }
  363. /**
  364. *
  365. * @return background for this sheet
  366. */
  367. public XSLFBackground getBackground() {
  368. return null;
  369. }
  370. /**
  371. * Render this sheet into the supplied graphics object
  372. *
  373. * @param graphics
  374. */
  375. public void draw(Graphics2D graphics){
  376. XSLFSheet master = getMasterSheet();
  377. if(getFollowMasterGraphics() && master != null) master.draw(graphics);
  378. for(XSLFShape shape : getShapeList()) {
  379. if(!canDraw(shape)) continue;
  380. // remember the initial transform and restore it after we are done with drawing
  381. AffineTransform at = graphics.getTransform();
  382. // concrete implementations can make sense of this hint,
  383. // for example PSGraphics2D or PDFGraphics2D would call gsave() / grestore
  384. graphics.setRenderingHint(XSLFRenderingHint.GSAVE, true);
  385. // apply rotation and flipping
  386. shape.applyTransform(graphics);
  387. // draw stuff
  388. shape.draw(graphics);
  389. // restore the coordinate system
  390. graphics.setTransform(at);
  391. graphics.setRenderingHint(XSLFRenderingHint.GRESTORE, true);
  392. }
  393. }
  394. /**
  395. * Import a picture data from another document.
  396. *
  397. * @param blipId ID of the package relationship to retrieve.
  398. * @param packagePart package part containing the data to import
  399. * @return ID of the created relationship
  400. */
  401. String importBlip(String blipId, PackagePart packagePart) {
  402. PackageRelationship blipRel = packagePart.getRelationship(blipId);
  403. PackagePart blipPart;
  404. try {
  405. blipPart = packagePart.getRelatedPart(blipRel);
  406. } catch (InvalidFormatException e){
  407. throw new POIXMLException(e);
  408. }
  409. XSLFPictureData data = new XSLFPictureData(blipPart, null);
  410. XMLSlideShow ppt = getSlideShow();
  411. int pictureIdx = ppt.addPicture(data.getData(), data.getPictureType());
  412. PackagePart pic = ppt.getAllPictures().get(pictureIdx).getPackagePart();
  413. PackageRelationship rel = getPackagePart().addRelationship(
  414. pic.getPartName(), TargetMode.INTERNAL, blipRel.getRelationshipType());
  415. addRelation(rel.getId(), new XSLFPictureData(pic, rel));
  416. return rel.getId();
  417. }
  418. }