PDFBox - читать текст из нескольких PDF-файлов и загружать его в несколько текстовых файлов - PullRequest
0 голосов
/ 07 октября 2018

У меня есть более 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();
        }
    }
 }
}

Спасибо, бесплатно

1 Ответ

0 голосов
/ 07 октября 2018

По сути, ваш вопрос заключается в том, как пройти через каталог ...

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
}
...