功能:
解析上传的pdf表格,并存入数据库
最近有个需求,功能如上。百度了一下主要推荐的框架有两个。一个是Itext,另一个是PdfBox,都不太好用。
在之后发现了Tabula,功能很强大,就搜了搜有没有给Java调用的方法,就找到了下边的贴子:
https://blog.csdn.net/qq_36956002/article/details/101070525
感谢这位博主的分享,写的很好,大家跟着步骤走就可以整合到项目中了!
但是大家会发现下载的Tabula是从本地获取pdf文件的,我们需要改成获取上传的文件。方法如下:
1.创建MyCommandLineApp类,继承CommandLineApp类,重写extractTables方法。
重写也比较简单,原方法里要解析的File是通过路径生成的,只需要改成上传过来的File就可以了。这里的 if (line.hasOption(‘b’)是判断是否为批量上传的文件,没有重写,有需要可以自己改一下。 else if里的条件加了“”&& pdfFile == null”。
/**
* 重写 extractTables() 方法,实现上传文件源
* */
public class MyCommandLineApp extends CommandLineApp {
public MyCommandLineApp(Appendable defaultOutput, CommandLine line) throws ParseException {
super(defaultOutput, line);
}
public void extractTables(CommandLine line, File pdfFile) throws ParseException {
// 批量上传未重写,还需要传递路径
if (line.hasOption('b')) {
if (line.getArgs().length != 0) {
throw new ParseException("Filename specified with batch\nTry --help for help");
} else {
pdfFile = new File(line.getOptionValue('b'));
if (!pdfFile.isDirectory()) {
throw new ParseException("Directory does not exist or is not a directory");
} else {
this.extractDirectoryTables(line, pdfFile);
}
}
} else if (line.getArgs().length != 1 && pdfFile == null) {
throw new ParseException("Need exactly one filename\nTry --help for help");
} else {
if (!pdfFile.exists()) {
throw new ParseException("File does not exist");
} else {
this.extractFileTables(line, pdfFile);
}
}
}
}
2.TabulaUtil类中调用我们自己重写的方法
output这个方法会生成一个StringBuilder,数据格式参见文章开头的链接,然后用FastJson转成json格式,就可以继续操作了,操作json或者转实体之类的。(可能格式有一些问题无法直接转化,需要自己去按照Json格式微调)
到这里基本就可以了,其他写的不详细的地方参考文章开头贴的链接就ok了。
。
。
。
最后如果大家controller中是用的MultipartFile接受的文件,这里给一个MultipartFile to File转换类型的方法:
public static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
后记
Java结合Tabule会有一些问题存在,比如只能解析到表格里的数据、表格有缺表格线的数据获取不到等等。
我想到的解决思路就是结合Tabula与pdfbox,还有拿到的坐标,一起来解决问题。
有问题希望大家多多指教!
谢谢阅读。