小工具知识网

当前位置: 首页 > 行业知识 > java 将word转为pdf文件的两种方式【spire.doc.free】【documents4j】

行业知识

java 将word转为pdf文件的两种方式【spire.doc.free】【documents4j】

2026-12-06 09:04:34 来源:互联网转载

场景

如资产证明等场景下,一般要求同时生成word与pdf两种格式的证明文件,且两者格式需保持一致,可以各自单独生成,但那样可能需要维护两个模板文件,所以也可以仅定义一份word的模板文件,使用模板生成word文件,再将word转换为pdf,这样不仅少维护一个模板,也可以保证word与pdf的格式始终一致。

目标

在保留原word文件格式的情况下,通过java,后台将word文件转换为pdf文件并输出。

差异

documents4j会保留原word文件中更多的样式,如修订模式下的差异化字体颜色、文档右侧修订记录等。

spire.doc.free则不会保留修订模式下的差异。

准备

准备一份word文件(最好带有各种文本格式、表格等,以便校验转为pdf后是否仍保持原样)。

如:

一、spire.doc.free 实现方式

引用pom

    e-iceblue    spire.doc.free    5.2.0

java实现

package com.example.demo.word2pdf;import com.spire.doc.Document;import com.spire.doc.FileFormat;public class Word2PdfUtil {    public static void main(String[] args) {        // 参考:https:        //www.cnblogs.com/Carina-baby/p/16665310.html        //实例化Document类的对象        Document doc = new Document();        //加载Word        doc.loadFromFile("E:\test2\word模板.docx");        //保存为PDF格式        doc.saveToFile("E:\test2\word模板转pdf.pdf", FileFormat.PDF);    }}

效果

一、documents4j 实现方式

引用pom

    com.documents4j    documents4j-local    1.0.3    com.documents4j    documents4j-transformer-msoffice-word    1.0.3    e-iceblue    spire.doc.free    5.2.0

java

package com.example.demo.word2pdf;import com.documents4j.api.DocumentType;import com.documents4j.api.IConverter;import com.documents4j.job.LocalConverter;import java.io.*;public class Word2Pdf {    public void word2pdf() throws IOException {        // 参考:https:        //blog.csdn.net/ka3p06/article/details/125476270 通过documents4j实现        InputStream docxInputStream = null;        OutputStream outputStream = null;        try {            // 原word地址            docxInputStream = new FileInputStream("E:\\test2\\word模板.docx");            // 转换后pdf生成地址            outputStream = new FileOutputStream("E:\\test2\\word模板转pdf.pdf");            IConverter converter = LocalConverter.builder().build();            converter.convert(docxInputStream)                    .as(DocumentType.DOCX)                    .to(outputStream)                    .as(DocumentType.PDF).execute();            // 关闭            converter.shutDown();            // 关闭            outputStream.close();            // 关闭            docxInputStream.close();        } catch (Exception e) {            System.out.println("[documents4J] word转pdf失败:" + e.toString());        } finally {            if (outputStream != null) {                outputStream.close();            }            if (docxInputStream != null) {                docxInputStream.close();            }        }    }    public static void main(String[] args) throws Exception {        Word2Pdf bean = new Word2Pdf();        bean.word2pdf();    }}

效果

上一篇:IDE怎么配服务器?

下一篇:逃跑吧少年,下载指南