
本教程详细介绍了如何使用apache pdfbox库在java中高效地从pdf文件中提取文本,并在此基础上实现关键词搜索功能。文章将指导读者如何正确处理pdf文件(而非将其视为纯文本),如何在提取的文本中执行搜索,以及如何根据搜索结果将pdf文件复制或移动到指定目录,同时提供完整的代码示例和最佳实践。
PDF(Portable Document Format)文件是一种复杂的二进制格式,它不仅仅包含文本,还包括字体、图像、矢量图形、布局信息等。因此,直接使用Java的 FileReader 或 BufferedReader 对PDF文件进行读取,并不能正确地获取其内部的文本内容。尝试这样做通常会导致乱码或错误,因为这些类是为处理纯文本文件设计的,它们无法解析PDF的内部结构。
要正确地从PDF文件中提取文本,我们需要借助专门的PDF处理库,这些库能够理解PDF的内部结构并解析出可读的文本。
Apache PDFBox 是一个开源的Java库,用于处理PDF文档。它提供了丰富的API,可以执行各种PDF操作,包括创建、修改、打印、渲染和从PDF中提取文本等。
在使用PDFBox之前,需要将其添加到项目的依赖中。如果你使用Maven,可以在 pom.xml 文件中添加以下依赖:
立即学习“Java免费学习笔记(深入)”;
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.29</version> <!-- 请使用最新稳定版本 -->
</dependency>如果你使用Gradle,可以在 build.gradle 文件中添加:
implementation 'org.apache.pdfbox:pdfbox:2.0.29' // 请使用最新稳定版本
使用PDFBox从PDF文件中提取文本是实现搜索功能的第一步。
本文档主要讲述的是Flash Builder操作指南;Flash Builder将构成应用程序的资源(文件夹和文件)组合到一个容器中,我们将其称为项目。项目包含一组属性,这些属性控制应用程序的构建方式、构建的应用程序所在的位置、调试的处理方式以及该项目于工作空间中其他项目的关系。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
0
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
public class PdfTextExtractor {
public static String extractTextFromPdf(String filePath) throws IOException {
File file = new File(filePath);
// 使用 try-with-resources 确保 PDDocument 在使用后被关闭
try (PDDocument document = PDDocument.load(file)) {
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(document);
return text;
}
}
public static void main(String[] args) {
String pdfPath = "D:\Sample.pdf"; // 替换为你的PDF文件路径
try {
String extractedText = extractTextFromPdf(pdfPath);
System.out.println("PDF文件内容:
" + extractedText.substring(0, Math.min(extractedText.length(), 500)) + "..."); // 打印前500字
} catch (IOException e) {
System.err.println("提取PDF文本时发生错误: " + e.getMessage());
}
}
}一旦我们成功地从PDF中提取了所有文本内容(以 String 形式),就可以使用Java标准的字符串处理方法来执行关键词搜索。
以下示例展示了如何在提取的PDF文本中搜索一个或多个关键词:
import java.io.IOException;
import java.util.Scanner;
public class PdfTextSearcher {
/**
* 在PDF文本中搜索指定词语
* @param pdfContent PDF文件的全部文本内容
* @param searchWord 要搜索的词语
* @param ignoreCase 是否忽略大小写
* @return 如果找到词语则返回 true,否则返回 false
*/
public static boolean searchInPdfContent(String pdfContent, String searchWord, boolean ignoreCase) {
if (pdfContent == null || pdfContent.isEmpty() || searchWord == null || searchWord.isEmpty()) {
return false;
}
if (ignoreCase) {
return pdfContent.toLowerCase().contains(searchWord.toLowerCase());
} else {
return pdfContent.contains(searchWord);
}
}
public static void main(String[] args) {
String pdfPath = "D:\Sample.pdf"; // 替换为你的PDF文件路径
String pdfContent = null;
try {
pdfContent = PdfTextExtractor.extractTextFromPdf(pdfPath);
} catch (IOException e) {
System.err.println("加载或提取PDF文本失败: " + e.getMessage());
return;
}
if (pdfContent == null || pdfContent.isEmpty()) {
System.out.println("PDF内容为空,无法执行搜索。");
return;
}
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要搜索的词语(输入 'Exit' 结束):");
while (scanner.hasNextLine()) {
String searchWord = scanner.nextLine().trim();
if (searchWord.equalsIgnoreCase("Exit")) {
break;
}
if (searchInPdfContent(pdfContent, searchWord, true)) { // 忽略大小写搜索
System.out.println("是的,'" + searchWord + "' 在文件中。");
} else {
System.out.println("不,'" + searchWord + "' 不在文件中。");
}
System.out.println("请输入下一个要搜索的词语(输入 'Exit' 结束):");
}
scanner.close();
System.out.println("搜索程序结束。");
}
}在确定PDF文件中包含特定关键词后,下一步是根据业务需求对文件进行操作,例如将其复制或移动到另一个目录。Java的 java.nio.file.Files 类提供了强大的文件操作功能。
常用的 CopyOption 包括:
以下是一个整合了PDF文本提取、关键词搜索和文件复制/移动功能的完整示例。
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
public class PdfSearchAndFileOperation {
public static void main(String[] args) {
String sourcePdfPath = "C:\Users\user012\Desktop\Evalution.pdf"; // 替换为你的PDF文件路径
String targetDirectoryPath = "C:\Users\user012\Desktop\Search\"; // 替换为目标目录路径
// 1. 确保目标目录存在,如果不存在则创建
Path targetDirPath = Paths.get(targetDirectoryPath);
if (!Files.exists(targetDirPath)) {
try {
Files.createDirectories(targetDirPath);
System.out.println("已创建目标目录: " + targetDirectoryPath);
} catch (IOException e) {
System.err.println("无法创建目标目录 '" + targetDirectoryPath + "': " + e.getMessage());
return; // 无法创建目录则退出
}
}
// 2. 尝试加载并提取PDF文本一次
String pdfContent = null;
try (PDDocument document = PDDocument.load(new File(sourcePdfPath))) {
PDFTextStripper pdfStripper = new PDFTextStripper();
pdfContent = pdfStripper.getText(document);
System.out.println("PDF文本提取成功。");
} catch (IOException e) {
System.err.println("加载或提取PDF文本失败: " + e.getMessage());
return; // 如果无法读取PDF,则退出程序
}
if (pdfContent == null || pdfContent.isEmpty()) {
System.out.println("PDF内容为空,无法搜索。");
return;
}
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要搜索的词语(输入 'Exit' 结束):");
// 3. 循环处理用户输入的搜索词
boolean fileMovedOrCopied = false; // 标志位,确保文件只被操作一次
while (scanner.hasNextLine()) {
String searchWord = scanner.nextLine().trim();
if (searchWord.equalsIgnoreCase("Exit")) {
break;
}
// 4. 执行搜索(忽略大小写)
if (pdfContent.toLowerCase().contains(searchWord.toLowerCase())) {
System.out.println("是的,'" + searchWord + "' 在文件中。");
// 5. 如果找到关键词且文件尚未被操作,则执行文件复制/移动
if (!fileMovedOrCopied) {
Path sourcePath = Paths.get(sourcePdfPath);
Path destinationPath = targetDirPath.resolve(sourcePath.getFileName()); // 保持原文件名
try {
// 复制文件到目标目录
// 如果需要移动文件,请使用 Files.move() 代替 Files.copy()
// Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件 '" + sourcePath.getFileName() + "' 已成功复制到 '" + targetDirectoryPath + "'。");
fileMovedOrCopied = true; // 设置标志位,避免重复操作
} catch (IOException e) {
System.err.println("复制文件失败: " + e.getMessage());
}
} else {
System.out.println("文件已因之前的搜索结果被操作,不再重复。");
}
} else {
System.out.println("不,'" + searchWord + "' 不在文件中。");
}
System.out.println("请输入下一个要搜索的词语(输入 'Exit' 结束):");
}
scanner.close();
System.out.println("程序结束。");
}
}通过遵循本教程的指导,你可以有效地利用Apache PDFBox库在Java应用程序中实现PDF文本搜索和文件自动化处理功能。
以上就是使用Java和PDFBox在PDF中搜索文本及文件操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号