专业的JAVA编程教程与资源

网站首页 > java教程 正文

java批量将word文档转换为pdf java实现doc文档转pdf

temp10 2024-12-28 15:46:57 java教程 12 ℃ 0 评论

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

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

java批量将word文档转换为pdf java实现doc文档转pdf

一 jar包下载

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

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

二 pom.xml文件配置

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

<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-words</artifactId>
			<version>15.12.0</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.12.0-jdk16.jar</systemPath>
		</dependency>

三 配置license.xml

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

在 resources目录下新建 license.xml

   <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>

四 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();
                }
            }
        }
    }

}

源文件 目录

执行完上述代码后

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

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表