PDFBox - 获取单词位置(而不仅仅是字符')

use*_*797 6 java pdf text extraction pdfbox

是否可以使用PDFBox获取单词的位置,类似于"processTextPosition"?似乎processTextPosition仅在单个字符上调用,并且将它们合并为单词的代码是PDFTextStripper(在"normalize")方法中的一部分,该方法确实返回文本的位置.是否有提取位置的方法/实用程序?(对于那些想知道动机是什么的人 - 信息实际上是一个表,我们想要检测空单元格)谢谢

Ovo*_*eta 2

要获取从 pdf 文件中提取的文本中的单词及其 x 和 y 位置,您必须扩展 PdfTextStripper 类并使用自定义类从 pdf 文件中提取文本,例如

public class CustomPDFTextStripper extends PDFTextStripper{

    public CustomPDFTextStripper() throws IOException {

    }

    /**
    * Override the default functionality of PDFTextStripper.
    */

    @Override
    protected void writeString(String text, List<TextPosition> textPositions) throws IOException{
        TextPosition firstProsition = textPositions.get(0);
        writeString(String.format("[%s , %s , %s]", firstProsition.getTextPos().getXPosition(),
                firstProsition.getTextPos().getYPosition(), text));

    }
}
Run Code Online (Sandbox Code Playgroud)

创建此自定义类的对象并提取文本,如下所示

PDFTextStripper pdfStripper = new CustomPDFTextStripper();
String text = pdfStripper.getText(*pdf file wrapped as a PDDocument object*);
Run Code Online (Sandbox Code Playgroud)

生成的文本字符串的格式为 [xposition, yposition, word],由默认的单词分隔符分隔