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

完美转换

相关推荐
一只乔哇噻11 分钟前
java后端工程师进修ing(研一版‖day44)
java·开发语言·学习·算法
老华带你飞18 分钟前
畅阅读小程序|畅阅读系统|基于java的畅阅读系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序·毕设·畅阅读系统小程序
卓码软件测评3 小时前
第三方软件测试机构【性能测试工具用LoadRunner还是JMeter?】
java·功能测试·测试工具·jmeter·性能优化
Lionel_SSL7 小时前
《深入理解Java虚拟机》第三章读书笔记:垃圾回收机制与内存管理
java·开发语言·jvm
记得开心一点嘛7 小时前
手搓Springboot
java·spring boot·spring
老华带你飞7 小时前
租房平台|租房管理平台小程序系统|基于java的租房系统 设计与实现(源码+数据库+文档)
java·数据库·小程序·vue·论文·毕设·租房系统管理平台
独行soc7 小时前
2025年渗透测试面试题总结-66(题目+回答)
java·网络·python·安全·web安全·adb·渗透测试
脑子慢且灵8 小时前
[JavaWeb]模拟一个简易的Tomcat服务(Servlet注解)
java·后端·servlet·tomcat·intellij-idea·web
华仔啊9 小时前
SpringBoot 中 6 种数据脱敏方案,第 5 种太强了,支持深度递归!
java·后端
异常驯兽师10 小时前
Spring 中处理 HTTP 请求参数注解全解析
java·spring·http