首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PDFBox -从多个PDF中读取文本并将其加载到多个文本文件中

PDFBox -从多个PDF中读取文本并将其加载到多个文本文件中
EN

Stack Overflow用户
提问于 2018-10-08 00:16:44
回答 1查看 805关注 0票数 0

我在一个文件夹中有超过1000个pdf文件,每个文件都要转换并保存在相应的文本文件中。我是Java的新手,我正在使用PDFBox进行转换;我成功地获得了单个pdf的代码,但我被困在如何为单个文件夹中的所有pdf进行转换。有没有人能用Java帮我做到这一点?

代码语言:javascript
复制
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();
        }
    }
 }
}

谢谢,免费

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-08 01:41:39

基本上,您的问题是如何遍历目录…

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52690457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档