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();
			}
		}
	}


}
相关推荐
float_六七1 小时前
IntelliJ IDEA双击Ctrl的妙用
java·ide·intellij-idea
能摆一天是一天2 小时前
JAVA stream().flatMap()
java·windows
颜如玉3 小时前
🤲🏻🤲🏻🤲🏻临时重定向一定要能重定向🤲🏻🤲🏻🤲🏻
java·http·源码
程序员的世界你不懂4 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
星空寻流年4 小时前
设计模式第一章(建造者模式)
java·设计模式·建造者模式
gb42152875 小时前
java中将租户ID包装为JSQLParser的StringValue表达式对象,JSQLParser指的是?
java·开发语言·python
曾经的三心草5 小时前
Python2-工具安装使用-anaconda-jupyter-PyCharm-Matplotlib
android·java·服务器
Metaphor6925 小时前
Java 高效处理 Word 文档:查找并替换文本的全面指南
java·经验分享·word
ChinaRainbowSea5 小时前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
stormsha5 小时前
飞算JavaAI炫技赛电商系统商品管理模块的架构设计与实现
java·架构·鸿蒙系统