我想将 html 代码呈现给 docx。而不是呈现html(即表格格式的表格),它只是将html代码作为纯文本写入其中。我正在使用 docx4j-ImportXHTML jar。我使用了此处的代码并对其进行了修改以保存在文件中。
我究竟做错了什么?
public static void xhtmlToDocx(String xhtml, String destinationPath, String fileName)
{
File dir = new File (destinationPath);
File actualFile = new File (dir, fileName);
WordprocessingMLPackage wordMLPackage = null;
try
{
wordMLPackage = WordprocessingMLPackage.createPackage();
}
catch (InvalidFormatException e)
{
e.printStackTrace();
}
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
//XHTMLImporter.setDivHandler(new DivToSdt());
//OutputStream os = null;
OutputStream fos = null;
try
{
fos = new FileOutputStream(actualFile);
wordMLPackage.getMainDocumentPart().getContent().addAll(
XHTMLImporter.convert( xhtml, null) );
System.out.println(XmlUtils.marshaltoString(wordMLPackage
.getMainDocumentPart().getJaxbElement(), true, true));
// Back to XHTML
HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
htmlSettings.setWmlPackage(wordMLPackage);
// output to an OutputStream.
//os = new ByteArrayOutputStream();
// If you want XHTML output
Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML",
true);
Docx4J.toHTML(htmlSettings, fos, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
catch (Docx4JException | FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}