首页 > 解决方案 > 在特定行之后获取 PDF 文件的行

问题描述

Apache PDFBox用来解析pdf文件中的文本。我试图在特定行之后获得一行。

PDDocument document = PDDocument.load(new File("my.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text from pdf:" + text);
} else{
    log.info("File is encrypted!");
}
document.close();

样本:

第 1 句,文件的第 n 行

所需线路

第 3 句,文件的第 n+2 行

我试图从数组中的文件中获取所有行,但它不稳定,因为无法过滤到特定文本。这也是第二个解决方案中的问题,这就是我寻找PDFBox基于解决方案的原因。解决方案1:

String[] lines = myString.split(System.getProperty("line.separator"));

解决方案2:

String neededline = (String) FileUtils.readLines(file).get("n+2th")

标签: javastringfile-iopdfboxtext-processing

解决方案


事实上,该类的源代码使用PDFTextStripper与您完全相同的行结尾,因此您的第一次尝试使用 PDFBox 尽可能接近正确。

您会看到,该PDFTextStripper getText方法调用了该writeText方法,该方法仅使用该方法逐行写入输出缓冲区,其writeString方式与您已经尝试过的方式完全相同。此方法返回的结果是 buffer.toString()。

因此,给定格式良好的 PDF,您真正要问的问题似乎是如何过滤特定文本的数组。这里有一些想法:

首先,您像您说的那样在数组中捕获行。

import java.io.File;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class Main {

    static String[] lines;

    public static void main(String[] args) throws Exception {
        PDDocument document = PDDocument.load(new File("my2.pdf"));
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        lines = text.split(System.getProperty("line.separator"));
        document.close();
    }
}

这是一种通过任何行号索引获取完整字符串的方法,很简单:

// returns a full String line by number n
static String getLine(int n) {
    return lines[n];
}

这是一个线性搜索方法,它找到一个字符串匹配并返回找到的第一个行号。

// searches all lines for first line index containing `filter`
static int getLineNumberWithFilter(String filter) {
    int n = 0;
    for(String line : lines) {
        if(line.indexOf(filter) != -1) {
            return n;
        }
        n++;
    }
    return -1;
}

使用上述方法,可以只获取匹配搜索的行号:

System.out.println(getLine(8)); // line 8 for example

或者,包含匹配搜索的整个字符串行:

System.out.println(lines[getLineNumberWithFilter("Cat dog mouse")]);

这一切看起来都非常简单,并且仅在行可以通过行分隔符拆分为数组的假设下起作用。如果解决方案不像上述想法那么简单,我相信您的问题的根源可能不是您使用 PDFBox 的实现,而是您尝试使用文本 mine 的 PDF 源

这是一个教程的链接,该教程也可以执行您正在尝试做的事情:

https://www.tutorialkart.com/pdfbox/extract-text-line-by-line-from-pdf/

再次,同样的方法......


推荐阅读