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

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