Java将Word转换成PDF的常用用法

 更新时间:2024年08月03日 08:59:33   作者:一个新人程序猿  
Java开发人员在处理文档转换时,常常需要将Word或Excel文档转换为PDF格式,以便于更好地保持格式一致性、便于分发和打印,这篇文章主要给大家介绍了关于Java将Word转换成PDF的常用用法,需要的朋友可以参考下

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

总结 

到此这篇关于Java将Word转换成PDF的常用用法的文章就介绍到这了,更多相关Java将Word转换PDF内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • springboot之redis cache TTL选项的使用

    springboot之redis cache TTL选项的使用

    这篇文章主要介绍了springboot之redis cache TTL选项的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java里得到00:00:00格式的时分秒的Timestamp

    Java里得到00:00:00格式的时分秒的Timestamp

    Java里如何得到00:00:00格式的时分秒的Timestamp ,下面是具体的实现代码,需要的朋友可以参考下。
    2009-09-09
  • 解读Spring Bean的作用域

    解读Spring Bean的作用域

    这篇文章主要介绍了解读Spring Bean的作用域,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • Spring boot项目部署到云服务器小白教程详解

    Spring boot项目部署到云服务器小白教程详解

    这篇文章主要介绍了Spring boot项目部署到云服务器小白教程详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • Python爬虫 12306抢票开源代码过程详解

    Python爬虫 12306抢票开源代码过程详解

    这篇文章主要介绍了Python爬虫 12306抢票开源代码过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • 如何用java给文件加密的简单实现

    如何用java给文件加密的简单实现

    文件加密,简单来说就是把文件读取出来,把读取出来的字节码数组进行遍历,把每一个码值和一个秘钥(随便一个数)进行异或运算,将运算后的结果全部写入到文件里,这篇文章主要介绍了如何用java给文件加密的简单实现,需要的朋友可以参考下
    2023-12-12
  • 说说@ModelAttribute在父类和子类中的执行顺序

    说说@ModelAttribute在父类和子类中的执行顺序

    这篇文章主要介绍了@ModelAttribute在父类和子类中的执行顺序,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Spring boot测试找不到SpringRunner.class的问题

    Spring boot测试找不到SpringRunner.class的问题

    这篇文章主要介绍了Spring boot测试找不到SpringRunner.class的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • swing分割窗口控件JSplitPane使用方法详解

    swing分割窗口控件JSplitPane使用方法详解

    这篇文章主要为大家详细介绍了swing分割窗口控件JSplitPane的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • IDEA配置Maven的超详细步骤

    IDEA配置Maven的超详细步骤

    Maven是一个能使我们的java程序开发节省时间和精力,是开发变得相对简单,还能使开发规范化的工具,下面这篇文章主要给大家介绍了关于IDEA配置Maven的超详细步骤,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-08-08

最新评论