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"));
이것을 달성 할 수있는 방법이 있습니까?
감사합니다. 나는 또한 이것을 시도하고 작동합니다. 그러나 주된 질문은 기존 docx의 끝에 xhtml 콘텐츠를 저장하는 대신 변수를 xhtml 콘텐츠로 바꾸는 방법입니다. 내가 할 수있는 건 없니? – Pudelduscher
컨텐트 제어 데이터 바인딩을 사용하여 컨텐트 컨트롤을 XPath를 통해 이스케이프 된 XHTML이 포함 된 XML 요소에 바인딩 할 수 있습니다. 또는 Ben이 설명하는대로 XHTML을 WordML로 변환 한 다음 WordML을 VariableReplace 매핑에 사용할 수 있습니다. 내용이 삽입되는 위치에서 내용이 유효하다면 (예 : w : p의 형제, w : t 내부와 반대로), 작동해야합니다. 이 방법으로 변수를 배치하려면 Word를 사용하지 말고 XML을 편집해야합니다. – JasonPlutext
나에게 좋은 소리, 나는 그것을 시도 줄 것이다. – Pudelduscher