使用Docx4j将HTML转DOCX时,div标签Times字体不生效问题
问题:Docx4j转HTML到DOCX时,div标签的Times New Roman字体不生效
使用Docx4j将HTML转换为DOCX文件时出现以下异常:
- 给
<div>标签应用Times New Roman字体的样式完全不生效 - 相同字体样式设置在
<p>标签上可正常转换 - 设置
Segoe UI字体的<div>标签显示正常 - 本地Microsoft Word已安装并支持Times New Roman字体
相关代码
HTML代码
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .times { font-family: 'Times New Roman', Times, serif; font-size: 12px; } .segoe { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 12px; } </style> </head> <body> <div class="times">HELLO in Times New Roman</div> <div class="segoe">HELLO in Segoe UI</div> </body>
Java转换代码
htmlContent = htmlContent.replace("<br>", ""); WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage(); wordPackage.getMainDocumentPart().addAltChunk(AltChunkType.Xhtml, htmlContent.getBytes()); File exportFile = new File(EXPORT_DOCX_FILE_PATH); wordPackage.save(exportFile);
转换效果截图

解决方法
方法1:提升样式优先级
修改CSS,给.times类添加!important强制覆盖默认样式:
.times { font-family: 'Times New Roman', Times, serif !important; font-size: 12px; }
方法2:使用内联样式替代外部样式表
直接在div标签内嵌入样式,绕过外部样式的解析问题:
<div style="font-family: 'Times New Roman', Times, serif; font-size: 12px;">HELLO in Times New Roman</div>
方法3:替换div为p标签(业务允许的情况下)
既然<p>标签可以正常解析Times New Roman样式,直接将div替换为p:
<p class="times">HELLO in Times New Roman</p>
方法4:放弃AltChunk,手动构建DOCX内容
如果上述方法都无效,直接使用Docx4j的API手动创建段落并设置字体,避免HTML解析的兼容性问题:
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage(); MainDocumentPart mainPart = wordPackage.getMainDocumentPart(); // 创建Times New Roman段落 P timesPara = new P(); R timesRun = new R(); Text timesText = new Text("HELLO in Times New Roman"); timesRun.getContent().add(timesText); // 设置字体属性 RPr timesRPr = new RPr(); RFonts rFonts = new RFonts(); rFonts.setAscii("Times New Roman"); rFonts.setEastAsia("Times New Roman"); rFonts.setHAnsi("Times New Roman"); timesRPr.setRFonts(rFonts); // 设置字号(12pt对应24个半磅单位) Sz sz = new Sz(); sz.setVal(java.math.BigInteger.valueOf(24)); timesRPr.setSz(sz); timesRun.setRPr(timesRPr); timesPara.getContent().add(timesRun); mainPart.getContent().add(timesPara); // 创建Segoe UI段落(同理) P segoePara = new P(); R segoeRun = new R(); Text segoeText = new Text("HELLO in Segoe UI"); segoeRun.getContent().add(segoeText); RPr segoeRPr = new RPr(); RFonts segoeFonts = new RFonts(); segoeFonts.setAscii("Segoe UI"); segoeFonts.setEastAsia("Segoe UI"); segoeFonts.setHAnsi("Segoe UI"); segoeRPr.setRFonts(segoeFonts); Sz segoeSz = new Sz(); segoeSz.setVal(java.math.BigInteger.valueOf(24)); segoeRPr.setSz(segoeSz); segoeRun.setRPr(segoeRPr); segoePara.getContent().add(segoeRun); mainPart.getContent().add(segoePara); wordPackage.save(new File(EXPORT_DOCX_FILE_PATH));
内容的提问来源于stack exchange,提问作者Nguyen Tran Nhat Vu
相关产品推荐
相关产品推荐

