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.

XMLSlideShow.java 13KB

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