将样式文本写入 .docx 文件 [英] Writing Styled Text to a .docx file

查看:33
本文介绍了将样式文本写入 .docx 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个将文本写入 .docx 文件的应用程序.我的应用程序使用 JTextPane,因此用户可以编写他/她想要的任何内容,它还提供了许多按钮,例如粗体、字体颜色、字体大小...等.我遇到的问题是在写入 .docx 文件时保持 JTextPane 上文本的样式.我对 Swing 和 Apache POI 还很陌生,因此示例代码和/或详细解释会有所帮助.

I'm trying to write an application that will write text to a .docx file. My application uses a JTextPane so the user can write whatever he/she wants, and it also provides many buttons such as bold, font color, font size... ect. What I'm having a problem with is maintaining the style of the text on the JTextPane to when I write to the .docx file. I'm fairly new to Swing and Apache POI so example code and/or a detailed explanation would be helpful.

我所拥有的是:(pad 指的是 JTextPane)

What I have is this: (pad refers to the 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 并相应地设置 textruns.

For my example I assume you'd use a HTMLEditorKit in your JTextPane. I would then parse the StyledDocument of the pane and set the textruns accordingly.

当然这只是一个开始,您需要解析所有可能的样式并在下面的循环中自己转换它们.

Of course this is just a starter, you'd need to parse all the possible styles and convert them yourself in the loop below.

我必须承认,我从未对 HTMLEditorKit 做过任何事情,因此我不知道如何正确处理 CSS.CssValues.

I've to admit, that I've never done something with the HTMLEditorKit and therefore I don't know how to handle the CSS.CssValues properly.

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();
    }
}

这篇关于将样式文本写入 .docx 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆