java springboot word文档转pdf

java springboot word文档转pdf

1、环境

1、java、springboot

2、maven或者gradle

3、办公软件(自己电脑上的wps或者office等,如果部署到服务器上也要安装,linux、Mac 都有,自己安装)

可能会遇到的问题:

java springboot maven项目,当然gradle 也可以,特别注意的是这个需要依赖外部软件,就是我们熟知的wps或者office 都可以,应该说是有办公软件且办公软件有word转pdf的功能,这个它应该是获取到我们电脑本地的环境来转的,如果有时候不行的话可以考虑一下是不是自己的办公软件的问题,我之前就遇到这个问题,我本地已经安装wps的,也可以正常使用,但是代码里面就是不行,一直报流已经关闭,意思就是获取不到我本地相关的流。最后我重新安装一下我的办公软件(wps)就好了,还有一种就可能版本的问题,也一定要注意

2、依赖

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

这是maven的依赖,其他的自己找

3、代码

java 复制代码
package org.jeecg.modules.xunshu.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @author weisn
 */
@Slf4j
@Component
public class WordConvertPdfUtil {

	private  static final IConverter CONVERTER = LocalConverter.builder().build();

	/**
	 * 通过documents4j 实现word转pdf
	 *
	 * @param sourcePath 源文件地址 如 /root/example.doc
	 * @param targetPath 目标文件地址 如 /root/example.pdf
	 */
	public static void documents4jWordToPdf(String sourcePath, String targetPath) throws IOException {
		InputStream docxInputStream = null;
		OutputStream outputStream = null;
		try {
			// 原word地址
			docxInputStream = new FileInputStream(sourcePath);
			// 转换后pdf生成地址
			outputStream = new FileOutputStream(targetPath);
			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();
			}
		}
	}


}
相关推荐
g***B7381 小时前
Java 工程复杂性的真正来源:从语言设计到现代架构的全链路解析
java·人工智能·架构
期待のcode3 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
醇氧5 小时前
【Windows】优雅启动:解析一个 Java 服务的后台启动脚本
java·开发语言·windows
sunxunyong6 小时前
doris运维命令
java·运维·数据库
菜鸟起航ing6 小时前
Spring AI 全方位指南:从基础入门到高级实战
java·人工智能·spring
古城小栈6 小时前
Docker 多阶段构建:Go_Java 镜像瘦身运动
java·docker·golang
MapGIS技术支持6 小时前
MapGIS Objects Java计算一个三维点到平面的距离
java·开发语言·平面·制图·mapgis
Coder_Boy_6 小时前
业务导向型技术日志首日记录(业务中使用的技术栈)
java·驱动开发·微服务
盖世英雄酱581367 小时前
springboot 项目 从jdk 8 升级到jdk21 会面临哪些问题
java·后端
济南壹软网络科技有限公司7 小时前
企业级盲盒系统:Java高并发架构在多元化抽奖电商中的设计与实践
java·架构·开源源码·盲盒源码·盲盒h5·盲盒app