Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.apache.poi.hslf.usermodel;
- import java.awt.Color;
- import java.awt.Rectangle;
- import java.io.FileOutputStream;
- import java.lang.reflect.Field;
- import java.util.Enumeration;
- import javax.swing.JTextPane;
- import javax.swing.text.AttributeSet;
- import javax.swing.text.Element;
- import javax.swing.text.StyledDocument;
- import javax.swing.text.html.CSS;
- import javax.swing.text.html.HTMLDocument;
- import javax.swing.text.html.HTMLEditorKit;
- import org.junit.Test;
- public class TestBla {
- @Test
- public void htmlToTextbox() throws Exception {
- // adding the empty slide
- HSLFSlideShow ppt = new HSLFSlideShow();
- HSLFSlide s = ppt.createSlide();
- HSLFTextBox title = s.addTitle();
- title.setText(" "); // doesn't work if an empty string is used
- HSLFTextRun rt = title.getTextParagraphs().get(0).getTextRuns().get(0);
- rt.setFontColor(Color.black);
- rt.setFontFamily("Arial");
- rt.setFontSize(44.);
- Rectangle anchorInTheSlide = new java.awt.Rectangle(5, 5, 710, 125);
- title.setAnchor(anchorInTheSlide);
- // prepare
- JTextPane pad = new JTextPane();
- pad.setContentType("text/html");
- HTMLEditorKit kit = (HTMLEditorKit)pad.getEditorKit();
- HTMLDocument htmldoc = (HTMLDocument)kit.createDefaultDocument();
- kit.insertHTML(htmldoc, htmldoc.getLength(), "<p>paragraph <i>1</i></p>", 0, 0, null);
- kit.insertHTML(htmldoc, htmldoc.getLength(), "<p>paragraph <span style=\"color:red\">2</span></p>", 0, 0, null);
- pad.setDocument(htmldoc);
- // convert
- StyledDocument doc = pad.getStyledDocument();
- int lastPos=-1;
- while (lastPos < doc.getLength()) {
- Element line = doc.getParagraphElement(lastPos+1);
- lastPos = line.getEndOffset();
- boolean newParagraph = true;
- for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) {
- final Element frag = line.getElement(elIdx);
- String subtext = doc.getText(frag.getStartOffset(), frag.getEndOffset()-frag.getStartOffset());
- HSLFTextRun run = title.appendText(subtext, newParagraph);
- newParagraph = false;
- final AttributeSet as = frag.getAttributes();
- final Enumeration<?> ae = as.getAttributeNames();
- while (ae.hasMoreElements()) {
- final Object attrib = ae.nextElement();
- if (CSS.Attribute.COLOR.equals(attrib)) {
- // I don't know how to really work with the CSS-swing class ...
- Field f = as.getAttribute(attrib).getClass().getDeclaredField("c");
- f.setAccessible(true);
- Color c = (Color)f.get(as.getAttribute(attrib));
- run.setFontColor(c);
- } else if (CSS.Attribute.FONT_STYLE.equals(attrib)) {
- if ("italic".equals(as.getAttribute(attrib).toString())) {
- run.setItalic(true);
- }
- } else if (CSS.Attribute.FONT_WEIGHT.equals(attrib)) {
- if ("bold".equals(as.getAttribute(attrib).toString())) {
- run.setBold(true);
- }
- }
- }
- }
- }
- FileOutputStream fos = new FileOutputStream("bla.ppt");
- ppt.write(fos);
- fos.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment