场景:
从网银上下载的交通银行回单是多页PDF,需要将每页分割再进行解析具体数据进行数据库匹配,保存与流水之间的关联关系,之后再上传至SFTP服务器中。
代码
public static void main(String[] args) {
File file = new File("document.pdf");
//解析文件
try (PDDocument document = PDDocument.load(file)) {
// 创建 Splitter 对象并设置拆分选项
Splitter splitter = new Splitter();
splitter.setStartPage(1);
splitter.setEndPage(document.getNumberOfPages());
// 拆分 PDF 文档并保存每个页面到单独的文件中
List<PDDocument> pages = splitter.split(document);
for (PDDocument page : pages) {
File f = null;
try {
PDFTextStripper stripper = new PDFTextStripper();
String c = stripper.getText(page);
//不同的操作系统可能会使用不同的行尾字符(例如,Windows 使用`\r\n`,而 Linux 使用`\n`)。
String[] content = c.split(System.lineSeparator());
//保存拆分后的回单
page.save(new File("xxx"));
/*
进行业务操作
*/
} catch (Exception e) {
log.error(e);
} finally {
if (Objects.nonNull(f)) {
FileUtil.del(f);
}
}
}
} catch (Exception e) {
log.error(e);
e.printStackTrace();
} finally {
FileUtil.del(file);
}
}
注意事项:
不同的操作系统可能会使用不同的行尾字符(例如,Windows 使用 \r\n
,而 Linux 使用 \n
)。
你可以尝试使用 System.lineSeparator()
来获取当前环境的行尾字符,然后使用这个字符来分割你的字符串。