文件处理(五):word转pdf

一、概述

可以使用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();
}

四、效果

转换前

转换后
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。