版本:23.8
编程语言:java
当中间加了一段css样式后,html转word后图片消失,
如果中不加css样式,图片可以正常显示
源文件:
ccc.zip (1.5 MB)
转换代码:
com.aspose.words.Document docx = new com.aspose.words.Document(htmlInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
docx.save(byteArrayOutputStream, SaveFormat.DOCX);
return byteArrayOutputStream.toByteArray();```
@ZhonghaoSun
在将 HTML 转换为 Word 文档时,如果在 <head>
标签中添加了 CSS 样式导致图片消失,这可能与 CSS 样式的处理方式有关。以下是解决此问题的具体步骤:
-
使用 HtmlLoadOptions: 在加载 HTML 文档时,使用 HtmlLoadOptions
来指定如何处理外部资源(如图像)。确保调用 setResourceLoadingCallback
方法,以便正确加载图像。
-
检查 CSS 规则: 确保您添加的 CSS 样式不会影响图像的显示。例如,某些样式可能会导致图像被隐藏或不显示。
-
使用绝对路径: 如果您的图像使用相对路径,尝试将其更改为绝对路径,以确保在转换过程中能够正确找到图像。
-
调试输出: 在转换过程中,添加调试信息,查看是否有任何警告或错误提示,特别是与图像加载相关的。
以下是一个示例代码,展示如何使用 HtmlLoadOptions
:
import com.aspose.words.*;
public byte[] convertHtmlToWord(InputStream htmlInputStream) throws Exception {
HtmlLoadOptions options = new HtmlLoadOptions();
options.setResourceLoadingCallback(new IResourceLoadingCallback() {
@Override
public ResourceLoadingAction resourceLoading(ResourceLoadingArgs args) {
// 处理资源加载
return ResourceLoadingAction.DEFAULT;
}
});
Document docx = new Document(htmlInputStream, options);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
docx.save(byteArrayOutputStream, SaveFormat.DOCX);
return byteArrayOutputStream.toByteArray();
}
请按照上述步骤进行操作,以解决您遇到的问题。如果问题仍然存在或有其他疑问,请随时与我联系,我将乐意提供进一步的帮助!
@ZhonghaoSun 在最新的 25.7 版中没有问题,遗憾的是,除了移除 css 样式,或为每个元素使用内联 css 样式,或在加载 HTML 文档后调整表单与图片的大小外,没有其他合适的解决方法。
你好,麻烦问下【加载 HTML 文档后调整表单与图片的大小】具体怎么操作呢,是修改源HTML文件内容嘛
@ZhonghaoSun 下面是调整形状大小的代码:
Document doc = new Document("ccc.html");
PageSetup pageSetup = doc.getFirstSection().getPageSetup();
double pageWidth = pageSetup.getPageWidth() - pageSetup.getRightMargin() - pageSetup.getLeftMargin();
Shape shape = (Shape) doc.getChild(NodeType.SHAPE, 0, true);
shape.setAspectRatioLocked(false);
shape.setWidth(pageWidth / 2);
double imageHeightPoints = shape.getImageData().getImageSize().getHeightPoints();
double imageHeight = imageHeightPoints > 1584 ? 1584 : imageHeightPoints;
shape.setHeight(imageHeight);
doc.save("output.docx");
Aspose.Words 将表单的宽度和高度限制为 1584 点。我已就此限制创建了一个问题 WORDSNET-28523。