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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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.addRelation(null, XSLFRelation.SLIDE_LAYOUT, layout);
  228. _slides.add(slide);
  229. return slide;
  230. }
  231. /**
  232. * Create a blank slide using the default (first) master.
  233. */
  234. @Override
  235. public XSLFSlide createSlide() {
  236. XSLFSlideMaster sm = _masters.get(0);
  237. XSLFSlideLayout layout = sm.getLayout(SlideLayout.BLANK);
  238. if (layout == null) {
  239. LOG.log(POILogger.WARN, "Blank layout was not found - defaulting to first slide layout in master");
  240. XSLFSlideLayout sl[] = sm.getSlideLayouts();
  241. if (sl.length == 0) {
  242. throw new POIXMLException("SlideMaster must contain a SlideLayout.");
  243. }
  244. layout = sl[0];
  245. }
  246. return createSlide(layout);
  247. }
  248. /**
  249. * Return notes slide for the specified slide or create new if it does not exist yet.
  250. */
  251. public XSLFNotes getNotesSlide(XSLFSlide slide) {
  252. XSLFNotes notesSlide = slide.getNotes();
  253. if (notesSlide == null) {
  254. notesSlide = createNotesSlide(slide);
  255. }
  256. return notesSlide;
  257. }
  258. /**
  259. * Create a blank notes slide.
  260. */
  261. private XSLFNotes createNotesSlide(XSLFSlide slide) {
  262. if (_notesMaster == null) {
  263. createNotesMaster();
  264. }
  265. Integer slideIndex = XSLFRelation.SLIDE.getFileNameIndex(slide);
  266. // add notes slide to presentation
  267. XSLFNotes notesSlide = (XSLFNotes) createRelationship
  268. (XSLFRelation.NOTES, XSLFFactory.getInstance(), slideIndex);
  269. // link slide and notes slide with each other
  270. slide.addRelation(null, XSLFRelation.NOTES, notesSlide);
  271. notesSlide.addRelation(null, XSLFRelation.NOTES_MASTER, _notesMaster);
  272. notesSlide.addRelation(null, XSLFRelation.SLIDE, slide);
  273. notesSlide.importContent(_notesMaster);
  274. return notesSlide;
  275. }
  276. /**
  277. * Create a notes master.
  278. */
  279. public void createNotesMaster() {
  280. RelationPart rp = createRelationship
  281. (XSLFRelation.NOTES_MASTER, XSLFFactory.getInstance(), 1, false);
  282. _notesMaster = rp.getDocumentPart();
  283. CTNotesMasterIdList notesMasterIdList = _presentation.addNewNotesMasterIdLst();
  284. CTNotesMasterIdListEntry notesMasterId = notesMasterIdList.addNewNotesMasterId();
  285. notesMasterId.setId(rp.getRelationship().getId());
  286. Integer themeIndex = 1;
  287. // TODO: check if that list can be replaced by idx = Math.max(idx,themeIdx)
  288. List<Integer> themeIndexList = new ArrayList<Integer>();
  289. for (POIXMLDocumentPart p : getRelations()) {
  290. if (p instanceof XSLFTheme) {
  291. themeIndexList.add(XSLFRelation.THEME.getFileNameIndex(p));
  292. }
  293. }
  294. if (!themeIndexList.isEmpty()) {
  295. Boolean found = false;
  296. for (Integer i = 1; i <= themeIndexList.size(); i++) {
  297. if (!themeIndexList.contains(i)) {
  298. found = true;
  299. themeIndex = i;
  300. }
  301. }
  302. if (!found) {
  303. themeIndex = themeIndexList.size() + 1;
  304. }
  305. }
  306. XSLFTheme theme = (XSLFTheme) createRelationship
  307. (XSLFRelation.THEME, XSLFFactory.getInstance(), themeIndex);
  308. theme.importTheme(getSlides().get(0).getTheme());
  309. _notesMaster.addRelation(null, XSLFRelation.THEME, theme);
  310. }
  311. /**
  312. * Return the Notes Master, if there is one.
  313. * (May not be present if no notes exist)
  314. */
  315. public XSLFNotesMaster getNotesMaster() {
  316. return _notesMaster;
  317. }
  318. @Override
  319. public List<XSLFSlideMaster> getSlideMasters() {
  320. return _masters;
  321. }
  322. /**
  323. * Return all the slides in the slideshow
  324. */
  325. @Override
  326. public List<XSLFSlide> getSlides() {
  327. return _slides;
  328. }
  329. /**
  330. * Returns the list of comment authors, if there is one.
  331. * Will only be present if at least one slide has comments on it.
  332. */
  333. public XSLFCommentAuthors getCommentAuthors() {
  334. return _commentAuthors;
  335. }
  336. /**
  337. *
  338. * @param newIndex 0-based index of the slide
  339. */
  340. public void setSlideOrder(XSLFSlide slide, int newIndex){
  341. int oldIndex = _slides.indexOf(slide);
  342. if(oldIndex == -1) {
  343. throw new IllegalArgumentException("Slide not found");
  344. }
  345. if (oldIndex == newIndex) {
  346. return;
  347. }
  348. // fix the usermodel container
  349. _slides.add(newIndex, _slides.remove(oldIndex));
  350. // fix ordering in the low-level xml
  351. CTSlideIdList sldIdLst = _presentation.getSldIdLst();
  352. CTSlideIdListEntry[] entries = sldIdLst.getSldIdArray();
  353. CTSlideIdListEntry oldEntry = entries[oldIndex];
  354. if (oldIndex < newIndex) {
  355. System.arraycopy(entries, oldIndex + 1, entries, oldIndex, newIndex - oldIndex);
  356. } else {
  357. System.arraycopy(entries, newIndex, entries, newIndex + 1, oldIndex - newIndex);
  358. }
  359. entries[newIndex] = oldEntry;
  360. sldIdLst.setSldIdArray(entries);
  361. }
  362. public XSLFSlide removeSlide(int index){
  363. XSLFSlide slide = _slides.remove(index);
  364. removeRelation(slide);
  365. _presentation.getSldIdLst().removeSldId(index);
  366. return slide;
  367. }
  368. @Override
  369. public Dimension getPageSize(){
  370. CTSlideSize sz = _presentation.getSldSz();
  371. int cx = sz.getCx();
  372. int cy = sz.getCy();
  373. return new Dimension((int)Units.toPoints(cx), (int)Units.toPoints(cy));
  374. }
  375. @Override
  376. public void setPageSize(Dimension pgSize){
  377. CTSlideSize sz = CTSlideSize.Factory.newInstance();
  378. sz.setCx(Units.toEMU(pgSize.getWidth()));
  379. sz.setCy(Units.toEMU(pgSize.getHeight()));
  380. _presentation.setSldSz(sz);
  381. }
  382. @Internal
  383. public CTPresentation getCTPresentation(){
  384. return _presentation;
  385. }
  386. /**
  387. * Adds a picture to the workbook.
  388. *
  389. * @param pictureData The bytes of the picture
  390. * @param format The format of the picture.
  391. *
  392. * @return the picture data
  393. */
  394. @Override
  395. public XSLFPictureData addPicture(byte[] pictureData, PictureType format) {
  396. XSLFPictureData img = findPictureData(pictureData);
  397. if (img != null) {
  398. return img;
  399. }
  400. int imageNumber = _pictures.size();
  401. XSLFRelation relType = XSLFPictureData.getRelationForType(format);
  402. if (relType == null) {
  403. throw new IllegalArgumentException("Picture type "+format+" is not supported.");
  404. }
  405. img = (XSLFPictureData) createRelationship(relType, XSLFFactory.getInstance(), imageNumber + 1, true).getDocumentPart();
  406. img.setIndex(imageNumber);
  407. _pictures.add(img);
  408. try {
  409. OutputStream out = img.getPackagePart().getOutputStream();
  410. out.write(pictureData);
  411. out.close();
  412. } catch (IOException e) {
  413. throw new POIXMLException(e);
  414. }
  415. return img;
  416. }
  417. /**
  418. * Adds a picture to the slideshow.
  419. *
  420. * @param is The stream to read image from
  421. * @param format The format of the picture
  422. *
  423. * @return the picture data
  424. * @since 3.15 beta 2
  425. */
  426. @Override
  427. public XSLFPictureData addPicture(InputStream is, PictureType format) throws IOException
  428. {
  429. return addPicture(IOUtils.toByteArray(is), format);
  430. }
  431. /**
  432. * Adds a picture to the presentation.
  433. *
  434. * @param pict The file containing the image to add
  435. * @param format The format of the picture.
  436. *
  437. * @return the picture data
  438. * @since 3.15 beta 2
  439. */
  440. @Override
  441. public XSLFPictureData addPicture(File pict, PictureType format) throws IOException
  442. {
  443. int length = (int) pict.length();
  444. byte[] data = new byte[length];
  445. FileInputStream is = new FileInputStream(pict);
  446. try {
  447. IOUtils.readFully(is, data);
  448. } finally {
  449. is.close();
  450. }
  451. return addPicture(data, format);
  452. }
  453. /**
  454. * check if a picture with this picture data already exists in this presentation
  455. *
  456. * @param pictureData The picture data to find in the SlideShow
  457. * @return {@code null} if picture data is not found in this slideshow
  458. * @since 3.15 beta 2
  459. */
  460. @Override
  461. public XSLFPictureData findPictureData(byte[] pictureData) {
  462. long checksum = IOUtils.calculateChecksum(pictureData);
  463. byte cs[] = new byte[LittleEndianConsts.LONG_SIZE];
  464. LittleEndian.putLong(cs,0,checksum);
  465. for(XSLFPictureData pic : getPictureData()){
  466. if(Arrays.equals(pic.getChecksum(), cs)) {
  467. return pic;
  468. }
  469. }
  470. return null;
  471. }
  472. /**
  473. * Scan the master slides for the first slide layout with the given name.
  474. *
  475. * @param name The layout name (case-insensitive). Cannot be null.
  476. * @return the first layout found or null on failure
  477. */
  478. public XSLFSlideLayout findLayout(String name) {
  479. for (XSLFSlideMaster master : getSlideMasters()) {
  480. XSLFSlideLayout layout = master.getLayout(name);
  481. if (layout != null) {
  482. return layout;
  483. }
  484. }
  485. return null;
  486. }
  487. public XSLFTableStyles getTableStyles(){
  488. return _tableStyles;
  489. }
  490. CTTextParagraphProperties getDefaultParagraphStyle(int level) {
  491. XmlObject[] o = _presentation.selectPath(
  492. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " +
  493. "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " +
  494. ".//p:defaultTextStyle/a:lvl" +(level+1)+ "pPr");
  495. if(o.length == 1){
  496. return (CTTextParagraphProperties)o[0];
  497. }
  498. return null;
  499. }
  500. @Override
  501. public MasterSheet<XSLFShape,XSLFTextParagraph> createMasterSheet() throws IOException {
  502. // TODO: implement!
  503. throw new UnsupportedOperationException();
  504. }
  505. @Override
  506. public Resources getResources() {
  507. // TODO: implement!
  508. throw new UnsupportedOperationException();
  509. }
  510. }