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

使用

java 复制代码
//拿到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");

或者写入输出流

java 复制代码
    /**
     * 将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

xml 复制代码
        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-words</artifactId>
            <version>23.1</version>
        </dependency>

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

使用

  1. 在resources创建word-license.xml
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>
  1. 工具类
java 复制代码
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);
        }
    }
}

使用

java 复制代码
Doc2PdfUtil.word2Pdf("aa.docx","bb.pdf");

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

java 复制代码
//拿到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);
                }
            }
        }
java 复制代码
    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;
        }
    }

完美转换

相关推荐
red_redemption6 分钟前
Java的学习(语法相关)
java
学习ing小白14 分钟前
JavaWeb - 8 - 请求响应 & 分层解耦
java·springboot·后端web开发
2401_8572979115 分钟前
招联金融秋招内推2025
java·前端·算法·金融·求职招聘
小媛早点睡15 分钟前
day02笔试练习
java·开发语言·算法
shigen0117 分钟前
借助spring的IOC能力消除条件判断
java·spring
薰衣草233324 分钟前
java部分总结
java·开发语言
IT学长编程41 分钟前
计算机毕业设计 在线项目管理与任务分配系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计·计算机毕业设计选题
2401_857622661 小时前
SpringBoot与校园健康信息管理的融合
java·spring boot·后端
武子康1 小时前
大数据-153 Apache Druid 案例 从 Kafka 中加载数据并分析
java·大数据·分布式·flink·kafka·apache
Mr Aokey1 小时前
盛最多水的容器
java·算法·双指针