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

完美转换

相关推荐
珹洺25 分钟前
C++从入门到实战(十)类和对象(最终部分)static成员,内部类,匿名对象与对象拷贝时的编译器优化详解
java·数据结构·c++·redis·后端·算法·链表
一 乐28 分钟前
网红酒店|基于java+vue的网红酒店预定系统(源码+数据库+文档)
java·开发语言·数据库·毕业设计·论文·springboot·网红酒店预定系统
inxunoffice1 小时前
批量压缩与优化 PDF 文档,减少 PDF 文件的大小
pdf
xyliiiiiL2 小时前
从责任链模式聊到aware接口
java·开发语言
码农老起6 小时前
与Aspose.pdf类似的jar库分享
java·pdf·jar
程序猿小D6 小时前
第三百八十九节 JavaFX教程 - JavaFX WebEngine
java·eclipse·intellij-idea·vr·javafx
self-discipline6348 小时前
【Java】Java核心知识点与相应面试技巧(七)——类与对象(二)
java·开发语言·面试
wei3872452328 小时前
java笔记02
java·开发语言·笔记
zjj5878 小时前
Docker使用ubuntu
java·docker·eureka
士别三日&&当刮目相看8 小时前
JAVA学习*简单的代理模式
java·学习·代理模式