如何在Android Studio中从PDF文档中的某个区域获取文本?

5fjcxozz  于 2022-12-14  发布在  Android
关注(0)|答案(1)|浏览(237)

我想从PDF文档中的某个位置获取数据。
我尝试使用pdfbox库从PDF中的某个区域获取文本。但是addRegion方法需要Rectangle2D。Android只有Rect类,而不是Rectangle2D。因此,我在以下方面遇到错误:

stripper.addRegion("class1", rect);

我该怎么做才能克服这个问题?是否有其他方法可以使用Android SDK从PDF文档中的某个位置提取数据?是否有其他库可以实现这一点?因为我认为没有适用于Android Studio for Rectangle2D的库。

PDDocument document = PDDocument.load(new File("/Users/osman/Desktop/test.pdf"));
    PDFTextStripperByArea stripper = new PDFTextStripperByArea();
    stripper.setSortByPosition(true);
    Rect rect = new Rect(0, 0, 0, 0);
    stripper.addRegion("class1", rect);
    stripper.extractRegions(document.getPage(1));
    System.out.println(stripper.getTextForRegion("class1"));

Error Message

s2j5cfk0

s2j5cfk01#

我找到了自己问题的解决方案:
GitHub上有一个适用于Android的PDFBox库。https://github.com/TomRoush/PdfBox-Android
将此添加到Android。

dependencies {
    implementation 'com.tom-roush:pdfbox-android:2.0.25.0'
}

提取数据的代码为:

File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    File file = new File(path, "Test.pdf");
    PDDocument document = PDDocument.load(new File(file.getAbsolutePath()));
    PDFBoxResourceLoader.init(getApplicationContext());
    PDFTextStripperByArea stripper = new PDFTextStripperByArea();
    stripper.setSortByPosition(true);
    RectF rect = new RectF(100, 100, 300, 300);
    stripper.addRegion("class1", rect);
    stripper.extractRegions(document.getPage(0));
    System.out.println(stripper.getTextForRegion("class1"));

相关问题