在我之前解決了我在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類型。)