前言

前段时间一直使用到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

用Java写一个PDF,Word文件转换工具的更多相关文章

  1. 用java写一个servlet,可以将放在tomcat项目根目录下的文件进行下载

    用java写一个servlet,可以将放在tomcat项目根目录下的文件进行下载,将一个完整的项目进行展示,主要有以下几个部分: 1.servlet部分   Export 2.工具类:TxtFileU ...

  2. 用Python将word文件转换成html(转)

    用Python将word文件转换成html   序 最近公司一个客户大大购买了一堆医疗健康方面的科普文章,希望能放到我们正在开发的健康档案管理软件上.客户大大说,要智能推送!要掌握节奏!要深度学习!要 ...

  3. 用JAVA写一个函数,功能例如以下: 随意给定一组数, 找出随意数相加之后的结果为35(随意设定)的情况

    用JAVA写一个函数.功能例如以下:随意给定一组数,比如{12,60,-8,99,15,35,17,18},找出随意数相加之后的结果为35(随意设定)的情况. 能够递归算法来解: package te ...

  4. 五:用JAVA写一个阿里云VPC Open API调用程序

    用JAVA写一个阿里云VPC Open API调用程序 摘要:用JAVA拼出来Open API的URL 引言 VPC提供了丰富的API接口,让网络工程是可以通过API调用的方式管理网络资源.用程序和软 ...

  5. Java实现一个简单的文件上传案例

    Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...

  6. 用JAVA写一个多线程程序,写四个线程,其中二个对一个变量加1,另外二个对一个变量减1

    package com.ljn.base; /** * @author lijinnan * @date:2013-9-12 上午9:55:32 */ public class IncDecThrea ...

  7. 使用JAVA写一个简单的日历

    JAVA写一个简单的日历import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateF ...

  8. java 支持分词的高性能拼音转换工具,速度是 pinyin4j 的两倍

    pinyin pinyin 是 java 实现的高性能中文拼音转换工具. 变更日志 创作目的 想为 java 设计一款便捷易用的拼音工具. 如何为 java 设计一款高性能的拼音转换工具 pinyin ...

  9. 用 C# 写一个 Redis 数据同步小工具

    用 C# 写一个 Redis 数据同步小工具 Intro 为了实现 redis 的数据迁移而写的一个小工具,将一个实例中的 redis 数据同步到另外一个实例中.(原本打算找一个已有的工具去做,找了一 ...

  10. java 写一个"HelloJavaWorld你好世界"输出到操作系统文件Hello.txt文件中

    package com.beiwo.homework; import java.io.File; import java.io.FileOutputStream; import java.io.IOE ...

随机推荐

  1. Pytest进阶使用

    fixture 特点: 命令灵活:对于setup,teardown可以省略 数据共享:在conftest.py配置里写方法可以实现数据共享,不需要import导入,可以跨文件共享 scope的层次及神 ...

  2. 后端框架学习-----mybatis(4)

    文章目录 4.解决属性名和字段名不一致的问题 4.解决属性名和字段名不一致的问题 1.问题.数据库字段名和属性名不一致,导致查出的数据部分为空 2.resultMap(用于解决数据库表中的字段和属性) ...

  3. virtualenv +virtualenvwrapper

    一.虚拟环境virtualenv 1.安装:pip3 install virtualenv 2.创建虚拟环境:virtualenv venv #venv为虚拟环境目录名,目录名自定义 #virtual ...

  4. OCI runtime create failed: container_linux.go:349: starting container process caused "exec: "bash": executable file not found in $PATH": unknown

    docker save docker save centos:self -o centos.tar 导出镜像到文件 用于持久化镜像,导出的tar包需要用 docker load -i imagedat ...

  5. python简单的tcp服务端

    1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 # 文件名:tcpserver.py 4 5 import socket 6 import time 7 ...

  6. Python基础之面向对象:3、继承与派生

    面向对象 一.三大特征之继承 python三大特征: 封装.继承.多态 三者中继承最为核心,实际应用对,感受较为直观 封装和多态略微抽象 1.继承的概念 继承的含义: ​ 在现实生活中,继承表示人与人 ...

  7. (线段树) P4588 数学计算

    小豆现在有一个数 x,初始值为 1.小豆有 QQ 次操作,操作有两种类型: 1 m:将 x变为 x × m,并输出 x mod M 2 pos:将 x 变为 x 除以第 pos次操作所乘的数(保证第  ...

  8. vue 数组更新(push【可用】,$set,slice,filter,map【都属于浅拷贝】)问题

    this.$axios.post('https://....php',this.$qs.stringify({ user: 'suess' })) .then(res => { this.dat ...

  9. scp工具上传下载

    1.从本地复制到远程 scp local_file remote_username@remote_ip:remote_folder 或者 scp local_file remote_username@ ...

  10. 第三方模块的下载与使用、requests模块、爬取链家二手房数据、openpyxl模块、hashlib加密模块

    目录 第三方模块的下载与使用 下载第三方模块可能会出现的问题 网络爬虫模块之requests模块 网络爬虫实战之爬取链家二手房数据 自动化办公领域之openpyxl模块 第三方模块的下载与使用 第三方 ...