java - PDFBox - 从多个 PDF 中读取文本并将其加载到多个文本文件中
问题描述
我在一个文件夹中有 1000 多个 pdf 文件,每个文件都需要转换并保存在其相应的文本文件中。我对 Java 有点陌生,我正在使用 PDFBox 进行转换;我成功地获得了一个 pdf 的代码,但我被困在如何为单个文件夹中的所有 PDFS 进行转换。有人可以帮助我在 Java 中实现这一目标吗?.
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public final class ExtractPdf
{
public static void main( String[] args ) throws IOException
{
String fileName = "sample.pdf";
PDDocument document = null;
try (PrintWriter out = new PrintWriter("out.txt"))
{
document = PDDocument.load( new File(fileName));
PDFTextStripper stripper = new PDFTextStripper();
String pdfText = stripper.getText(document).toString();
System.out.println( "Text in the area:" + pdfText);
out.println(pdfText);
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
谢谢,免费
解决方案
基本上你的问题是如何通过一个目录...</p>
public static void main(String[] args) throws IOException
{
File dir = new File("....");
File[] files = dir.listFiles(new FilenameFilter()
{
// use anonymous inner class
@Override
public boolean accept(File dir, String name)
{
return name.toLowerCase().endsWith(".pdf");
}
});
// null check omitted!
for (File file : files)
{
int len = file.getAbsolutePath().length();
String txtFilename = file.getAbsolutePath().substring(0, len - 4) + ".txt";
// check whether txt file exists omitted
try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(txtFilename), Charsets.UTF_8);
PDDocument document = PDDocument.load(file))
{
PDFTextStripper stripper = new PDFTextStripper();
stripper.writeText(document, out);
}
}
// exception catch omitted. Add code here to avoid your whole job
// dying if only one file is broken
}
推荐阅读
- python - 创建后网址不存在
- azure - AADSTS65001:用户或管理员未同意使用 ID 为“的应用程序”
- javascript - Vue js获取存储在div中的隐藏输入的单个值
- python - 从 mysql 选择/加载数据到内存/pandas 的最快方法
- select - 开放层:持久选择交互功能的问题
- java - 如何知道 PhantomReference 的引用对象是否真的是 GC-ed?
- bash - 环境变量 Bash PROMPT_COMMAND 的 ksh 等效项
- model-view-controller - dotnet core 中多个局部视图的模型绑定
- javascript - 用增量值和超时填充一个条形图
- android - 如何修复 Volley 库中的 JSONException 错误?