如何在pdf文档中搜索字符串

How to search for a string in a pdf document

我有一个 pdf 文档,其中包含图像、超链接、文字和许多其他内容。

我想在所有的词中搜索一个刺,即排除图像和超链接。 如何用它编写 java 代码。有人可以帮忙吗。

您可以使用 Apache (https://pdfbox.apache.org/download.cgi) 的 PDFbox 库。 这是一个代码示例。

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
    public static void main(String args[]) throws IOException {
        Scanner scan = new Scanner(System.in);
        System.out.println("Type the directory of the PDF File : ");
        String PDFdir = scan.nextLine();
        System.out.println("Input the phrase to find");
        String phrase = scan.nextLine();
        File file = new File(PDFdir);
        PDDocument doc = PDDocument.load(file);
        PDFTextStripper findPhrase = new PDFTextStripper();
        String text = findPhrase.getText(doc);
        String PDF_content = text;
        String result = PDF_content.contains(phrase) ? "Yes" : "No"
        System.out.println(result);
        doc.close();
    }
}

请记住,您必须下载 PDFbox jar 文件并将其导入到您的项目中。

Output/Result :

编辑:

您还可以找到 PDF 中的短语数:

if (result.equals("Yes")) {
    int counter = 0;
        while(PDF_content.contains(phrase)) {
            counter++;
            PDF_content = PDF_content.replaceFirst(phrase, "");
        }
    System.out.println(counter);
}

Output/Result :