如何使用Apache POI将含韩语内容的Word文档转换为PDF?已尝试设置UTF-8编码
韩语内容Word转PDF正确实现方案
核心问题说明
仅配置pdfOptions.fontEncoding("UTF-8")无法解决韩语显示异常,根本原因是Apache POI配套的PdfConverter默认未加载支持韩语字符的字体,缺失对应字符的字体渲染映射。
实现步骤
- 提前准备支持韩语的字体:可选择开源的Noto Sans KR、Windows自带的Malgun Gothic、macOS自带的Apple SD Gothic Neo,也可以直接读取操作系统已安装的字体目录
- 为PdfOptions配置自定义字体提供器,注册韩语字体
- 用try-with-resources自动管理流资源,避免内存泄漏
完整可运行代码
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import java.io.*; import com.lowagie.text.pdf.BaseFont; import fr.opensagres.poi.xwpf.converter.core.FontProvider; public class WordToPdfKorean { public static void main(String[] args) throws Exception { String filePath = "/your/file/path/"; String fileName = "test_korean.docx"; String fileWithoutExtension = fileName.substring(0, fileName.lastIndexOf(".")); // try-with-resources自动关闭流 try (InputStream inputStream = new FileInputStream(filePath + fileName); OutputStream outputStream = new FileOutputStream(filePath + fileWithoutExtension + ".pdf"); XWPFDocument xwpfDocument = new XWPFDocument(inputStream)) { PdfOptions pdfOptions = PdfOptions.create(); // 配置字体提供器,注册韩语字体 pdfOptions.fontProvider(new FontProvider() { @Override public BaseFont getFont(String familyName, String encoding, float size, int style, java.awt.Color color) throws Exception { // 替换为你的韩语字体文件路径,也可以读取系统字体目录 String koreanFontPath = filePath + "fonts/NotoSansKR-Regular.ttf"; return BaseFont.createFont(koreanFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } }); // 执行转换 PdfConverter.getInstance().convert(xwpfDocument, outputStream, pdfOptions); } } }
依赖说明
需确保项目引入稳定版本的转换依赖,以Maven为例:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.poi.xwpf.converter.pdf</artifactId> <version>2.0.4</version> </dependency>
注意事项
- 部署到Linux服务器时,需确保服务器上存在对应韩语字体,或者将字体文件打包到项目资源目录中读取,避免服务器缺失字体导致渲染失败
- 需保持poi和xdocreport依赖版本匹配,避免出现类加载冲突
- 若Word文档同时包含多语言内容,可在字体提供器中根据字体名称判断返回对应语言的字体即可兼容
内容的提问来源于stack exchange,提问作者Blink Blank
相关产品推荐
相关产品推荐

