在我之前解决了我在docx4j上的问题后,现在可以使用它了。将段落从文档添加到另一个文档
我只是想通过此链接
http://www.smartjava.org/content/create-complex-word-docx-documents-programatically-docx4j
一些修改就可以运行的代码示例。
比方说,我有两个文件。
一个是约2-3页的主要模板。 第二个只有1段文字与各种风格(粗体,斜体,下划线,字体大小等)。
我想用我的模板中的参数替换第二个文档中的段落。
结果是它可以用段落替换我的参数,但是样式有问题。我可以与许多实验观察的是:
- 缩进仍有
- 新线仍有
- 沿太
- 字体颜色/字体大小下划线此举工作
- 粗体/斜体不前来
- 字体家庭不会出现
这里是我的代码
private static void replaceParagraph2(String placeholder, WordprocessingMLPackage template, ContentAccessor addTo) throws Exception {
//get the paragraph
WordprocessingMLPackage paragraph_template = getTemplate("./resources/input/paragraph.docx");
List<Object> paragraphs_LineList = getAllElementFromObject(paragraph_template.getMainDocumentPart(), P.class);
// get the template
List<Object> template_lineList = getAllElementFromObject(template.getMainDocumentPart(), P.class);
int position = 0;
P toReplace = null;
//find placeholder position
for (Object p : template_lineList) {
List<Object> texts = getAllElementFromObject(p, Text.class);
for (Object t : texts) {
Text content = (Text) t;
if (content.getValue().equals(placeholder)) {
toReplace = (P) p;
position = template_lineList.indexOf(toReplace);
break;
}
}
}
//add paragraph into template
for (int i = 0; i < paragraphs_LineList.size(); i++) {
P para = (P) XmlUtils.deepCopy(paragraphs_LineList.get(i));
addTo.getContent().add(position + 1 + i, para);
}
// remove the placeholder on the template
((ContentAccessor)toReplace.getParent()).getContent().remove(toReplace);
}
难道我失去了一些东西?
PS。我调试来检查模板的对象。看来P对象中的大胆值是配置为空。 (我认为这是booleanTrueifNull类型。)