【问题标题】:Get line of PDF file after a specific line在特定行之后获取 PDF 文件的行
【发布时间】:2018-12-16 13:35:40
【问题描述】:

我使用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 的解决方案。 解决方案一:

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

解决方案 2:

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

【问题讨论】:

  • “但它不稳定,因为无法过滤到特定文本” - 你能解释一下你的意思吗?
  • 您的解决方案 1 应该适用于由 Microsoft Word 等编辑器生成的基本格式的 PDF。它实际上与 PDFBox 源代码使用的行分隔符相同。我怀疑在许多奇怪的情况下,PDF 具有奇怪的格式,会给您带来不稳定的结果,但是除非您控制需要文本挖掘的 PDF 的创建,否则您无法控制这种情况。这是一个从 PDF 中捕获行的教程,但它仅适用于格式正确的 PDF。此外,在完成本教程后,您只需调用 lines.get(index) 即可获得所需的行号:

标签: java string file-io pdfbox text-processing


【解决方案1】:

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

你看,PDFTextStrippergetText 方法调用了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 的实现,而在于您尝试发送文本的 PDF 源

这是一个教程的链接,它也可以做你想做的事情:

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

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

【讨论】:

  • 尝试在剥离器中切换排序选项。
猜你喜欢
  • 2022-12-24
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
相关资源
最近更新 更多