我正在尝试编写一个将文本写入 .docx 文件的应用程序。我的应用程序使用 JTextPane,因此用户可以编写他/她想要的任何内容,并且它还提供了许多按钮,例如粗体、字体颜色、字体大小...等。我遇到的问题是在写入 .docx 文件时保持 JTextPane 上文本的样式。我对 Swing 和 Apache POI 相当陌生,因此示例代码和/或详细解释会很有帮助。
我所拥有的是这样的:(pad指的是JTextPane)
FileOutputStream output = new FileOutputStream(file);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(pad.getText());
document.write(output);
output.close();
最佳答案
对于我的示例,我假设您会使用 HTMLEditorKit
在你的JTextPane
。然后我会解析 StyledDocument
Pane 并相应地设置文本运行。
当然这只是一个开始,您需要解析所有可能的样式并在下面的循环中自行转换它们。
我必须承认,我从未使用 HTMLEditorKit 做过任何事情,因此我不知道如何正确处理 CSS.CssValues。
import java.awt.Color;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import org.apache.poi.xwpf.usermodel.*;
public class StyledText {
public static void main(String[] args) throws Exception {
// 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 <b>1</b></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();
XWPFDocument docX = new XWPFDocument();
int lastPos=-1;
while (lastPos < doc.getLength()) {
Element line = doc.getParagraphElement(lastPos+1);
lastPos = line.getEndOffset();
XWPFParagraph paragraph = docX.createParagraph();
for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) {
final Element frag = line.getElement(elIdx);
XWPFRun run = paragraph.createRun();
String subtext = doc.getText(frag.getStartOffset(), frag.getEndOffset()-frag.getStartOffset());
run.setText(subtext);
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.setColor(String.format("%1$02X%2$02X%3$02X", c.getRed(),c.getGreen(),c.getBlue()));
} else if (CSS.Attribute.FONT_WEIGHT.equals(attrib)) {
if ("bold".equals(as.getAttribute(attrib).toString())) {
run.setBold(true);
}
}
}
}
}
FileOutputStream fos = new FileOutputStream("test.docx");
docX.write(fos);
fos.close();
}
}
关于java - 将样式文本写入 .docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17800017/