2015-09-14 84 views
0

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

回答

0

格式化來自直接格式化(在段落中的rPr和pPr元素中)以及樣式部分。如果未指定樣式,則將使用默認樣式。

您需要查看段落中的XML和樣式部分中的XML。

Microsoft Word(2010至少)有一個有用的「顯示格式」邊欄,它可以幫助您瞭解格式來自何處。點擊底部的「區分風格源」。

docx4j中有代碼(由其PDF輸出使用)來確定有效的格式。我想你可以使用它來專門將源代碼中的有效格式應用到目標中的每次運行。

相關問題