Java如何将Word转换成PDF

目录

java中word转换PDF的常用用法

documents4j用法


java中word转换PDF的常用用法

1、POI

POI是Apache下的一个Java类库,可以帮助我们实现Java与各种Office格式文件的互相转换。(不推荐,只能用于文字的文档,如果有图片和表格则会排版错误)

2、Aspose.Words
Aspose.Words for Java是一个原生库,为开发人员提供了丰富的功能来创建、编辑和转换 Word、PDF、Web 文档,而无需在系统上安装 Microsoft Word 环境。这个工具非常好用,maven上有对应的依赖和jar包,但是转换后会有水印,因为他是(收费的)

3、spire.doc.free
Spire.Doc for Java是一个专业的 Word API,它使 Java 应用程序能够创建、转换、操作和打印 Word文档,而无需依赖 Microsoft Word。通过使用这个多功能库,开发人员可以轻松处理大量任务,例如插入图像、超链接、 数字签名、书签和水印、设置页眉和页脚、创建表格、设置背景图像以及添加脚注和尾注。这个跟aspose功能感觉有点差不多,也很好用,但是收费比对还是aspose更好用,而且这个也是收费的

4、documents4j
官网:https://documents4j.com/#/

GitHub:https://github.com/documents4j/documents4j

documents4j 是一个跨平台的文档转换库,并且可以在 Linux 上进行 Word 转 PDF 的操作。这个比较推荐,开源而且转换后也不会有格式错误(推荐)


documents4j用法

注意Windows和linux系统的代码不一样

1.Windows系统用法

1.导入依赖,本地必须要有wps或者微软的office

   <!--word转换为PDF文档-->
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.0.3</version>
        </dependency>

2.编写转换代码(这里我都是传入input输出output然后根据流自己操作)

package com.daysuns.dmas.module.testReportwd.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
public class Documents4jUtil {

    /**
     * word转pdf
     *
     */
    public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        String os = System.getProperty("os.name").toLowerCase();
        log.info("convertWordToPdf 当前操作系统:{}", os);
        if (os.contains("win")) {
            // Windows操作系统
            windowsWordToPdf(stream,sourceOutput);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix/Linux/Mac操作系统
            linuxWordToPdf(stream,sourceOutput);
        } else {
            // 未知操作系统
            throw new RuntimeException("不支持当前操作系统转换文档。");
        }
    }

    /**
     * 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务
     *
     */
    public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
        try{
            IConverter converter = LocalConverter.builder().build();
            converter.convert(stream)
                    .as(DocumentType.DOCX)
                    .to(sourceOutput)
                    .as(DocumentType.PDF).execute();
        } catch (Exception e) {
            log.error("winWordToPdf windows环境word转换为pdf时出现异常:", e);
        }
    }

    /**
     * 通过libreoffice 实现word转pdf -- linux 环境 需要有 libreoffice 服务
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 创建临时文件
        File tempFile = createTempFileFromInputStream(stream);
        // 构建LibreOffice的命令行工具命令
        String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent();
        // 执行转换命令
        try {
            if (!executeLinuxCmd(command)) {
                throw new IOException("转换失败");
            }
             readPdfFileToByteArrayOutputStream(tempFile,sourceOutput);
        } catch (Exception e) {
            log.error("ConvertWordToPdf: Linux环境word转换为pdf时出现异常:"+e +tempFile.getPath());
            // 清理临时文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理转换后的pdf文件
            pdfFile.delete();
            // 清理临时文件,无论是否成功转换
            tempFile.delete();
        }
    }

    /**
     * 执行命令行
     *
     * @param cmd 命令行
     * @return
     * @throws IOException
     */
    private static boolean executeLinuxCmd(String cmd) throws IOException {
        Process process = Runtime.getRuntime().exec(cmd);
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            log.error("executeLinuxCmd 执行Linux命令异常:", e);
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }

    /**
     *
     * 创建临时文件
     */
    private static File createTempFileFromInputStream(InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("temp_word", ".docx");
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        } catch (IOException e) {
            log.error("创建临时文件失败:", e);
            throw new RuntimeException("创建临时文件失败", e);
        }
    }

    /**
     * 读取pdf文件
     */
    private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){
        try {
            Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            Files.copy(outputFile, sourceOutput);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2.linux系统用法

linux操作系统要安装libreoffice6,原因是documents4j调用的是office的API

1.在线安装

sudo yum install libreoffice  (这里建议安装低版本,高版本要求服务器的很多对应API库版本要求也比较高)

2.离线安装(点击后选择版本下载rpm包,上传至linux系统)

3.解压文件

4.进入两个文件夹安装rpm包

使用安装命令

cd LibreOffice_6.4.2_Linux_x86-64_rpm/RPMS

yum localinstall *.rpm

安装完成查看版本

which libreoffice6.4     --》显示路径说明安装成功

ll /usr/bin/libreoffice6.4  --》得到 "/opt/libreoffice6.4/program/soffice",说明安装到了 "/opt/libreoffice6.4"

5.脚本测试是否可以成功转换

libreoffice --headless --convert-to pdf 1.doc  --》去/temp  临时目录查看,也可以指定文件目录导出

6.同样适用上面代码成功转换文档

package com.daysuns.dmas.module.testReportwd.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;



@Slf4j
public class Documents4jUtil {

    /**
     * word转pdf
     *
     */
    public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        String os = System.getProperty("os.name").toLowerCase();
        log.info("convertWordToPdf 当前操作系统:{}", os);
        if (os.contains("win")) {
            // Windows操作系统
            windowsWordToPdf(stream,sourceOutput);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix/Linux/Mac操作系统
            linuxWordToPdf(stream,sourceOutput);
        } else {
            // 未知操作系统
            throw new RuntimeException("不支持当前操作系统转换文档。");
        }
    }

    /**
     * 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务
     *
     */
    public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
        try{
            IConverter converter = LocalConverter.builder().build();
            converter.convert(stream)
                    .as(DocumentType.DOCX)
                    .to(sourceOutput)
                    .as(DocumentType.PDF).execute();
        } catch (Exception e) {
            log.error("winWordToPdf windows环境word转换为pdf时出现异常:", e);
        }
    }

    /**
     * 通过libreoffice 实现word转pdf -- linux 环境 需要有 libreoffice 服务
     *
     */
    public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
        // 创建临时文件
        File tempFile = createTempFileFromInputStream(stream);
        // 构建LibreOffice的命令行工具命令
        String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent();
        // 执行转换命令
        try {
            if (!executeLinuxCmd(command)) {
                throw new IOException("转换失败");
            }
             readPdfFileToByteArrayOutputStream(tempFile,sourceOutput);
        } catch (Exception e) {
            log.error("ConvertWordToPdf: Linux环境word转换为pdf时出现异常:"+e +tempFile.getPath());
            // 清理临时文件
            tempFile.delete();
        } finally {
            File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            //清理转换后的pdf文件
            pdfFile.delete();
            // 清理临时文件,无论是否成功转换
            tempFile.delete();
        }
    }

    /**
     * 执行命令行
     *
     * @param cmd 命令行
     * @return
     * @throws IOException
     */
    private static boolean executeLinuxCmd(String cmd) throws IOException {
        Process process = Runtime.getRuntime().exec(cmd);
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            log.error("executeLinuxCmd 执行Linux命令异常:", e);
            Thread.currentThread().interrupt();
            return false;
        }
        return true;
    }

    /**
     *
     * 创建临时文件
     */
    private static File createTempFileFromInputStream(InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("temp_word", ".docx");
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        } catch (IOException e) {
            log.error("创建临时文件失败:", e);
            throw new RuntimeException("创建临时文件失败", e);
        }
    }

    /**
     * 读取pdf文件
     */
    private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){
        try {
            Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
            Files.copy(outputFile, sourceOutput);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


 

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值