PageRenderTime 205ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/pptx/src/org/apache/poi/xslf/usermodel/XMLSlideShow.java

https://github.com/minstrelsy/POI-Android
Java | 394 lines | 253 code | 47 blank | 94 comment | 33 complexity | affb9bb9cdc3dc16020b82db1f4ce116 MD5 | raw file
  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 java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.regex.Pattern;
  25. import org.apache.poi.POIXMLDocument;
  26. import org.apache.poi.POIXMLDocumentPart;
  27. import org.apache.poi.POIXMLException;
  28. import org.apache.poi.POIXMLRelation;
  29. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.openxml4j.opc.PackagePart;
  32. import org.apache.poi.openxml4j.opc.PackagePartName;
  33. import org.apache.poi.openxml4j.opc.TargetMode;
  34. import org.apache.poi.util.Beta;
  35. import org.apache.poi.util.IOUtils;
  36. import org.apache.poi.util.Internal;
  37. import org.apache.poi.util.POILogFactory;
  38. import org.apache.poi.util.POILogger;
  39. import org.apache.poi.util.PackageHelper;
  40. import org.apache.poi.util.Units;
  41. import org.apache.poi.xslf.XSLFSlideShow;
  42. import org.apache.xmlbeans.XmlException;
  43. import org.apache.xmlbeans.XmlObject;
  44. import org.apache.xmlbeans.XmlOptions;
  45. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties;
  46. import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
  47. import org.openxmlformats.schemas.presentationml.x2006.main.CTPresentation;
  48. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdList;
  49. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry;
  50. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideSize;
  51. import org.openxmlformats.schemas.presentationml.x2006.main.PresentationDocument;
  52. import and.awt.Dimension;
  53. /**
  54. * High level representation of a ooxml slideshow.
  55. * This is the first object most users will construct whether
  56. * they are reading or writing a slideshow. It is also the
  57. * top level object for creating new slides/etc.
  58. */
  59. @Beta
  60. public class XMLSlideShow extends POIXMLDocument {
  61. private static POILogger _logger = POILogFactory.getLogger(XMLSlideShow.class);
  62. private CTPresentation _presentation;
  63. private List<XSLFSlide> _slides;
  64. private Map<String, XSLFSlideMaster> _masters;
  65. private List<XSLFPictureData> _pictures;
  66. // private XSLFTableStyles _tableStyles;
  67. private XSLFNotesMaster _notesMaster;
  68. private XSLFCommentAuthors _commentAuthors;
  69. public XMLSlideShow() {
  70. this(empty());
  71. }
  72. public XMLSlideShow(OPCPackage pkg) {
  73. super(pkg);
  74. try {
  75. if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) {
  76. rebase(getPackage());
  77. }
  78. //build a tree of POIXMLDocumentParts, this presentation being the root
  79. load(XSLFFactory.getInstance());
  80. } catch (Exception e){
  81. throw new POIXMLException(e);
  82. }
  83. }
  84. public XMLSlideShow(InputStream is) throws IOException {
  85. this(PackageHelper.open(is));
  86. }
  87. static final OPCPackage empty() {
  88. InputStream is = XMLSlideShow.class.getResourceAsStream("empty.pptx");
  89. if (is == null) {
  90. throw new RuntimeException("Missing resource 'empty.pptx'");
  91. }
  92. try {
  93. return OPCPackage.open(is);
  94. } catch (Exception e){
  95. throw new POIXMLException(e);
  96. }
  97. }
  98. // TODO get rid of this method
  99. @Deprecated
  100. public XSLFSlideShow _getXSLFSlideShow() throws OpenXML4JException, IOException, XmlException{
  101. return new XSLFSlideShow(getPackage());
  102. }
  103. @Override
  104. protected void onDocumentRead() throws IOException {
  105. try {
  106. PresentationDocument doc =
  107. PresentationDocument.Factory.parse(getCorePart().getInputStream());
  108. _presentation = doc.getPresentation();
  109. Map<String, XSLFSlide> shIdMap = new HashMap<String, XSLFSlide>();
  110. _masters = new HashMap<String, XSLFSlideMaster>();
  111. for (POIXMLDocumentPart p : getRelations()) {
  112. if (p instanceof XSLFSlide) {
  113. shIdMap.put(p.getPackageRelationship().getId(), (XSLFSlide) p);
  114. } else if (p instanceof XSLFSlideMaster) {
  115. XSLFSlideMaster master = (XSLFSlideMaster)p;
  116. _masters.put(p.getPackageRelationship().getId(), master);
  117. // }else if (p instanceof XSLFTableStyles){
  118. // _tableStyles = (XSLFTableStyles)p;
  119. } else if (p instanceof XSLFNotesMaster) {
  120. _notesMaster = (XSLFNotesMaster)p;
  121. } else if (p instanceof XSLFCommentAuthors) {
  122. _commentAuthors = (XSLFCommentAuthors)p;
  123. }
  124. }
  125. _slides = new ArrayList<XSLFSlide>();
  126. if (_presentation.isSetSldIdLst()) {
  127. List<CTSlideIdListEntry> slideIds = _presentation.getSldIdLst().getSldIdList();
  128. for (CTSlideIdListEntry slId : slideIds) {
  129. XSLFSlide sh = shIdMap.get(slId.getId2());
  130. if (sh == null) {
  131. _logger.log(POILogger.WARN, "Slide with r:id " + slId.getId() + " was defined, but didn't exist in package, skipping");
  132. continue;
  133. }
  134. _slides.add(sh);
  135. }
  136. }
  137. } catch (XmlException e) {
  138. throw new POIXMLException(e);
  139. }
  140. }
  141. @Override
  142. protected void commit() throws IOException {
  143. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  144. Map<String, String> map = new HashMap<String, String>();
  145. map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
  146. xmlOptions.setSaveSuggestedPrefixes(map);
  147. PackagePart part = getPackagePart();
  148. OutputStream out = part.getOutputStream();
  149. _presentation.save(out, xmlOptions);
  150. out.close();
  151. }
  152. /**
  153. * Get the document's embedded files.
  154. */
  155. public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
  156. return Collections.unmodifiableList(
  157. getPackage().getPartsByName(Pattern.compile("/ppt/embeddings/.*?"))
  158. );
  159. }
  160. /**
  161. * Returns all Pictures, which are referenced from the document itself.
  162. * @return a {@link List} of {@link PackagePart}.
  163. * The returned {@link List} is unmodifiable.
  164. */
  165. public List<XSLFPictureData> getAllPictures() {
  166. if(_pictures == null){
  167. List<PackagePart> mediaParts = getPackage().getPartsByName(Pattern.compile("/ppt/media/.*?"));
  168. _pictures = new ArrayList<XSLFPictureData>(mediaParts.size());
  169. for(PackagePart part : mediaParts){
  170. _pictures.add(new XSLFPictureData(part, null));
  171. }
  172. }
  173. return Collections.unmodifiableList(_pictures);
  174. }
  175. /**
  176. * Create a slide and initialize it from the specified layout.
  177. *
  178. * @param layout
  179. * @return created slide
  180. */
  181. public XSLFSlide createSlide(XSLFSlideLayout layout) {
  182. int slideNumber = 256, cnt = 1;
  183. CTSlideIdList slideList;
  184. if (!_presentation.isSetSldIdLst()) slideList = _presentation.addNewSldIdLst();
  185. else {
  186. slideList = _presentation.getSldIdLst();
  187. for(CTSlideIdListEntry slideId : slideList.getSldIdList()){
  188. slideNumber = (int)Math.max(slideId.getId() + 1, slideNumber);
  189. cnt++;
  190. }
  191. }
  192. XSLFSlide slide = (XSLFSlide)createRelationship(
  193. XSLFRelation.SLIDE, XSLFFactory.getInstance(), cnt);
  194. CTSlideIdListEntry slideId = slideList.addNewSldId();
  195. slideId.setId(slideNumber);
  196. slideId.setId2(slide.getPackageRelationship().getId());
  197. layout.copyLayout(slide);
  198. slide.addRelation(layout.getPackageRelationship().getId(), layout);
  199. PackagePartName ppName = layout.getPackagePart().getPartName();
  200. slide.getPackagePart().addRelationship(ppName, TargetMode.INTERNAL,
  201. layout.getPackageRelationship().getRelationshipType());
  202. _slides.add(slide);
  203. return slide;
  204. }
  205. /**
  206. * Create a blank slide.
  207. */
  208. public XSLFSlide createSlide() {
  209. // String masterId = _presentation.getSldMasterIdLst().getSldMasterIdArray(0).getId2();
  210. // XSLFSlideMaster master = _masters.get(masterId);
  211. // XSLFSlideLayout layout = master.getLayout(SlideLayout.BLANK);
  212. XSLFSlideLayout layout = null;
  213. if(layout == null) throw new IllegalArgumentException("Blank layout was not found");
  214. return createSlide(layout);
  215. }
  216. /**
  217. * Return the Notes Master, if there is one.
  218. * (May not be present if no notes exist)
  219. */
  220. public XSLFNotesMaster getNotesMaster() {
  221. return _notesMaster;
  222. }
  223. public XSLFSlideMaster[] getSlideMasters() {
  224. return _masters.values().toArray(new XSLFSlideMaster[_masters.size()]);
  225. }
  226. /**
  227. * Return all the slides in the slideshow
  228. */
  229. public XSLFSlide[] getSlides() {
  230. return _slides.toArray(new XSLFSlide[_slides.size()]);
  231. }
  232. /**
  233. * Returns the list of comment authors, if there is one.
  234. * Will only be present if at least one slide has comments on it.
  235. */
  236. public XSLFCommentAuthors getCommentAuthors() {
  237. return _commentAuthors;
  238. }
  239. /**
  240. *
  241. * @param newIndex 0-based index of the slide
  242. */
  243. public void setSlideOrder(XSLFSlide slide, int newIndex){
  244. int oldIndex = _slides.indexOf(slide);
  245. if(oldIndex == -1) throw new IllegalArgumentException("Slide not found");
  246. // fix the usermodel container
  247. _slides.add(newIndex, _slides.remove(oldIndex));
  248. // fix ordering in the low-level xml
  249. List<CTSlideIdListEntry> slideIds = _presentation.getSldIdLst().getSldIdList();
  250. CTSlideIdListEntry oldEntry = slideIds.get(oldIndex);
  251. slideIds.add(newIndex, oldEntry);
  252. slideIds.remove(oldEntry);
  253. }
  254. public XSLFSlide removeSlide(int index){
  255. XSLFSlide slide = _slides.remove(index);
  256. removeRelation(slide);
  257. _presentation.getSldIdLst().getSldIdList().remove(index);
  258. return slide;
  259. }
  260. /**
  261. * Returns the current page size
  262. *
  263. * @return the page size
  264. */
  265. public Dimension getPageSize(){
  266. CTSlideSize sz = _presentation.getSldSz();
  267. int cx = sz.getCx();
  268. int cy = sz.getCy();
  269. return new Dimension((int)Units.toPoints(cx), (int)Units.toPoints(cy));
  270. }
  271. /**
  272. * Sets the page size to the given <code>Dimension</code> object.
  273. *
  274. * @param pgSize page size
  275. */
  276. public void setPageSize(Dimension pgSize){
  277. CTSlideSize sz = CTSlideSize.Factory.newInstance();
  278. sz.setCx(Units.toEMU(pgSize.getWidth()));
  279. sz.setCy(Units.toEMU(pgSize.getHeight()));
  280. _presentation.setSldSz(sz);
  281. }
  282. @Internal
  283. public CTPresentation getCTPresentation(){
  284. return _presentation;
  285. }
  286. /**
  287. * Adds a picture to the workbook.
  288. *
  289. * @param pictureData The bytes of the picture
  290. * @param format The format of the picture.
  291. *
  292. * @return the index to this picture (1 based).
  293. * @see XSLFPictureData#PICTURE_TYPE_EMF
  294. * @see XSLFPictureData#PICTURE_TYPE_WMF
  295. * @see XSLFPictureData#PICTURE_TYPE_PICT
  296. * @see XSLFPictureData#PICTURE_TYPE_JPEG
  297. * @see XSLFPictureData#PICTURE_TYPE_PNG
  298. * @see XSLFPictureData#PICTURE_TYPE_DIB
  299. */
  300. public int addPicture(byte[] pictureData, int format) {
  301. XSLFPictureData img = findPictureData(pictureData);
  302. POIXMLRelation relDesc = XSLFPictureData.RELATIONS[format];
  303. if(img == null) {
  304. int imageNumber = _pictures.size();
  305. img = (XSLFPictureData) createRelationship(
  306. XSLFPictureData.RELATIONS[format], XSLFFactory.getInstance(), imageNumber + 1, true);
  307. _pictures.add(img);
  308. try {
  309. OutputStream out = img.getPackagePart().getOutputStream();
  310. out.write(pictureData);
  311. out.close();
  312. } catch (IOException e) {
  313. throw new POIXMLException(e);
  314. }
  315. return _pictures.size() - 1;
  316. } else {
  317. return _pictures.indexOf(img);
  318. }
  319. }
  320. /**
  321. * check if a picture with this picture data already exists in this presentation
  322. */
  323. XSLFPictureData findPictureData(byte[] pictureData){
  324. long checksum = IOUtils.calculateChecksum(pictureData);
  325. for(XSLFPictureData pic : getAllPictures()){
  326. if(pic.getChecksum() == checksum) {
  327. return pic;
  328. }
  329. }
  330. return null;
  331. }
  332. // public XSLFTableStyles getTableStyles(){
  333. // return _tableStyles;
  334. // }
  335. CTTextParagraphProperties getDefaultParagraphStyle(int level) {
  336. XmlObject[] o = _presentation.selectPath(
  337. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " +
  338. "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " +
  339. ".//p:defaultTextStyle/a:lvl" +(level+1)+ "pPr");
  340. if(o.length == 1){
  341. return (CTTextParagraphProperties)o[0];
  342. }
  343. return null;
  344. }
  345. }