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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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.Dimension;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.regex.Pattern;
  30. import org.apache.poi.POIXMLDocument;
  31. import org.apache.poi.POIXMLDocumentPart;
  32. import org.apache.poi.POIXMLException;
  33. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  34. import org.apache.poi.openxml4j.opc.OPCPackage;
  35. import org.apache.poi.openxml4j.opc.PackagePart;
  36. import org.apache.poi.sl.usermodel.MasterSheet;
  37. import org.apache.poi.sl.usermodel.PictureData.PictureType;
  38. import org.apache.poi.sl.usermodel.Resources;
  39. import org.apache.poi.sl.usermodel.SlideShow;
  40. import org.apache.poi.util.Beta;
  41. import org.apache.poi.util.IOUtils;
  42. import org.apache.poi.util.Internal;
  43. import org.apache.poi.util.LittleEndian;
  44. import org.apache.poi.util.LittleEndianConsts;
  45. import org.apache.poi.util.POILogFactory;
  46. import org.apache.poi.util.POILogger;
  47. import org.apache.poi.util.PackageHelper;
  48. import org.apache.poi.util.Units;
  49. import org.apache.xmlbeans.XmlException;
  50. import org.apache.xmlbeans.XmlObject;
  51. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties;
  52. import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMasterIdList;
  53. import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMasterIdListEntry;
  54. import org.openxmlformats.schemas.presentationml.x2006.main.CTPresentation;
  55. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdList;
  56. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry;
  57. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry;
  58. import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideSize;
  59. import org.openxmlformats.schemas.presentationml.x2006.main.PresentationDocument;
  60. /**
  61. * High level representation of a ooxml slideshow.
  62. * This is the first object most users will construct whether
  63. * they are reading or writing a slideshow. It is also the
  64. * top level object for creating new slides/etc.
  65. */
  66. @Beta
  67. public class XMLSlideShow extends POIXMLDocument
  68. implements SlideShow<XSLFShape,XSLFTextParagraph> {
  69. private static POILogger _logger = POILogFactory.getLogger(XMLSlideShow.class);
  70. private CTPresentation _presentation;
  71. private List<XSLFSlide> _slides;
  72. private List<XSLFSlideMaster> _masters;
  73. private List<XSLFPictureData> _pictures;
  74. private XSLFTableStyles _tableStyles;
  75. private XSLFNotesMaster _notesMaster;
  76. private XSLFCommentAuthors _commentAuthors;
  77. public XMLSlideShow() {
  78. this(empty());
  79. }
  80. public XMLSlideShow(OPCPackage pkg) {
  81. super(pkg);
  82. try {
  83. if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) {
  84. rebase(getPackage());
  85. }
  86. //build a tree of POIXMLDocumentParts, this presentation being the root
  87. load(XSLFFactory.getInstance());
  88. } catch (Exception e){
  89. throw new POIXMLException(e);
  90. }
  91. }
  92. public XMLSlideShow(InputStream is) throws IOException {
  93. this(PackageHelper.open(is));
  94. }
  95. static OPCPackage empty() {
  96. InputStream is = XMLSlideShow.class.getResourceAsStream("empty.pptx");
  97. if (is == null) {
  98. throw new POIXMLException("Missing resource 'empty.pptx'");
  99. }
  100. try {
  101. return OPCPackage.open(is);
  102. } catch (Exception e){
  103. throw new POIXMLException(e);
  104. } finally {
  105. try {
  106. is.close();
  107. } catch (Exception e) {
  108. throw new POIXMLException(e);
  109. }
  110. }
  111. }
  112. @Override
  113. protected void onDocumentRead() throws IOException {
  114. try {
  115. PresentationDocument doc =
  116. PresentationDocument.Factory.parse(getCorePart().getInputStream(), DEFAULT_XML_OPTIONS);
  117. _presentation = doc.getPresentation();
  118. Map<String, XSLFSlideMaster> masterMap = new HashMap<String, XSLFSlideMaster>();
  119. Map<String, XSLFSlide> shIdMap = new HashMap<String, XSLFSlide>();
  120. for (RelationPart rp : getRelationParts()) {
  121. POIXMLDocumentPart p = rp.getDocumentPart();
  122. if (p instanceof XSLFSlide) {
  123. shIdMap.put(rp.getRelationship().getId(), (XSLFSlide) p);
  124. } else if (p instanceof XSLFSlideMaster) {
  125. masterMap.put(getRelationId(p), (XSLFSlideMaster) p);
  126. } else if (p instanceof XSLFTableStyles){
  127. _tableStyles = (XSLFTableStyles)p;
  128. } else if (p instanceof XSLFNotesMaster) {
  129. _notesMaster = (XSLFNotesMaster)p;
  130. } else if (p instanceof XSLFCommentAuthors) {
  131. _commentAuthors = (XSLFCommentAuthors)p;
  132. }
  133. }
  134. _masters = new ArrayList<XSLFSlideMaster>(masterMap.size());
  135. for (CTSlideMasterIdListEntry masterId : _presentation.getSldMasterIdLst().getSldMasterIdList()) {
  136. XSLFSlideMaster master = masterMap.get(masterId.getId2());
  137. _masters.add(master);
  138. }
  139. _slides = new ArrayList<XSLFSlide>(shIdMap.size());
  140. if (_presentation.isSetSldIdLst()) {
  141. for (CTSlideIdListEntry slId : _presentation.getSldIdLst().getSldIdList()) {
  142. XSLFSlide sh = shIdMap.get(slId.getId2());
  143. if (sh == null) {
  144. _logger.log(POILogger.WARN, "Slide with r:id " + slId.getId() + " was defined, but didn't exist in package, skipping");
  145. continue;
  146. }
  147. _slides.add(sh);
  148. }
  149. }
  150. } catch (XmlException e) {
  151. throw new POIXMLException(e);
  152. }
  153. }
  154. @Override
  155. protected void commit() throws IOException {
  156. PackagePart part = getPackagePart();
  157. OutputStream out = part.getOutputStream();
  158. _presentation.save(out, DEFAULT_XML_OPTIONS);
  159. out.close();
  160. }
  161. /**
  162. * Get the document's embedded files.
  163. */
  164. @Override
  165. public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
  166. return Collections.unmodifiableList(
  167. getPackage().getPartsByName(Pattern.compile("/ppt/embeddings/.*?"))
  168. );
  169. }
  170. @Override
  171. public List<XSLFPictureData> getPictureData() {
  172. if(_pictures == null){
  173. List<PackagePart> mediaParts = getPackage().getPartsByName(Pattern.compile("/ppt/media/.*?"));
  174. _pictures = new ArrayList<XSLFPictureData>(mediaParts.size());
  175. for(PackagePart part : mediaParts){
  176. XSLFPictureData pd = new XSLFPictureData(part);
  177. pd.setIndex(_pictures.size());
  178. _pictures.add(pd);
  179. }
  180. }
  181. return Collections.unmodifiableList(_pictures);
  182. }
  183. /**
  184. * Create a slide and initialize it from the specified layout.
  185. *
  186. * @param layout The layout to use for the new slide.
  187. * @return created slide
  188. */
  189. public XSLFSlide createSlide(XSLFSlideLayout layout) {
  190. int slideNumber = 256, cnt = 1;
  191. CTSlideIdList slideList;
  192. if (!_presentation.isSetSldIdLst()) slideList = _presentation.addNewSldIdLst();
  193. else {
  194. slideList = _presentation.getSldIdLst();
  195. for(CTSlideIdListEntry slideId : slideList.getSldIdArray()){
  196. slideNumber = (int)Math.max(slideId.getId() + 1, slideNumber);
  197. cnt++;
  198. }
  199. // Bug 55791: We also need to check that the resulting file name is not already taken
  200. // this can happen when removing/adding slides
  201. while(true) {
  202. String slideName = XSLFRelation.SLIDE.getFileName(cnt);
  203. boolean found = false;
  204. for (POIXMLDocumentPart relation : getRelations()) {
  205. if (relation.getPackagePart() != null &&
  206. slideName.equals(relation.getPackagePart().getPartName().getName())) {
  207. // name is taken => try next one
  208. found = true;
  209. break;
  210. }
  211. }
  212. if(!found &&
  213. getPackage().getPartsByName(Pattern.compile(Pattern.quote(slideName))).size() > 0) {
  214. // name is taken => try next one
  215. found = true;
  216. }
  217. if (!found) {
  218. break;
  219. }
  220. cnt++;
  221. }
  222. }
  223. RelationPart rp = createRelationship(
  224. XSLFRelation.SLIDE, XSLFFactory.getInstance(), cnt, false);
  225. XSLFSlide slide = rp.getDocumentPart();
  226. CTSlideIdListEntry slideId = slideList.addNewSldId();
  227. slideId.setId(slideNumber);
  228. slideId.setId2(rp.getRelationship().getId());
  229. layout.copyLayout(slide);
  230. slide.addRelation(null, XSLFRelation.SLIDE_LAYOUT, layout);
  231. _slides.add(slide);
  232. return slide;
  233. }
  234. /**
  235. * Create a blank slide using the default (first) master.
  236. */
  237. @Override
  238. public XSLFSlide createSlide() {
  239. XSLFSlideLayout layout = _masters.get(0).getLayout(SlideLayout.BLANK);
  240. if(layout == null) throw new IllegalArgumentException("Blank layout was not found");
  241. return createSlide(layout);
  242. }
  243. /**
  244. * Return notes slide for the specified slide or create new if it does not exist yet.
  245. */
  246. public XSLFNotes getNotesSlide(XSLFSlide slide) {
  247. XSLFNotes notesSlide = slide.getNotes();
  248. if (notesSlide == null) {
  249. notesSlide = createNotesSlide(slide);
  250. }
  251. return notesSlide;
  252. }
  253. /**
  254. * Create a blank notes slide.
  255. */
  256. private XSLFNotes createNotesSlide(XSLFSlide slide) {
  257. if (_notesMaster == null) {
  258. createNotesMaster();
  259. }
  260. Integer slideIndex = XSLFRelation.SLIDE.getFileNameIndex(slide);
  261. // add notes slide to presentation
  262. XSLFNotes notesSlide = (XSLFNotes) createRelationship
  263. (XSLFRelation.NOTES, XSLFFactory.getInstance(), slideIndex);
  264. // link slide and notes slide with each other
  265. slide.addRelation(null, XSLFRelation.NOTES, notesSlide);
  266. notesSlide.addRelation(null, XSLFRelation.NOTES_MASTER, _notesMaster);
  267. notesSlide.addRelation(null, XSLFRelation.SLIDE, slide);
  268. notesSlide.importContent(_notesMaster);
  269. return notesSlide;
  270. }
  271. /**
  272. * Create a notes master.
  273. */
  274. public void createNotesMaster() {
  275. RelationPart rp = createRelationship
  276. (XSLFRelation.NOTES_MASTER, XSLFFactory.getInstance(), 1, false);
  277. _notesMaster = rp.getDocumentPart();
  278. CTNotesMasterIdList notesMasterIdList = _presentation.addNewNotesMasterIdLst();
  279. CTNotesMasterIdListEntry notesMasterId = notesMasterIdList.addNewNotesMasterId();
  280. notesMasterId.setId(rp.getRelationship().getId());
  281. Integer themeIndex = 1;
  282. // TODO: check if that list can be replaced by idx = Math.max(idx,themeIdx)
  283. List<Integer> themeIndexList = new ArrayList<Integer>();
  284. for (POIXMLDocumentPart p : getRelations()) {
  285. if (p instanceof XSLFTheme) {
  286. themeIndexList.add(XSLFRelation.THEME.getFileNameIndex(p));
  287. }
  288. }
  289. if (!themeIndexList.isEmpty()) {
  290. Boolean found = false;
  291. for (Integer i = 1; i <= themeIndexList.size(); i++) {
  292. if (!themeIndexList.contains(i)) {
  293. found = true;
  294. themeIndex = i;
  295. }
  296. }
  297. if (!found) {
  298. themeIndex = themeIndexList.size() + 1;
  299. }
  300. }
  301. XSLFTheme theme = (XSLFTheme) createRelationship
  302. (XSLFRelation.THEME, XSLFFactory.getInstance(), themeIndex);
  303. theme.importTheme(getSlides().get(0).getTheme());
  304. _notesMaster.addRelation(null, XSLFRelation.THEME, theme);
  305. }
  306. /**
  307. * Return the Notes Master, if there is one.
  308. * (May not be present if no notes exist)
  309. */
  310. public XSLFNotesMaster getNotesMaster() {
  311. return _notesMaster;
  312. }
  313. @Override
  314. public List<XSLFSlideMaster> getSlideMasters() {
  315. return _masters;
  316. }
  317. /**
  318. * Return all the slides in the slideshow
  319. */
  320. public List<XSLFSlide> getSlides() {
  321. return _slides;
  322. }
  323. /**
  324. * Returns the list of comment authors, if there is one.
  325. * Will only be present if at least one slide has comments on it.
  326. */
  327. public XSLFCommentAuthors getCommentAuthors() {
  328. return _commentAuthors;
  329. }
  330. /**
  331. *
  332. * @param newIndex 0-based index of the slide
  333. */
  334. public void setSlideOrder(XSLFSlide slide, int newIndex){
  335. int oldIndex = _slides.indexOf(slide);
  336. if(oldIndex == -1) throw new IllegalArgumentException("Slide not found");
  337. if (oldIndex == newIndex) return;
  338. // fix the usermodel container
  339. _slides.add(newIndex, _slides.remove(oldIndex));
  340. // fix ordering in the low-level xml
  341. CTSlideIdList sldIdLst = _presentation.getSldIdLst();
  342. CTSlideIdListEntry[] entries = sldIdLst.getSldIdArray();
  343. CTSlideIdListEntry oldEntry = entries[oldIndex];
  344. if (oldIndex < newIndex) {
  345. System.arraycopy(entries, oldIndex + 1, entries, oldIndex, newIndex - oldIndex);
  346. } else {
  347. System.arraycopy(entries, newIndex, entries, newIndex + 1, oldIndex - newIndex);
  348. }
  349. entries[newIndex] = oldEntry;
  350. sldIdLst.setSldIdArray(entries);
  351. }
  352. public XSLFSlide removeSlide(int index){
  353. XSLFSlide slide = _slides.remove(index);
  354. removeRelation(slide);
  355. _presentation.getSldIdLst().removeSldId(index);
  356. return slide;
  357. }
  358. @Override
  359. public Dimension getPageSize(){
  360. CTSlideSize sz = _presentation.getSldSz();
  361. int cx = sz.getCx();
  362. int cy = sz.getCy();
  363. return new Dimension((int)Units.toPoints(cx), (int)Units.toPoints(cy));
  364. }
  365. @Override
  366. public void setPageSize(Dimension pgSize){
  367. CTSlideSize sz = CTSlideSize.Factory.newInstance();
  368. sz.setCx(Units.toEMU(pgSize.getWidth()));
  369. sz.setCy(Units.toEMU(pgSize.getHeight()));
  370. _presentation.setSldSz(sz);
  371. }
  372. @Internal
  373. public CTPresentation getCTPresentation(){
  374. return _presentation;
  375. }
  376. /**
  377. * Adds a picture to the workbook.
  378. *
  379. * @param pictureData The bytes of the picture
  380. * @param format The format of the picture.
  381. *
  382. * @return the picture data
  383. */
  384. public XSLFPictureData addPicture(byte[] pictureData, PictureType format) {
  385. XSLFPictureData img = findPictureData(pictureData);
  386. if (img != null) return img;
  387. int imageNumber = _pictures.size();
  388. XSLFRelation relType = XSLFPictureData.getRelationForType(format);
  389. if (relType == null) {
  390. throw new IllegalArgumentException("Picture type "+format+" is not supported.");
  391. }
  392. img = (XSLFPictureData) createRelationship(relType, XSLFFactory.getInstance(), imageNumber + 1, true).getDocumentPart();
  393. img.setIndex(imageNumber);
  394. _pictures.add(img);
  395. try {
  396. OutputStream out = img.getPackagePart().getOutputStream();
  397. out.write(pictureData);
  398. out.close();
  399. } catch (IOException e) {
  400. throw new POIXMLException(e);
  401. }
  402. return img;
  403. }
  404. /**
  405. * Adds a picture to the slideshow.
  406. *
  407. * @param is The stream to read image from
  408. * @param format The format of the picture
  409. *
  410. * @return the picture data
  411. * @since 3.15 beta 2
  412. */
  413. @Override
  414. public XSLFPictureData addPicture(InputStream is, PictureType format) throws IOException
  415. {
  416. return addPicture(IOUtils.toByteArray(is), format);
  417. }
  418. /**
  419. * Adds a picture to the presentation.
  420. *
  421. * @param pict The file containing the image to add
  422. * @param format The format of the picture.
  423. *
  424. * @return the picture data
  425. * @since 3.15 beta 2
  426. */
  427. @Override
  428. public XSLFPictureData addPicture(File pict, PictureType format) throws IOException
  429. {
  430. int length = (int) pict.length();
  431. byte[] data = new byte[length];
  432. FileInputStream is = new FileInputStream(pict);
  433. try {
  434. IOUtils.readFully(is, data);
  435. } finally {
  436. is.close();
  437. }
  438. return addPicture(data, format);
  439. }
  440. /**
  441. * check if a picture with this picture data already exists in this presentation
  442. *
  443. * @param pictureData The picture data to find in the SlideShow
  444. * @return {@code null} if picture data is not found in this slideshow
  445. * @since 3.15 beta 2
  446. */
  447. @Override
  448. public XSLFPictureData findPictureData(byte[] pictureData) {
  449. long checksum = IOUtils.calculateChecksum(pictureData);
  450. byte cs[] = new byte[LittleEndianConsts.LONG_SIZE];
  451. LittleEndian.putLong(cs,0,checksum);
  452. for(XSLFPictureData pic : getPictureData()){
  453. if(Arrays.equals(pic.getChecksum(), cs)) {
  454. return pic;
  455. }
  456. }
  457. return null;
  458. }
  459. /**
  460. * Scan the master slides for the first slide layout with the given name.
  461. *
  462. * @param name The layout name (case-insensitive). Cannot be null.
  463. * @return the first layout found or null on failure
  464. */
  465. public XSLFSlideLayout findLayout(String name) {
  466. for (XSLFSlideMaster master : getSlideMasters()) {
  467. XSLFSlideLayout layout = master.getLayout(name);
  468. if (layout != null) {
  469. return layout;
  470. }
  471. }
  472. return null;
  473. }
  474. public XSLFTableStyles getTableStyles(){
  475. return _tableStyles;
  476. }
  477. CTTextParagraphProperties getDefaultParagraphStyle(int level) {
  478. XmlObject[] o = _presentation.selectPath(
  479. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " +
  480. "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " +
  481. ".//p:defaultTextStyle/a:lvl" +(level+1)+ "pPr");
  482. if(o.length == 1){
  483. return (CTTextParagraphProperties)o[0];
  484. }
  485. return null;
  486. }
  487. @Override
  488. public MasterSheet<XSLFShape,XSLFTextParagraph> createMasterSheet() throws IOException {
  489. // TODO: implement!
  490. throw new UnsupportedOperationException();
  491. }
  492. public Resources getResources() {
  493. // TODO: implement!
  494. throw new UnsupportedOperationException();
  495. }
  496. }