实现代码如下:
public static byte[] htmlToWord(byte[] content, Integer toType) {
byte[] result = new byte[1];
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(content);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
String line;
StringBuilder html = new StringBuilder();
while ((line = reader.readLine()) != null) {
html.append(line);
}
reader.close();
builder.insertHtml(String.valueOf(html));
doc.save(os, toType);
log.info("html转word成功!");
result = os.toByteArray();
} catch (Exception e) {
log.error("html转word失败!", e);
}
return result;
}
public static byte[] wordToHtml(byte[] content) {
byte[] result = new byte[1] ;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream sbs = new ByteArrayInputStream(content);
Document document = new Document(sbs);
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
options.setExportImagesAsBase64(true);
document.save(os, options);
log.info("html转word成功!");
result = os.toByteArray();
} catch (Exception e) {
log.error("word转html失败!", e);
}
return result;
}