2014-07-08 8 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

감사합니다. 나는 또한 이것을 시도하고 작동합니다. 그러나 주된 질문은 기존 docx의 끝에 xhtml 콘텐츠를 저장하는 대신 변수를 xhtml 콘텐츠로 바꾸는 방법입니다. 내가 할 수있는 건 없니? – Pudelduscher

+1

컨텐트 제어 데이터 바인딩을 사용하여 컨텐트 컨트롤을 XPath를 통해 이스케이프 된 XHTML이 포함 된 XML 요소에 바인딩 할 수 있습니다. 또는 Ben이 설명하는대로 XHTML을 WordML로 변환 한 다음 WordML을 VariableReplace 매핑에 사용할 수 있습니다. 내용이 삽입되는 위치에서 내용이 유효하다면 (예 : w : p의 형제, w : t 내부와 반대로), 작동해야합니다. 이 방법으로 변수를 배치하려면 Word를 사용하지 말고 XML을 편집해야합니다. – JasonPlutext

+0

나에게 좋은 소리, 나는 그것을 시도 줄 것이다. – Pudelduscher

관련 문제