Hello, I will convert the Word stream file into HTML
And then the string returned with this issue (Image file cannot be written to disk. When saving the document to a stream either ImagesFolder should be specified or custom streams should be provided via ImageSaving Callback. Please see documentation for details.), how to handle this issue,The code is as follows:
byte[] fileFromMongoByGridFsId = mongoFileService.getFileFromMongoByGridFsId(fileId);
InputStream inputStream = new ByteArrayInputStream(fileFromMongoByGridFsId);
Document doc = new Document(inputStream);
// 2. 设置HTML保存选项以保留原始格式
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
// 输出更易读的格式
options.setPrettyFormat(true);
// 导出字体资源以保持文本样式
options.setExportFontResources(true);
// 使用外部CSS样式表
options.setCssStyleSheetType(CssStyleSheetType.EXTERNAL);
// 3. 将Word文档转换为HTML字符串
String htmlContent;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
doc.save(baos, options);
htmlContent = new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
return htmlContent;
@Mikeykiss You should do exactly what is suggested in the exception message, i.e. specify folder where images will be saved:
Document doc = new Document("C:\\Temp\\in.docx");
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
options.setImagesFolder("C:\\Temp\\");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos, options);
Or specify ImageSaving Callback:
Document doc = new Document("C:\\Temp\\in.docx");
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
options.setImageSavingCallback(new ImageSavingCallback());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos, options);
private static class ImageSavingCallback implements IImageSavingCallback
{
@Override
public void imageSaving(ImageSavingArgs imageSavingArgs) throws Exception {
// Save the image to nowhere.
imageSavingArgs.setImageStream(new ByteArrayOutputStream());
}
}
Or export images as embedded base64:
Document doc = new Document("C:\\Temp\\in.docx");
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
options.setExportImagesAsBase64(true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos, options);
@alexey.noskov Thank you very much, your code is very useful
1 Like