Groovy PDFBox 按顺序读取 PDF 文件并提取内容到列表
以下是一个示例代码,可以按顺序读取 pdf 文件,并将每个页面的内容提取出来放到一个 list 中:
import java.io.File
import java.io.IOException
import java.util.ArrayList
import java.util.List
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.text.PDFTextStripper
class PDFReader {
static void main(String[] args) {
List<String> contentList = new ArrayList<String>()
try {
// Load PDF document
PDDocument document = PDDocument.load(new File('test.pdf'))
// Create PDF text stripper
PDFTextStripper stripper = new PDFTextStripper()
// Loop through each page and extract content
for (int i = 1; i <= document.getNumberOfPages(); i++) {
stripper.setStartPage(i)
stripper.setEndPage(i)
String content = stripper.getText(document)
contentList.add(content)
}
// Close the document
document.close()
} catch (IOException e) {
e.printStackTrace()
}
// Print the content list
for (String content in contentList) {
println content
}
}
}
在这个示例代码中,我们使用了 PDFBox 的 PDDocument 类来读取 pdf 文件。我们使用 PDFTextStripper 类来提取每个页面的内容,并将其添加到一个 list 中。最后,我们循环遍历这个 list 并将其输出到控制台。
原文地址: https://www.cveoy.top/t/topic/nwU9 著作权归作者所有。请勿转载和采集!