package document;
import interfaces.ICommon;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
import common.AddTxt;
/**
* 将pdf中的内容复制到txt中
*
* @author DanielCooger <a href="mailto:tangjunfeng52099@gmail.com">daniel</a>
*/
public class Pdf implements ICommon{
// 新建文件夹路径
private String path = "d:\\doc";
private String date = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
// 新建的txt文件路径
private String pdf = "d:\\doc\\PDF" + date + ".txt";
// 内存中存储的PDF Document
private PDDocument document = null;
// 是否排序
private boolean sort = false;
// 开始提取页数
private int startPage = 1;
// 结束提取页数
private int endPage = Integer.MAX_VALUE;
/**
*根据输入的源文件路径得到pdf文件中的内容 file 参数为源文件pdf路径
*/
public boolean readText(String file) throws Exception {
// 注意参数已不是以前版本中的URL.而是File。
document = PDDocument.load(file);
// PDFTextStripper来提取文本
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();
// 设置是否排序
stripper.setSortByPosition(sort);
// 设置起始页
stripper.setStartPage(startPage);
// 设置结束页
stripper.setEndPage(endPage);
// 调用PDFTextStripper的getText提取pdf中的文本
try {
if (new AddTxt()
.addtxt(path, pdf, stripper.getText(document), true)) {
System.out.println("ok");
return true;
} else {
return false;
}
} catch (Exception e) {
throw new Exception("此PDF文件无法解析");
}
}
}