今天一个美女同事(人家不是程序员)找我帮忙,想要把好多pdf文件(都是表格)转换为word文档,方便修改;
好心的我,这个忙得帮啊,上来就一顿百度,有好多可以pdf转word的工具软件,下了几个,试了试,发现要想不花钱,都是只能转换文档的前几页,一般是前3页,但是我看看了美女给我的pdf,一般都在10页左右,开始想 看看能不能写一个程序转换下,试了试,发现不行,一是手里还有一堆活要做,没有时间;二是能力也有限,写出来也比较费劲。
折中下吧,先写一个程序将pdf切割成每3页一个文档,然后再拿工具转换;代码实现起来还比较容易,还能达到效果。
废话不多说,直接上代码:
package com.dong.util.pdf;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
/**
* <p>项目名称: </p>
* <p>类名称: PdfUtil </p>
* <p>描述: [pdf工具类] </p>
* 创建时间: 2020/6/24 16:15
*
* @author [toney]
* @version v1.0
* <p>更新:[序号][日期YYYY-MM-DD] [更改人姓名][变更描述]</p>
**/
public class PdfUtil {
//要转换的pdf文件名称,支持多个
private static final String[] FILES = new String[]{"文件1","文件2"};
//所有文件存放路径
private static final String PATH = "E:\\CODE\\WISH-GIT-CODE\\lib\\pdf\\";
public static void main(String[] args) {
for(int i=0;i<FILES.length;i++){
//要转换的pdf文件路径
String filePath =PATH+FILES[i]+".pdf";
//每3页一个文档
split(filePath,3);
}
}
public static void split(String pdfFile,int pages){
Document document = null;
PdfCopy copy = null;
try {
PdfReader reader = new PdfReader(pdfFile);
//获取文档总页数
int n = reader.getNumberOfPages();
int begNum = 1;
int endNum = pages;
//获取文件名
String fileName = pdfFile.substring(pdfFile.lastIndexOf("\\")+1);
fileName =fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("n====="+n+"fileName==="+fileName);
String newFileName ="";
for(int i=1;i<=n;i++){
newFileName="";
if(i== endNum){
//记录
newFileName=fileName+begNum+"-"+endNum+".pdf";
splitPdfFile(pdfFile,newFileName, begNum,endNum);
begNum = i+1;
endNum = i+pages;
}else if(i==n){
endNum = i;
newFileName=fileName+begNum+"-"+endNum+".pdf";
splitPdfFile(pdfFile,newFileName, begNum,endNum);
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
public static void splitPdfFile(String pdfFile,String newFile, int from, int end){
Document document = null;
PdfCopy copy = null;
try {
PdfReader reader = new PdfReader(pdfFile);
int n = reader.getNumberOfPages();
if(end==0){
end = n;
}
ArrayList<String> savepaths = new ArrayList<String>();
String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\")+1);
String savepath = staticpath+ newFile;
savepaths.add(savepath);
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
document.open();
for(int j=from; j<=end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch(DocumentException e) {
e.printStackTrace();
}
}
}
程序依赖的jar包:com.lowagie.text-2.1.7.jar,请自行下载,如果下载不到,可以给我留言
顺便说下,pdf转换word使用的工具是 风云PDF转换器,可以自行下载
以上,转换效果,美女很满意,说要请我吃麻辣烫。
注意:转换效果主要依赖pdf转换器。