基于Java编写一个PDF与Word文件转换工具
作者:秋玻 发布时间:2023-05-30 19:23:12
标签:Java,PDF,Word
前言
前段时间一直使用到word文档转pdf或者pdf转word,寻思着用Java应该是可以实现的,于是花了点时间写了个文件转换工具
源码weloe/FileConversion (github.com)
主要功能就是word和pdf的文件转换,如下
pdf 转 word
pdf 转 图片
word 转 图片
word 转 html
word 转 pdf
实现方法
主要使用了pdfbox Apache PDFBox | A Java PDF Library以及spire.doc Free Spire.Doc for Java | 100% 免费 Java Word 组件 (e-iceblue.cn)两个工具包
pom.xml
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
策略接口
public interface FileConversion {
boolean isSupport(String s);
String convert(String pathName,String dirAndFileName) throws Exception;
}
PDF转图片实现
public class PDF2Image implements FileConversion{
private String suffix = ".jpg";
public static final int DEFAULT_DPI = 150;
@Override
public boolean isSupport(String s) {
return "pdf2image".equals(s);
}
@Override
public String convert(String pathName,String dirAndFileName) throws Exception {
String outPath = dirAndFileName + suffix;
if(Files.exists(Paths.get(outPath))){
throw new RuntimeException(outPath+" 文件已存在");
}
pdf2multiImage(pathName,outPath,DEFAULT_DPI);
return outPath;
}
/**
* pdf转图片
* 多页PDF会每页转换为一张图片,下面会有多页组合成一页的方法
*
* @param pdfFile pdf文件路径
* @param outPath 图片输出路径
* @param dpi 相当于图片的分辨率,值越大越清晰,但是转换时间变长
*/
public void pdf2multiImage(String pdfFile, String outPath, int dpi) {
if (dpi <= 0) {
// 如果没有设置DPI,默认设置为150
dpi = DEFAULT_DPI;
}
try (PDDocument pdf = PDDocument.load(new FileInputStream(pdfFile))) {
int actSize = pdf.getNumberOfPages();
List<BufferedImage> picList = new ArrayList<>();
for (int i = 0; i < actSize; i++) {
BufferedImage image = new PDFRenderer(pdf).renderImageWithDPI(i, dpi, ImageType.RGB);
picList.add(image);
}
// 组合图片
ImageUtil.yPic(picList, outPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF转word实现
public class PDF2Word implements FileConversion {
private String suffix = ".doc";
@Override
public boolean isSupport(String s) {
return "pdf2word".equals(s);
}
/**
*
* @param pathName
* @throws IOException
*/
@Override
public String convert(String pathName,String dirAndFileName) throws Exception {
String outPath = dirAndFileName + suffix;
if(Files.exists(Paths.get(outPath))){
throw new RuntimeException(outPath+" 文件已存在");
}
pdf2word(pathName, outPath);
return outPath;
}
private void pdf2word(String pathName, String outPath) throws IOException {
PDDocument doc = PDDocument.load(new File(pathName));
int pagenumber = doc.getNumberOfPages();
// 创建文件
createFile(Paths.get(outPath));
FileOutputStream fos = new FileOutputStream(outPath);
Writer writer = new OutputStreamWriter(fos, "UTF-8");
PDFTextStripper stripper = new PDFTextStripper();
stripper.setSortByPosition(true);//排序
stripper.setStartPage(1);//设置转换的开始页
stripper.setEndPage(pagenumber);//设置转换的结束页
stripper.writeText(doc, writer);
writer.close();
doc.close();
}
}
word转html
public class Word2HTML implements FileConversion{
private String suffix = ".html";
@Override
public boolean isSupport(String s) {
return "word2html".equals(s);
}
@Override
public String convert(String pathName, String dirAndFileName) {
String outPath = dirAndFileName + suffix;
if(Files.exists(Paths.get(outPath))){
throw new RuntimeException(outPath+" 文件已存在");
}
Document doc = new Document();
doc.loadFromFile(pathName);
doc.saveToFile(outPath, FileFormat.Html);
doc.dispose();
return outPath;
}
}
word转图片
public class Word2Image implements FileConversion{
private String suffix = ".jpg";
@Override
public boolean isSupport(String s) {
return "word2image".equals(s);
}
@Override
public String convert(String pathName, String dirAndFileName) throws Exception {
String outPath = dirAndFileName + suffix;
if(Files.exists(Paths.get(outPath))){
throw new RuntimeException(outPath+" 文件已存在");
}
Document doc = new Document();
//加载文件
doc.loadFromFile(pathName);
//上传文档页数,也是最后要生成的图片数
Integer pageCount = doc.getPageCount();
// 参数第一个和第三个都写死 第二个参数就是生成图片数
BufferedImage[] image = doc.saveToImages(0, pageCount, ImageType.Bitmap);
// 组合图片
List<BufferedImage> imageList = Arrays.asList(image);
ImageUtil.yPic(imageList, outPath);
return outPath;
}
}
word转pdf
public class Word2PDF implements FileConversion{
private String suffix = ".pdf";
@Override
public boolean isSupport(String s) {
return "word2pdf".equals(s);
}
@Override
public String convert(String pathName, String dirAndFileName) throws Exception {
String outPath = dirAndFileName + suffix;
if(Files.exists(Paths.get(outPath))){
throw new RuntimeException(outPath+" 文件已存在");
}
//加载word
Document document = new Document();
document.loadFromFile(pathName, FileFormat.Docx);
//保存结果文件
document.saveToFile(outPath, FileFormat.PDF);
document.close();
return outPath;
}
}
使用
输入转换方法,文件路径,输出路径(输出路径如果输入'null'则为文件同目录下同名不同后缀文件)
转换方法可选项:
pdf2word
pdf2image
word2html
word2image
word2pdf
例如输入:
pdf2word D:\test\testpdf.pdf null
控制台输出:
转换方法: pdf2word 文件: D:\test\testFile.pdf
转换成功!文件路径: D:\test\testFile.doc
来源:https://www.cnblogs.com/weloe/p/17038372.html
0
投稿
猜你喜欢
- 这篇文章主要介绍了java泛型常用通配符实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以
- 本文实例讲述了C#实现对Json字符串处理方法,分享给大家供大家参考。具体分析如下:一般对于web应用开发人员来说对Json字符串都会很熟悉
- Map集合的概述概述:interface Map<K,V> 其中K是键的类型,键是唯一的,不重复。V是值的类型,是可以重复。且每
- 题目描述:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数
- 反射方式获取JPA Entity属性和值在记录日志或者调试的时候,往往需要输出数据库查询或者写入的值,或者在接 * 互的时候,可能需要将实体转
- 1、导入资源2、JSP代码<div class="page-container">  
- 引言java中的Math.random()是一个在[0,1)范围等概率返回double数值类型的算法,基于此函数,我们来延申一些随机概率算法
- 本文实例讲述了Java使用Thread和Runnable的线程实现方法。分享给大家供大家参考,具体如下:一 使用Thread实现多线程模拟铁
- 在application.properties中填写中文信息,在读取该文件时会出现中文乱码问题。比如:application.propert
- 一、setting.xml文件的位置今天我们来谈谈Maven setting文件配置的禅定之道。不知道大家有没有听说过禅宗?嗯,没错,就是那
- 1 概念方面List是接口,ArrayList是List接口的一个实现类2 初始化方面2.1 List2.1.1 错误写 * ist list
- 下面给大家介绍下mybatis结果生成键值对的实例代码,具体内容如下所示:在实际应用中我们经常会遇到这样的情况,需要给下拉框赋值,这个时候就
- 一、JTA组件简介什么是JTAJTA,全称:Java Transaction API。JTA事务比JDBC事务更强大。一个JTA事务可以有多
- 在项目中,需要使用XStream将xml string转成相应的对象,却报出了java.lang.ClassCastException: c
- 在 Servlet/Jsp 项目中,如果涉及到系统任务,例如在项目启动阶段要做一些数据初始化操作,这些操作有一个共同的特点,只在项目启动时进
- 通常情况下我们想实现文字的走马灯效果需要在xml文件中这样设置<TextView android:layout_widt
- 用Stream解决两层List属性求和假设一个人有很多个银行账户,每个银行账户中存有不同金额的存款,那么我们如何用Stream求一组人的所有
- 本文实例为大家分享了Java读取并下载网络文件的具体代码,供大家参考,具体内容如下import java.io.ByteArrayOutpu
- java读写ini文件、FileOutputStream在上课让学生练习文件读写,就让他们做了一个使用文件保存账号和密码的练习,有一个比较爱
- 因为在Action的execute方法声明时就抛出了Exception异常,所以我们无需再execute方法中捕捉异常,仅需在struts.