word、excel文件转PDF(documents4j方式,简单)

1 documents4j方式

引入pom

java 复制代码
<dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.1.12</version>
        </dependency>

#excel转pdf需要的jar
<dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-excel</artifactId>
            <version>1.1.12</version>
        </dependency>

2 代码实现(word,excel转pdf代码)

java 复制代码
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

public static void main(String[] args) {
        File inputWord = new File("E:\\111\\123.docx");
        File outputFile = new File("E:\\111\\123.pdf");
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
java 复制代码
/**
     * documents4j方式excel转pdf
     * @param file 源文件
     * @return 返回转成功的文件
     */
    public static File wordToPDFByDocuments4j(File file) {
        File outputFile = new File(String.format("%s%s%s%s", file.getParentFile(),  File.separator, System.currentTimeMillis(), ".pdf"));
        try  {
            InputStream docxInputStream = new FileInputStream(file);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputFile;
    }

2 poi方式

相关推荐
imperialeast5 小时前
WinAXP 2.4.0.828正式版
windows
周小董8 小时前
[1369]Windows上安装PostgreSQL
数据库·windows·postgresql
doujiaozh8 小时前
Win7 复活记:用 3 个补丁让 13 年前的老电脑跑通 Kimi API
windows
bbq烤鸡14 小时前
Win11 资源管理器“白条“修复报告
windows
10mAh15 小时前
【Java】ArrayList 遍历删除为什么报错?三种写法与漏删复现
java·开发语言·windows
tianyatest16 小时前
给 AI Agent 写了个 Skill:扫描版电子书自动解压合并 + 加书签(附 PDG 格式逆向)
ai·pdf·电子书
瑶山18 小时前
Windows + WSL2 Ubuntu + VS Code配置C++开发环境
开发语言·c++·windows·vscode·wsl
开开心心就好18 小时前
一元二次方程求解工具,答案带详细步骤
java·服务器·开发语言·算法·pdf·ocr·perl
在角落发呆19 小时前
一键脚本配置备份方法:从 Shell 脚本到自动备份
网络·windows
闭包不眠19 小时前
网页转PDF字体出错不报错,我先看文件大小
图像处理·人工智能·计算机视觉·pdf