2014-07-08 117 views
2

我得到了這個示例代碼,用文本替換變量,它的工作原理非常完美。docx4j用html替換變量

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx")); 

VariablePrepare.prepare(wordMLPackage); 

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();    

HashMap<String, String> mappings = new HashMap<String, String>(); 
mappings.put("firstname", "Name"); //${firstname} 
mappings.put("lastname", "Name"); //${lastname} 

documentPart.variableReplace(mappings); 

wordMLPackage.save(new java.io.File("c:/replace.docx")); 

但現在我必須用html替換變量。我嘗試過這樣的事情。但因爲它不起作用

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx")); 

VariablePrepare.prepare(wordMLPackage); 

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  

String html = "<html><head><title>Import me</title></head><body><p style='color:#ff0000;'>Hello World!</p></body></html>"; 

AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html")); 
afiPart.setBinaryData(html.toString().getBytes()); 
afiPart.setContentType(new ContentType("text/html")); 
Relationship altChunkRel = documentPart.addTargetPart(afiPart); 
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk(); 
ac.setId(altChunkRel.getId()); 


HashMap<String, String> mappings = new HashMap<String, String>(); 
mappings.put("firstname", ac.toString()); //${firstname} 
mappings.put("lastname", "Name"); //${lastname} 

documentPart.variableReplace(mappings); 

wordMLPackage.save(new java.io.File("c:/replace.docx")); 

有什麼辦法可以達到這個目的嗎?

回答

2

變量替換的東西都是關於在WordML中換出簡單的值,它不適用於HTML。

您需要以正確的方式將(X)HTML導入到Word文檔中。在最新版本的docx4j中,這是通過ImportXHTML子項目完成的:https://github.com/plutext/docx4j-ImportXHTML(在早期版本中,XHTML導入代碼是主docx4j項目的一部分)。

本質上,代碼採用格式良好的XHTML,將其解析爲WordML結構(即文本元素,運行,段落等),然後您可以將得到的對象集合插入到您的Word文件中。舉例:

// Where xhtml = String representing well-formed XHTML to insert 
// Where pkg = your WordProcessingMLPackage instance 
XHTMLImporterImpl importer = new XHTMLImporterImpl(pkg); 
pkg.getMainDocumentPart().getContent().addAll(importer.convert(xhtml, null)); 
+0

謝謝。我也試過這個,它的工作原理。但主要問題是如何用xhtml內容替換一個變量,而不是在現有docx的末尾放置xhtml內容。我無能爲力? – Pudelduscher

+1

您可以使用內容控制數據綁定將通過XPath綁定內容控件綁定到包含轉義XHTML的XML元素。或者,您可以按照Ben的描述將XHTML轉換爲WordML,然後在您的VariableReplace映射中使用該WordML。如果內容在插入位置(例如w:p的同胞,而不是在w:t內)有效,則應該起作用。請注意,要以這種方式放置變量,您必須編輯XML,而不是使用Word! – JasonPlutext

+0

聽起來不錯,我會試試看。 – Pudelduscher