基于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


猜你喜欢
- 1、编写一个Java程序在屏幕上输出“你好!”。 //programme name Helloworld.java public class
- Navigator 的 push 和 pop方法Navigator 导航器的 push 和 pop 方法可以携带参数在页面间传递,其他变形的
- AbstractDetectingUrlHandlerMapping是通过扫描方式注册Handler,收到请求时由Abstrac
- 当数据库中存有大量数据的时候,用Cursor查询时要注意,有可能引发性能问题。数据库查询出来的Cursor都会由一个CursorWindow
- 基类:using System;using System.Collections.Generic;using System.Linq;usi
- 偶然机会看到一种对象初始的方式:// 新建一个列表,并赋值 "Harry","Tony","
- CircuitBreaker 断路器服务熔断是为了保护我们的服务,比如当某个服务出现问题的时候,控制打向它的流量,让它有时间去恢复,或者限制
- 最近在搞一个购物车的功能,里面有一个批量删除的操作,采用的是ExpandableListView以及BaseExpandableListAd
- 概述从今天开始, 小白我将带大家开启 Java 数据结构 & 算法的新篇章.贪心算法贪心算法 (Greedy Algorithm)
- 最近项目中使用了mybatis-plus 3.1.1版本,发现使用lambda表达式方式的条件构造器,执行时会报错;但是我用单元测试却通过,
- 一.抽象类(一)概念 在继承的层次结构中,每个新的子类都使类变得更加明确和具体。如果从一个子类向父类
- 本文实例讲述了C#验证给定字符串形式日期是否合法的方法。分享给大家供大家参考。具体分析如下:这段C#代码用于验证日期的有效性,对于用户输入的
- smoothstep另一种用法在之前OpenGL Shader-抗锯齿实现文章中所介绍的那样:为了抗锯齿效果可以用smoothstep函数对
- 本文实例讲述了Android滑动按钮事件。分享给大家供大家参考,具体如下:今天纪录一下滑动按钮功能。。首先效果图:然后是分别建立三个文件,第
- Android中图片的左右切换随处可见,今天我也试着查阅资料试着做了一下,挺简单的一个小Demo,却也发现了一些问题,话不多说,上代码~:使
- 本文实例讲述了C#实现左截取和右截取字符串的方法,分享给大家供大家参考。具体方法分析如下:问题如下:使用C#语法编写程序时,我们需要截取一个
- 先来看看效果图先分析饼状图的构成,非常明显,饼状图就是一个又一个的扇形构成的,每个扇形都有不同的颜色,对应的有名字,数据和百分比。经以上信息
- 目录一、内部类1.什么是内部类?1.类作为形参和返回值:2.内部类的几种形式二、Lambda表达式(强调做什么,而不是以什么形式去做)1.L
- 作为我最近一直在进行的一些编码访谈的一部分,有时会出现不变性问题。我自己并不过分教条,但每当不需要可变状态时,我会试图摆脱导致可变性的代码,
- java 中二分法查找的应用实例二分查找的前提是:数组有序 注意:mid的动态变化,否则出错!!! 实例代码:publ