java将word docx pdf转换为图片(不需要额外下载压缩包,直接导入maven坐标)

(本代码实现的是将第1页转为图片,主要用于制作文件缩略图)

pdf转图片容易

docx转图片麻烦,看其他博客可以直接导入maven坐标,但我知道那是需要付费且有时限的包

本着简单实用的心,我找到法子了

pdf转图片:有库直接转

docx转图片:docx转pdf再转图片

第一步:导入maven依赖和仓库坐标

maven坐标

XML 复制代码
         <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.office.free</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version> 
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.27</version>
        </dependency>

然后还得在pom.xml添加仓库地址(我用的是阿里云maven仓库,仓库没有spire坐标)

添加到pom.xml文件中,具体添加位置如下

XML 复制代码
<!--    word转pdf仓库-->
    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>

第二步,编写代码测试

word转pdf

java 复制代码
FileInputStream inputStream = new FileInputStream("your/path/to.docx");
//创建Document实例
Document doc = new Document();
//以流的形式加载Word文档 指定文档格式
doc.loadFromStream(inputStream, FileFormat.Docx);
ByteArrayOutputStream os = new ByteArrayOutputStream();
         
//输出到文件
doc.saveToFile("your/path/to.pdf", FileFormat.PDF);

pdf转图片

java 复制代码
//pdf转图片
// 加载PDF文档
PDDocument document = PDDocument.load(new File("your/path/a.pdf"));

// 创建PDF渲染器
PDFRenderer pdfRenderer = new PDFRenderer(document);

// 获取PDF中的第一页
BufferedImage bufferedImage = pdfRenderer.renderImage(0);
        
// 保存为图片
ImageIO.write(bufferedImage, "PNG", new File("your/path/to/save.png"));

 // 关闭PDF文档
document.close();
相关推荐
Linlichaoblms14 小时前
Nginx性能调优:参数详解与压测对比
java·spring boot·nginx
一个很老的小萌新14 小时前
json 解析 [{“id“:1,“name“:“apple“},{“id“:2,“name“:“banana“}]
java·前端·json
是2的10次方啊14 小时前
🏗️ 线程池深度解析:ThreadPoolExecutor底层实现与CompletableFuture异步编程实战
java
小蒜学长14 小时前
django全国小米su7的行情查询系统(代码+数据库+LW)
java·数据库·spring boot·后端
杨杨杨大侠14 小时前
第2章:设计核心接口和事件模型
java·github·eventbus
杨杨杨大侠14 小时前
第1章:事件驱动框架基础概念
java·github·eventbus
半夏陌离14 小时前
SQL 进阶指南:视图的创建与使用(视图语法 / 作用 / 权限控制)
java·数据库·mybatis
程序员皮皮林15 小时前
Java jar 如何防止被反编译?代码写的太烂,害怕被人发现
java·开发语言·jar
橙序员小站15 小时前
搞定系统面试题:如何实现分布式Session管理
java·后端·面试
叫我阿柒啊16 小时前
从Java全栈到Vue3实战:一次真实面试中的技术探索
java·数据库·spring boot·微服务·typescript·vue3·restful