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.

SlideShowExtractor.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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.sl.extractor;
  16. import java.util.ArrayList;
  17. import java.util.BitSet;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.function.Consumer;
  21. import java.util.function.Function;
  22. import java.util.function.Predicate;
  23. import com.zaxxer.sparsebits.SparseBitSet;
  24. import org.apache.logging.log4j.LogManager;
  25. import org.apache.logging.log4j.Logger;
  26. import org.apache.poi.extractor.POITextExtractor;
  27. import org.apache.poi.sl.usermodel.MasterSheet;
  28. import org.apache.poi.sl.usermodel.Notes;
  29. import org.apache.poi.sl.usermodel.ObjectShape;
  30. import org.apache.poi.sl.usermodel.Placeholder;
  31. import org.apache.poi.sl.usermodel.PlaceholderDetails;
  32. import org.apache.poi.sl.usermodel.Shape;
  33. import org.apache.poi.sl.usermodel.ShapeContainer;
  34. import org.apache.poi.sl.usermodel.Sheet;
  35. import org.apache.poi.sl.usermodel.Slide;
  36. import org.apache.poi.sl.usermodel.SlideShow;
  37. import org.apache.poi.sl.usermodel.TableCell;
  38. import org.apache.poi.sl.usermodel.TableShape;
  39. import org.apache.poi.sl.usermodel.TextParagraph;
  40. import org.apache.poi.sl.usermodel.TextRun;
  41. import org.apache.poi.sl.usermodel.TextShape;
  42. import org.apache.poi.util.LocaleUtil;
  43. /**
  44. * Common SlideShow extractor
  45. *
  46. * @since POI 4.0.0
  47. */
  48. public class SlideShowExtractor<
  49. S extends Shape<S,P>,
  50. P extends TextParagraph<S,P,? extends TextRun>
  51. > implements POITextExtractor {
  52. private static final Logger LOG = LogManager.getLogger(SlideShowExtractor.class);
  53. // placeholder text for slide numbers
  54. private static final String SLIDE_NUMBER_PH = "‹#›";
  55. protected final SlideShow<S,P> slideshow;
  56. private boolean slidesByDefault = true;
  57. private boolean notesByDefault;
  58. private boolean commentsByDefault;
  59. private boolean masterByDefault;
  60. private Predicate<Object> filter = o -> true;
  61. private boolean doCloseFilesystem = true;
  62. public SlideShowExtractor(final SlideShow<S,P> slideshow) {
  63. this.slideshow = slideshow;
  64. }
  65. /**
  66. * Returns opened document
  67. *
  68. * @return the opened document
  69. */
  70. @Override
  71. public SlideShow<S,P> getDocument() {
  72. return slideshow;
  73. }
  74. /**
  75. * Should a call to getText() return slide text? Default is yes
  76. */
  77. public void setSlidesByDefault(final boolean slidesByDefault) {
  78. this.slidesByDefault = slidesByDefault;
  79. }
  80. /**
  81. * Should a call to getText() return notes text? Default is no
  82. */
  83. public void setNotesByDefault(final boolean notesByDefault) {
  84. this.notesByDefault = notesByDefault;
  85. }
  86. /**
  87. * Should a call to getText() return comments text? Default is no
  88. */
  89. public void setCommentsByDefault(final boolean commentsByDefault) {
  90. this.commentsByDefault = commentsByDefault;
  91. }
  92. /**
  93. * Should a call to getText() return text from master? Default is no
  94. */
  95. public void setMasterByDefault(final boolean masterByDefault) {
  96. this.masterByDefault = masterByDefault;
  97. }
  98. @Override
  99. public POITextExtractor getMetadataTextExtractor() {
  100. return slideshow.getMetadataTextExtractor();
  101. }
  102. /**
  103. * Fetches all the slide text from the slideshow, but not the notes, unless
  104. * you've called setSlidesByDefault() and setNotesByDefault() to change this
  105. */
  106. @Override
  107. public String getText() {
  108. final StringBuilder sb = new StringBuilder();
  109. for (final Slide<S, P> slide : slideshow.getSlides()) {
  110. getText(slide, sb::append);
  111. }
  112. return sb.toString();
  113. }
  114. public String getText(final Slide<S,P> slide) {
  115. final StringBuilder sb = new StringBuilder();
  116. getText(slide, sb::append);
  117. return sb.toString();
  118. }
  119. private void getText(final Slide<S,P> slide, final Consumer<String> consumer) {
  120. if (slidesByDefault) {
  121. printShapeText(slide, consumer);
  122. }
  123. if (masterByDefault) {
  124. final MasterSheet<S,P> ms = slide.getMasterSheet();
  125. printSlideMaster(ms, consumer);
  126. // only print slide layout, if it's a different instance
  127. final MasterSheet<S,P> sl = slide.getSlideLayout();
  128. if (sl != ms) {
  129. printSlideMaster(sl, consumer);
  130. }
  131. }
  132. if (commentsByDefault) {
  133. printComments(slide, consumer);
  134. }
  135. if (notesByDefault) {
  136. printNotes(slide, consumer);
  137. }
  138. }
  139. private void printSlideMaster(final MasterSheet<S,P> master, final Consumer<String> consumer) {
  140. if (master == null) {
  141. return;
  142. }
  143. for (final Shape<S,P> shape : master) {
  144. if (shape instanceof TextShape) {
  145. final TextShape<S,P> ts = (TextShape<S,P>)shape;
  146. final String text = ts.getText();
  147. if (text == null || text.isEmpty() || "*".equals(text)) {
  148. continue;
  149. }
  150. if (ts.isPlaceholder()) {
  151. // don't bother about boiler plate text on master sheets
  152. LOG.atInfo().log("Ignoring boiler plate (placeholder) text on slide master: {}", text);
  153. continue;
  154. }
  155. printTextParagraphs(ts.getTextParagraphs(), consumer);
  156. }
  157. }
  158. }
  159. private void printTextParagraphs(final List<P> paras, final Consumer<String> consumer) {
  160. printTextParagraphs(paras, consumer, "\n");
  161. }
  162. private void printTextParagraphs(final List<P> paras, final Consumer<String> consumer, String trailer) {
  163. printTextParagraphs(paras, consumer, trailer, SlideShowExtractor::replaceTextCap);
  164. }
  165. private void printTextParagraphs(final List<P> paras, final Consumer<String> consumer, String trailer, final Function<TextRun,String> converter) {
  166. for (P p : paras) {
  167. for (TextRun r : p) {
  168. if (filter.test(r)) {
  169. consumer.accept(converter.apply(r));
  170. }
  171. }
  172. if (!trailer.isEmpty() && filter.test(trailer)) {
  173. consumer.accept(trailer);
  174. }
  175. }
  176. }
  177. private void printHeaderFooter(final Sheet<S,P> sheet, final Consumer<String> consumer, final Consumer<String> footerCon) {
  178. final Sheet<S, P> m = (sheet instanceof Slide) ? sheet.getMasterSheet() : sheet;
  179. addSheetPlaceholderDatails(sheet, Placeholder.HEADER, consumer);
  180. addSheetPlaceholderDatails(sheet, Placeholder.FOOTER, footerCon);
  181. if (!masterByDefault) {
  182. return;
  183. }
  184. // write header texts and determine footer text
  185. for (Shape<S, P> s : m) {
  186. if (!(s instanceof TextShape)) {
  187. continue;
  188. }
  189. final TextShape<S, P> ts = (TextShape<S, P>) s;
  190. final PlaceholderDetails pd = ts.getPlaceholderDetails();
  191. if (pd == null || !pd.isVisible() || pd.getPlaceholder() == null) {
  192. continue;
  193. }
  194. switch (pd.getPlaceholder()) {
  195. case HEADER:
  196. printTextParagraphs(ts.getTextParagraphs(), consumer);
  197. break;
  198. case FOOTER:
  199. printTextParagraphs(ts.getTextParagraphs(), footerCon);
  200. break;
  201. case SLIDE_NUMBER:
  202. printTextParagraphs(ts.getTextParagraphs(), footerCon, "\n", SlideShowExtractor::replaceSlideNumber);
  203. break;
  204. case DATETIME:
  205. // currently not supported
  206. default:
  207. break;
  208. }
  209. }
  210. }
  211. private void addSheetPlaceholderDatails(final Sheet<S,P> sheet, final Placeholder placeholder, final Consumer<String> consumer) {
  212. final PlaceholderDetails headerPD = sheet.getPlaceholderDetails(placeholder);
  213. final String headerStr = (headerPD != null) ? headerPD.getText() : null;
  214. if (headerStr != null && filter.test(headerPD)) {
  215. consumer.accept(headerStr);
  216. }
  217. }
  218. private void printShapeText(final Sheet<S,P> sheet, final Consumer<String> consumer) {
  219. final List<String> footer = new LinkedList<>();
  220. printHeaderFooter(sheet, consumer, footer::add);
  221. printShapeText((ShapeContainer<S,P>)sheet, consumer);
  222. footer.forEach(consumer);
  223. }
  224. @SuppressWarnings("unchecked")
  225. private void printShapeText(final ShapeContainer<S,P> container, final Consumer<String> consumer) {
  226. for (Shape<S,P> shape : container) {
  227. if (shape instanceof TextShape) {
  228. printTextParagraphs(((TextShape<S,P>)shape).getTextParagraphs(), consumer);
  229. } else if (shape instanceof TableShape) {
  230. printShapeText((TableShape<S,P>)shape, consumer);
  231. } else if (shape instanceof ShapeContainer) {
  232. printShapeText((ShapeContainer<S,P>)shape, consumer);
  233. }
  234. }
  235. }
  236. @SuppressWarnings("Duplicates")
  237. private void printShapeText(final TableShape<S,P> shape, final Consumer<String> consumer) {
  238. final int nrows = shape.getNumberOfRows();
  239. final int ncols = shape.getNumberOfColumns();
  240. for (int row = 0; row < nrows; row++) {
  241. String trailer = "";
  242. for (int col = 0; col < ncols; col++){
  243. TableCell<S, P> cell = shape.getCell(row, col);
  244. //defensive null checks; don't know if they're necessary
  245. if (cell != null) {
  246. trailer = col < ncols-1 ? "\t" : "\n";
  247. printTextParagraphs(cell.getTextParagraphs(), consumer, trailer);
  248. }
  249. }
  250. if (!trailer.equals("\n") && filter.test("\n")) {
  251. consumer.accept("\n");
  252. }
  253. }
  254. }
  255. private void printComments(final Slide<S,P> slide, final Consumer<String> consumer) {
  256. slide.getComments().stream().filter(filter).map(c -> c.getAuthor()+" - "+c.getText()).forEach(consumer);
  257. }
  258. private void printNotes(final Slide<S,P> slide, final Consumer<String> consumer) {
  259. final Notes<S, P> notes = slide.getNotes();
  260. if (notes == null) {
  261. return;
  262. }
  263. List<String> footer = new LinkedList<>();
  264. printHeaderFooter(notes, consumer, footer::add);
  265. printShapeText(notes, consumer);
  266. footer.forEach(consumer);
  267. }
  268. public List<? extends ObjectShape<S,P>> getOLEShapes() {
  269. final List<ObjectShape<S,P>> oleShapes = new ArrayList<>();
  270. for (final Slide<S,P> slide : slideshow.getSlides()) {
  271. addOLEShapes(oleShapes, slide);
  272. }
  273. return oleShapes;
  274. }
  275. @SuppressWarnings("unchecked")
  276. private void addOLEShapes(final List<ObjectShape<S,P>> oleShapes, ShapeContainer<S,P> container) {
  277. for (Shape<S,P> shape : container) {
  278. if (shape instanceof ShapeContainer) {
  279. addOLEShapes(oleShapes, (ShapeContainer<S,P>)shape);
  280. } else if (shape instanceof ObjectShape) {
  281. oleShapes.add((ObjectShape<S,P>)shape);
  282. }
  283. }
  284. }
  285. private static String replaceSlideNumber(TextRun tr) {
  286. String raw = tr.getRawText();
  287. if (!raw.contains(SLIDE_NUMBER_PH)) {
  288. return raw;
  289. }
  290. TextParagraph<?,?,?> tp = tr.getParagraph();
  291. TextShape<?,?> ps = (tp != null) ? tp.getParentShape() : null;
  292. Sheet<?,?> sh = (ps != null) ? ps.getSheet() : null;
  293. String slideNr = (sh instanceof Slide) ? Integer.toString(((Slide<?,?>)sh).getSlideNumber() + 1) : "";
  294. return raw.replace(SLIDE_NUMBER_PH, slideNr);
  295. }
  296. private static String replaceTextCap(TextRun tr) {
  297. final TextParagraph<?,?,?> tp = tr.getParagraph();
  298. final TextShape<?,?> sh = (tp != null) ? tp.getParentShape() : null;
  299. final Placeholder ph = (sh != null) ? sh.getPlaceholder() : null;
  300. // 0xB acts like cariage return in page titles and like blank in the others
  301. final char sep = (
  302. ph == Placeholder.TITLE ||
  303. ph == Placeholder.CENTERED_TITLE ||
  304. ph == Placeholder.SUBTITLE
  305. ) ? '\n' : ' ';
  306. // PowerPoint seems to store files with \r as the line break
  307. // The messes things up on everything but a Mac, so translate them to \n
  308. String txt = tr.getRawText();
  309. txt = txt.replace('\r', '\n');
  310. txt = txt.replace((char) 0x0B, sep);
  311. switch (tr.getTextCap()) {
  312. case ALL:
  313. txt = txt.toUpperCase(LocaleUtil.getUserLocale());
  314. break;
  315. case SMALL:
  316. txt = txt.toLowerCase(LocaleUtil.getUserLocale());
  317. break;
  318. }
  319. return txt;
  320. }
  321. /**
  322. * Extract the used codepoints for font embedding / subsetting
  323. * @param typeface the typeface/font family of the textruns to examine
  324. * @param italic use {@code true} for italic TextRuns, {@code false} for non-italic ones and
  325. * {@code null} if it doesn't matter
  326. * @param bold use {@code true} for bold TextRuns, {@code false} for non-bold ones and
  327. * {@code null} if it doesn't matter
  328. * @return a bitset with the marked/used codepoints
  329. * @deprecated use {@link #getCodepointsInSparseBitSet(String, Boolean, Boolean)}
  330. */
  331. @Deprecated
  332. public BitSet getCodepoints(String typeface, Boolean italic, Boolean bold) {
  333. final BitSet glyphs = new BitSet();
  334. Predicate<Object> filterOld = filter;
  335. try {
  336. filter = o -> filterFonts(o, typeface, italic, bold);
  337. slideshow.getSlides().forEach(slide ->
  338. getText(slide, s -> s.codePoints().forEach(glyphs::set))
  339. );
  340. } finally {
  341. filter = filterOld;
  342. }
  343. return glyphs;
  344. }
  345. /**
  346. * Extract the used codepoints for font embedding / subsetting
  347. * @param typeface the typeface/font family of the textruns to examine
  348. * @param italic use {@code true} for italic TextRuns, {@code false} for non-italic ones and
  349. * {@code null} if it doesn't matter
  350. * @param bold use {@code true} for bold TextRuns, {@code false} for non-bold ones and
  351. * {@code null} if it doesn't matter
  352. * @return a bitset with the marked/used codepoints
  353. */
  354. public SparseBitSet getCodepointsInSparseBitSet(String typeface, Boolean italic, Boolean bold) {
  355. final SparseBitSet glyphs = new SparseBitSet();
  356. Predicate<Object> filterOld = filter;
  357. try {
  358. filter = o -> filterFonts(o, typeface, italic, bold);
  359. slideshow.getSlides().forEach(slide ->
  360. getText(slide, s -> s.codePoints().forEach(glyphs::set))
  361. );
  362. } finally {
  363. filter = filterOld;
  364. }
  365. return glyphs;
  366. }
  367. private static boolean filterFonts(Object o, String typeface, Boolean italic, Boolean bold) {
  368. if (!(o instanceof TextRun)) {
  369. return false;
  370. }
  371. TextRun tr = (TextRun)o;
  372. return
  373. typeface.equalsIgnoreCase(tr.getFontFamily()) &&
  374. (italic == null || tr.isItalic() == italic) &&
  375. (bold == null || tr.isBold() == bold);
  376. }
  377. @Override
  378. public void setCloseFilesystem(boolean doCloseFilesystem) {
  379. this.doCloseFilesystem = doCloseFilesystem;
  380. }
  381. @Override
  382. public boolean isCloseFilesystem() {
  383. return doCloseFilesystem;
  384. }
  385. @Override
  386. public SlideShow<S,P> getFilesystem() {
  387. return getDocument();
  388. }
  389. }