在工作项目中,有一个功能的需求是读取本地PDF文件,将PDF文件中的文字内容读取出来。特此记录一下。
首先,要在SpringBoot项目添加相解析PDF文件的依赖——pdfbox,完整的Maven依赖如下所示:
<!-- PDF解析依赖 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.28</version>
</dependency>
下面是一个简单的演示示例:
/**
* @return PDF文件内容
*/
public static String readPDFFile() {
String textContent = "";
//本地PDF文件路径
String pdfFilePath = "C:\\Users\\****\\Desktop\\Test.pdf";
try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
PDFTextStripper stripper = new PDFTextStripper();
textContent = stripper.getText(document);
//控制台输出,查看解析结果
System.out.println("======== textContent ======== \n" + textContent);
} catch (IOException e) {
e.printStackTrace();
}
return textContent;
}
至此,SpringBoot项目读取本都PDF文件内容的功能就完成了。
1万+

被折叠的 条评论
为什么被折叠?



