文件处理(五):word转pdf

2022-02-17  本文已影响0人  alex很累

一、概述

可以使用poi+xdocreportword转为pdf文件。

二、依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
    <version>2.0.3</version>
</dependency>

这里用了最新的包,xdocreport之前的版本在进行word转为pdf,存在一些小问题。

三、示例代码

@Test
public static void main(String[] args) throws IOException {
    // 1.获取docx文档,并生成XWPFDocument对象
    InputStream is = new FileInputStream("/users/xxx/website/pdf.docx");
    XWPFDocument docx = new XWPFDocument(is);
    // 2.FileOutputStream
    FileOutputStream fileOutputStream = new FileOutputStream("/users/xxx/website/pdf.pdf");
    // 3. word => pdf
    PdfOptions pdfOptions = PdfOptions.create();
    PdfConverter.getInstance().convert(docx, fileOutputStream, pdfOptions);

    is.close();
    fileOutputStream.close();
}

四、效果

转换前
转换后
上一篇 下一篇

猜你喜欢

热点阅读