使用POI用Java中的RTF内容填充Word文档表单字段

时间:2018-10-02 13:15:19

标签: java html apache-poi rtf

我有一个Word文档(.docx),其中包含我想由我的应用程序填充的字母的“框架”。在应用程序中,用户可以在文本编辑器(产生html)中为字母创建内容。 我的目标是将此html(或转换为rtf)插入到word模板的预定义表单字段中。

我现在所能做的就是替换模板中的一些文本:

String htmlText = "<html><head></head><body><h1>Some text</h1></body></html>";

XWPFDocument doc = new XWPFDocument(new FileInputStream("P:/temp/Template.docx"));

ByteArrayOutputStream bos = new ByteArrayOutputStream();

Document iDoc = new Document();
RtfWriter2.getInstance(iDoc, bos);
HtmlParser hp = new HtmlParser();

hp.go(iDoc, new ByteArrayInputStream(htmlText.getBytes()));

doc = replaceText(doc, "$VAR", bos.toString("UTF-8"));
saveWord("P:/temp/CreatedLetter.docx", doc);

可以这样替换文本:

protected XWPFDocument replaceText(XWPFDocument doc, String findText, String replaceText) {

    XSSFRichTextString rtfString = new XSSFRichTextString();
    rtfString.append(replaceText);

    List<XWPFParagraph> paragraphs = doc.getParagraphs();
    for (XWPFParagraph p : paragraphs) {

        if (p.getText() != null && p.getText().equals(findText)) {

            for (XWPFRun r : p.getRuns()) {
                String text = r.getText(0);
                if (text != null && text.contains(findText)) {
                    text = text.replace(findText, replaceText);
                    r.setText(text,0);
                }
            }
        }
    }
    return doc;
}

保存文档后,富文本将另存为纯文本。

因此,我尝试在模板中使用表单字段(RTF文本表单字段),然后在其中插入文本。但是,从文档返回表单字段的API是只读的,因此无法修改表单字段的内容。

有什么方法可以将html或rtf插入到word文档中,以便像在浏览器或html编辑器中一样显示它?

在此先感谢您的帮助!

霍尔格

0 个答案:

没有答案