gpt4 book ai didi

java - docx4j 用 html 替换变量

转载 作者:行者123 更新时间:2023-11-30 09:05:59 24 4
gpt4 key购买 nike

我得到了这个用文本替换变量的示例代码,它工作得很好。

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"));

有什么办法可以实现吗?

最佳答案

变量替换的内容都是关于在 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));

关于java - docx4j 用 html 替换变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24628367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com