今天有个做人事的朋友在整理合同,大概有200多个word文档,希望转换为pdf格式。免费的方式只能一个一个转,批量的收费,咋办。

体现java强大的时刻到了。我就顺手写了个批量将word转为pdf的java代码。

一 jar包下载

使用的是aspose-words-15.12.0-jdk16.jar 这个jar,

下载链接: https://pan.baidu.com/s/1X_gO1cwLUzoHGtX8UmF6XA 提取码: a3f2

二 pom.xml文件配置

将下载的jar包复制到 resources/lib目录下。

com.aspose aspose-words 15.12.0 system ${project.basedir}/src/main/resources/lib/aspose-words-15.12.0-jdk16.jar

三 配置license.xml

如果不配置的话,会有水印。

在 resources目录下新建 license.xml

Aspose.Total for Java

Aspose.Words for Java Enterprise 20991231 20991231 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7 sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=

四 java代码

public class WordToPdfTest { public static void main(String[] args) throws Exception { //org.springframework.core.io.ClassPathResource //加载licence.xml InputStream inputStream = new ClassPathResource("/license.xml").getInputStream(); License licenseObj = new License(); licenseObj.setLicense(inputStream); //word文件存放的目录 File sourcedir = new File("D:\tmp\dev_source"); File[] sourceFiles = sourcedir.listFiles(); //循环遍历word文件 for (File file : sourceFiles) { //获取带后缀的文件名 123.docx String sourceName = file.getName(); //去掉文件名后缀 String targetName = sourceName.split("\.")[0]; FileOutputStream os = null; try { //以原文件名 创建一个 pdf File targetFile = new File("D:\tmp\dev_target\" + targetName + ".pdf"); //构建pdf文件输出流 os = new FileOutputStream(targetFile); //已file的文件绝对路径为参数,获取Document对象 Document doc = new Document(file.getAbsolutePath()); //将文档内容 以pdf格式 输出到上面的输出流。 doc.save(os, SaveFormat.PDF); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) { os.close(); } } } } }

源文件 目录

执行完上述代码后

试验成功。欢迎大家尝试。