You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用docx4j将HTML转DOCX后LibreOffice图片显示不全的解决方法

问题:docx4j转DOCX后LibreOffice中图片显示异常

使用docx4j将包含Base64格式图片的HTML转换为DOCX文件时,出现以下问题:

  • 在Word中图片显示正常
  • 在LibreOffice中图片无法完全显示;手动设置“将图片附加到符号”后,图片虽能完整显示但会向上偏移

转换代码

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();

RFonts arialRFonts = Context.getWmlObjectFactory().createRFonts();
arialRFonts.setAscii(ReportAndTemplateManagementConstants.FONT_FAMILY);
arialRFonts.setHAnsi(ReportAndTemplateManagementConstants.FONT_FAMILY);
XHTMLImporterImpl.addFontMapping(ReportAndTemplateManagementConstants.FONT_FAMILY, arialRFonts);

XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);

xhtmlImporter.setHyperlinkStyle("Hyperlink");
tempConvertFile =
File.createTempFile("tempConvertFile", StringPool.PERIOD + ReportAndTemplateManagementWebKeys.DOCX);
tempFileOutput =
File.createTempFile("tempFileOutput", StringPool.PERIOD + ReportAndTemplateManagementWebKeys.DOCX);

wordMLPackage.getMainDocumentPart().getContent()
                 .addAll(xhtmlImporter.convert(content, tempFileOutput.getAbsolutePath()));
wordMLPackage.save(tempConvertFile);

待转换的HTML内容

<!DOCTYPE html>
<html>
   <p style="text-align: left;   font-size: 12pt;      font-family: Arial, sans-serif;  margin-top: 0px; margin-bottom: 0px;    line-height: 1.15;   " ><strong>СПРАВКА</strong><br />демо<br />25.05.2023<br /><strong>_________________________________________________________________________</strong></p>
   <p  style="text-align: justify;   font-size: 12pt;      font-family: Arial, sans-serif;   text-indent: 35.4pt;   margin-top: 0px; margin-bottom: 0px;    line-height: 1.15;   " ><ins class="ice-ins ice-cts" data-changedata="" data-cid="2" data-last-change-time="1684999190829" data-time="1684999190829" data-userid="" data-username=""><img src="data:image/png;base64,iV...UVORK5CYII=" /></ins></p>
</html>

问题原因

对比正常显示和显示异常的文档XML后发现:

  • 图片正常显示时,段落行距规则为 w:lineRule="auto"
  • 图片显示不全时,段落行距规则为 w:lineRule="exact"

解决方法

将段落的行距规则设置为auto后,图片可在LibreOffice中正常显示且位置无偏移。

内容的提问来源于stack exchange,提问作者Алина Михалева

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:52:43