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

完美转换

相关推荐
@ chen2 分钟前
IDEA初始化配置
java·ide·intellij-idea
wellc41 分钟前
SpringBoot集成Flowable
java·spring boot·后端
Hui Baby1 小时前
springAi+MCP三种
java
hsjcjh1 小时前
【MySQL】C# 连接MySQL
java
敖正炀1 小时前
LinkedBlockingDeque详解
java
wangyadong3171 小时前
datagrip 链接mysql 报错
java
untE EADO2 小时前
Tomcat的server.xml配置详解
xml·java·tomcat
ictI CABL2 小时前
Tomcat 乱码问题彻底解决
java·tomcat
敖正炀2 小时前
DelayQueue 详解
java
敖正炀2 小时前
PriorityBlockingQueue 详解
java