java开发中如何高效稳定地将word文档转换为pdf格式? 这个看似简单的需求,在企业合同电子归档、财务报表批量生成等场景中,开发者往往会遇到不同的问题,如样式错乱、字体丢失等。
今天我们将通过实测代码,展示如何用 spire.doc for java 库实现word到pdf文档的快速转换,并解析其转换选项的灵活配置技巧。
方法一:三步实现核心功能
步骤1:添加maven依赖
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupid>e-iceblue</groupid> <artifactid>spire.xls</artifactid> <version>15.7.7</version> </dependency> </dependencies>
步骤2:核心代码示例 (支持doc和docx格式)
// 创建文档对象模型 document doc = new document(); // 加载word doc.loadfromfile("input.docx"); // 保存为pdf doc.savetofile("output.pdf", fileformat.pdf); doc.dispose();
步骤3:异常处理
try { // 转换代码... } catch (documentexception e) { system.err.println("转换失败: " + e.getmessage()); throw new runtimeexception(e); }
最佳实践
生产环境务必调用doc.close()
释放资源,避免服务器出现文件句柄泄露
方法二:高级选项配置
转换过程中通过 topdfparameterlist 对象可实现精细控制:
选项参数 | 作用描述 | 典型应用场景 |
---|---|---|
isembeddedallfonts | 强制嵌入所有字体 | 跨系统排版一致性 |
setdisablelink | 禁用超链接 | 安全文档转换 |
setpdfconformancelevel | 设置pdf标准规范 | 归档级文档(法律/医疗 |
setcreatewordbookmarks | 保留书签 | 技术手册/论文等长文档导航 |
加密pdf代码示例:
// 高级转换配置示例 topdfparameterlist options = new topdfparameterlist(); options.setpdfconformancelevel(pdfconformancelevel.pdf_a_1_b); // 符合pdf/a-1b标准 string password1 = "e-iceblue"; // 打开密码 string password2 = "123"; // 用户密码 options..getpdfsecurity().encrypt(password1, password2, pdfpermissionsflags.none, pdfencryptionkeysize.key_128_bit); // 加密pdf // 转换word为pdf document doc = new document(); doc.loadfromfile("机密报告.docx"); doc.savetofile("加密文档.pdf", options);
最佳实践
转换时还可通过 setjpegquality
设置图片压缩质量 (0-100),以优化pdf体积。
性能优化建议
内存管理: 处理50页以上文档时,采用分段加载减少单次内存占用
批量处理:
file[] files = new file("docs/").listfiles((dir, name) -> name.endswith(".docx")); for (file file : files) { // 循环调用转换方法... }
方法补充
java 实现 word 转pdf方案
转换方案选择
项目开发我主要使用过 aspose 和 libreoffice,两者代码实现都很简单,转换效果也不错。其他生成 pdf 的方案,比如使用 html 转换、xml、或者直接操作 pdf 模板,实际使用代码逻辑繁琐不易理解,且转换生成效果一般。libreoffice主要是后期做复杂的 pdf 模板导出,使用 word 难以动态填充内容,后来使用 excel,在 java中计算后填充 excel,设置好格式在转换拼接 pdf 最后输出。
- aspose:商业收费软件,免费版有水印。
- libreoffice:开源免费, 需要部署环境安装libreoffice,实际使用需要控制并发与文件大小,避免对服务器整体造成影响。
aspose 实现方案
a. 依赖注入
可以直接下载 jar 包,注入 maven 依赖后直接使用:
<dependency> <groupid>com.aspose</groupid> <artifactid>aspose-words</artifactid> <version>15.8.0</version> <scope>system</scope> <systempath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systempath> </dependency>
b. 实际使用
基本用法:
// 先创建一个临时文件用来存储 pdf string pdfpath = fileutils.gettempdirectorypath() + system.currenttimemillis() + ".pdf"; /** * 加载license 用于破解 不生成水印 */ @sneakythrows private static void getlicense() { try (inputstream is = asposeutil.class.getclassloader().getresourceasstream("lib/license.xml")) { license license = new license(); license.setlicense(is); } } /** * word转pdf * * @param wordpath word文件保存的路径 * @param pdfpath 转换后pdf文件保存的路径 */ public static void wordtopdf(string wordpath, string pdfpath) throws exception { // 获取许可证 getlicense(); // 加载 word 文档 document doc = new document(wordpath); // 设置 pdfsaveoptions pdfsaveoptions options = new pdfsaveoptions(); options.setsaveformat(saveformat.pdf); // 保存为 pdf try (fileoutputstream os = new fileoutputstream(pdfpath)) { doc.save(os, options); } }
<license> <data> <products> <product>aspose.total for java</product> <product>aspose.words for java</product> </products> <editiontype>enterprise</editiontype> <subscriptionexpiry>20991231</subscriptionexpiry> <licenseexpiry>20991231</licenseexpiry> <serialnumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</serialnumber> </data> <signature> snllkgmudf0r8o1kkilwagdgfs2bvjb/2xp8p5iudvfzxmhppo+d0ran1p9tkdjv4abwagkxxj3jcqtqe/2irfqwnpf8itn8afzlv3tjpyed3ywe7it55gz6eijupc7akeoohtb4w2fpox58wwof3snp6sk6jdfiaugehyj9pju= </signature> </license>
c. 常见问题与解决思路
1. 字体文件缺失导致转换乱码
场景:在服务器或 docker 环境下运行,可能会因缺少字体导致 pdf 乱码。
解决方案一:将字体文件放在服务器的字体目录,docker 可在启动时拷贝字体。
# 使用带完整字体库的基础镜像 from openjdk:17-jdk-slim # 拷贝字体 copy fonts/ /usr/share/fonts/truetype/custom/ # 刷新字体缓存 run fc-cache -fv
解决方案二:将字体文件放在项目的 resources/fonts 目录下,导出时拷贝到临时目录后再进行转换(只需转换一次)。
private final static string[] font_paths = {"fonts/songti.ttc"}; fontpath = copytempfilefont(font_paths); /** * 将项目中的字体文件拷贝到临时目录 * @return 字体目录路径 */ private static string copytempfilefont(string... fontpath) { string tempdir = system.getproperty("java.io.tmpdir"); file fontdir = new file(tempdir, "fonts"); if (!fontdir.exists()) { fontdir.mkdirs(); // 创建目录 } for (string path : fontpath) { file tempfile = new file(fontdir, new file(path).getname()); if (!tempfile.exists()) { try (inputstream inputstream = object.class.getclassloader().getresourceasstream(path)) { fileutils.copyinputstreamtofile(inputstream, tempfile); } catch (ioexception e) { throw new runtimeexception("字体文件转换失败,请稍候重试"); } } } return fontdir.getpath() + "/"; }
带字体目录的转换方法:
/** * word转pdf(指定字体目录) * * @param wordpath word文件保存的路径 * @param pdfpath 转换后pdf文件保存的路径 * @param fontpath 字体目录 */ public static void wordtopdf(string wordpath, string pdfpath, string fontpath) throws exception { // 获取许可证 getlicense(); // 设置字体文件夹 fontsettings.setfontsfolder(fontpath, false); // 加载 word 文档 document doc = new document(wordpath); // 设置 pdfsaveoptions pdfsaveoptions options = new pdfsaveoptions(); options.setsaveformat(saveformat.pdf); // 保存为 pdf try (fileoutputstream os = new fileoutputstream(new file(pdfpath))) { doc.save(os, options); } }
libreoffice 实现方案(对应 excel 也可以直接使用)
a. jodconverter(调用 libreoffice 转换)
引入依赖
<dependency> <groupid>org.jodconverter</groupid> <artifactid>jodconverter-local</artifactid> <version>4.4.4</version> </dependency>
代码实现
/** * 转换为pdf(同时适用于 word excel) * @param file * @return * @throws officeexception * @throws ioexception */ public file converttopdf(file file) throws officeexception, ioexception { file temppdffile = file.createtempfile(string.valueof(system.currenttimemillis()), ".pdf"); localofficemanager officemanager = null; try { officemanager = (localofficemanager.builder().install()).build(); officemanager.start(); (localconverter.builder().officemanager(officemanager)).build().convert(file).to(temppdffile).execute(); } finally { if (officemanager != null) { officemanager.stop(); } } return temppdffile; }
拼接pdf
a. 依赖
<dependency> <groupid>com.itextpdf</groupid> <artifactid>itext7-core</artifactid> <version>7.1.15</version> </dependency>
b. 实现
/** * 合并pdf文件 */ private void mergepdffiles(list<file> pdffiles, string outputpath) throws ioexception { try (pdfwriter writer = new pdfwriter(outputpath); pdfdocument mergeddoc = new pdfdocument(writer)) { pdfmerger merger = new pdfmerger(mergeddoc); for (file pdffile : pdffiles) { try (pdfreader reader = new pdfreader(pdffile); pdfdocument sourcedoc = new pdfdocument(reader)) { merger.merge(sourcedoc, 1, sourcedoc.getnumberofpages()); } } } }
到此这篇关于java高效实现word转pdf的完整指南的文章就介绍到这了,更多相关java word转pdf内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论