java将word转pdf的方法示例详解

 更新时间:2025年01月26日 09:47:06   作者:ziyue7575  
这篇文章主要介绍了java将word转pdf的相关资料,文中讲解了使用Aspose-Words工具将Word文档转换为PDF的优劣,并提供了一种在Java项目中使用Aspose-Words进行Word转PDF的示例方法,需要的朋友可以参考下

总结

建议使用aspose-words转pdf,poi的容易出问题还丑…

poi的(多行的下边框就不对了)

aspose-words的(基本和word一样)

poi工具转换

        <!-- 处理PDF -->
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
            <version>2.0.3</version>
        </dependency>

这个工具使用了poi,最新的2.0.3对应poi的5.2.0,2.0.1对应poi的3.15

使用

//拿到word流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("word/muban3.docx");
        if (inputStream == null) {
            throw new MsgException("读取模板失败");
        }
XWPFDocument document = new XWPFDocument(inputStream);
//.....word处理
PdfOptions pdfOptions = PdfOptions.create();//.fontEncoding( BaseFont.CP1250 );
//转pdf操作 (直接写入响应)
PdfConverter.getInstance().convert(document, response.getOutputStream(), pdfOptions);
response.setContentType("application/pdf");

或者写入输出流

    /**
     * 将word转为pdf并返回一个输出流
     *
     * @param document 输出文件名(pdf格式)
     */
    public static ByteArrayOutputStream wordToPdfOutputStream(XWPFDocument document) throws IOException {
        //word转pdf
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfOptions pdfOptions = PdfOptions.create();//.fontEncoding( BaseFont.CP1250 );
        //转pdf操作
        PdfConverter.getInstance().convert(document, outputStream, pdfOptions);

        return outputStream;
    }

问题

poi改了word之后,生成没问题,word中创建的表格,转pdf的时候经常出问题(直接报错或者合并无效)

研究了2天,pdf转一直各种问题,一起之下换技术

aspose-words

https://blog.csdn.net/Wang_Pink/article/details/141898210

        &lt;dependency&gt;
            &lt;groupId&gt;com.luhuiguo&lt;/groupId&gt;
            &lt;artifactId&gt;aspose-words&lt;/artifactId&gt;
            &lt;version&gt;23.1&lt;/version&gt;
        &lt;/dependency&gt;

poi处理word一堆的依赖,这个一个就好,而且本身就支持转pdf!!!

使用

  • 在resources创建word-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>
  • 工具类
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

@Slf4j
public class Doc2PdfUtil {

    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getLicense() {
        String licenseFilePath = "word-license.xml";
        try {
            InputStream is = Doc2PdfUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(Objects.requireNonNull(is));
        } catch (Exception e) {
            log.error("license verify failed");
            e.printStackTrace();
        }
    }

    /**
     * word 转 pdf
     *
     * @param wordFile word 文件路径
     * @param pdfFile  生成的 pdf 文件路径
     */
    public static void word2Pdf(String wordFile, String pdfFile) {
        File file = new File(pdfFile);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        getLicense();
        try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
            Document doc = new Document(wordFile);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
        }
    }

    /**
     * word 转 pdf
     *
     * @param wordFile word 文件流
     * @param pdfFile  生成的 pdf 文件流
     */
    public static void word2Pdf(InputStream wordFile, OutputStream pdfFile) {
        getLicense();
        try {
            Document doc = new Document(wordFile);
            doc.save(pdfFile, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
        }
    }
}

使用

Doc2PdfUtil.word2Pdf("aa.docx","bb.pdf");

我是依旧使用poi处理word,用这个转pdf

//拿到word流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("word/muban3.docx");
        if (inputStream == null) {
            throw new MsgException("读取模板失败");
        }
XWPFDocument document = new XWPFDocument(inputStream);
//.....word处理
        ByteArrayInputStream in = null;
        try {
            //由于使用的poi的document,需要现将poi的document转为普通的输入流
            in = WordUtil.getInputStream(document);
            Doc2PdfUtil.word2Pdf(in,response.getOutputStream());
            response.setContentType("application/pdf");

        } catch (Exception e) {
            log.error("报告下载失败", e);
        } finally {
            try {
                document.close();
            } catch (Exception e1) {
                log.error("document 流关闭失败", e1);
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e1) {
                    log.error("in 流关闭失败", e1);
                }
            }
        }
    public static ByteArrayInputStream getInputStream(XWPFDocument document) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            document.write(outputStream);
            return outputStreamToPdfInputStream(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    /**
     * 将word转为pdf并返回一个输入流
     *
     * @param outputStream 输出文件名(pdf格式)
     */
    public static ByteArrayInputStream outputStreamToPdfInputStream(ByteArrayOutputStream outputStream) throws IOException {
        //输出的pdf输出流转输入流
        try {
            //临时
            byte[] bookByteAry = outputStream.toByteArray();
            return new ByteArrayInputStream(bookByteAry);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

完美转换

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

相关文章

  • Installij IDEA install或clean项目的使用

    Installij IDEA install或clean项目的使用

    这篇文章主要介绍了Installij IDEA install或clean项目的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • spring boot项目生成docker镜像并完成容器部署的方法步骤

    spring boot项目生成docker镜像并完成容器部署的方法步骤

    这篇文章主要介绍了spring boot项目生成docker镜像并完成容器部署的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • Java递归调用如何实现数字的逆序输出方式

    Java递归调用如何实现数字的逆序输出方式

    这篇文章主要介绍了Java递归调用如何实现数字的逆序输出方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • 使用IDEA创建一个vert.x项目的方法

    使用IDEA创建一个vert.x项目的方法

    这篇文章主要介绍了使用IDEA创建一个vert.x项目的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • springboot无法从静态上下文中引用非静态变量的解决方法

    springboot无法从静态上下文中引用非静态变量的解决方法

    这篇文章主要介绍了springboot无法从静态上下文中引用非静态变量的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-06-06
  • 排序算法的Java实现全攻略

    排序算法的Java实现全攻略

    这篇文章主要介绍了排序算法的Java实现,包括Collections.sort()的使用以及各种经典算法的Java代码实现方法总结,超级推荐!需要的朋友可以参考下
    2015-08-08
  • Java集合ArrayDeque类实例分析

    Java集合ArrayDeque类实例分析

    这篇文章主要介绍了Java集合ArrayDeque类实例分析的相关资料,需要的朋友可以参考下
    2017-04-04
  • SpringBoot Redis实现接口幂等性校验方法详细讲解

    SpringBoot Redis实现接口幂等性校验方法详细讲解

    这篇文章主要介绍了SpringBoot Redis实现接口幂等性校验方法,近期一个老项目出现了接口幂等性校验问题,前端加了按钮置灰,依然被人拉着接口参数一顿输出,还是重复调用了接口,通过复制粘贴,完成了后端接口幂等性调用校验
    2022-11-11
  • SpringBoot中集成Swagger2及简单实用

    SpringBoot中集成Swagger2及简单实用

    使用Swagger你只需要按照它的规范去定义接口及接口相关的信息,再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,以及在线接口调试页面等等,这篇文章主要介绍了SpringBoot中集成Swagger2,需要的朋友可以参考下
    2023-06-06
  • Java判断字符串是否含有乱码实例代码

    Java判断字符串是否含有乱码实例代码

    本文通过实例代码给大家介绍了Java判断字符串是否含有乱码的方法,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧
    2018-11-11

最新评论