【问题标题】:How to parse multiple pdfs to text from a folder in Java如何将多个pdf解析为Java文件夹中的文本
【发布时间】:2017-04-24 15:02:27
【问题描述】:

我有一个包含很多 pdf 的文件夹,我需要将它们全部转换为 txt 并将这些文本文件保存在另一个文件夹中。我想为此使用 java。

我有这段代码来解析一个 pdf,但它一次只能处理一个,我需要处理一个包含数千个 pdf 的文件夹。

 PDFTextStripper pdfStripper = null;
 PDDocument pdDoc = null;
 COSDocument cosDoc = null;
 File file = new File("C:/my.pdf");

 try {
     PDFParser parser = new PDFParser(new FileInputStream(file));
     parser.parse();
     cosDoc = parser.getDocument();
     pdfStripper = new PDFTextStripper();
     pdDoc = new PDDocument(cosDoc);
     pdfStripper.setStartPage(1);
     pdfStripper.setEndPage(20);
     String parsedText = pdfStripper.getText(pdDoc);
    }catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
 } 

有什么想法吗?

【问题讨论】:

  • 把上面的代码放在一个循环中,迭代文件。
  • 尝试使用文件夹名称和listFiles() 方法而不是一个文件名

标签: java pdf


【解决方案1】:

你可以试试这样的

PDFTextStripper pdfStripper = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
String parsedText=""; // append the text to this every time
File folder = new File("/yourFolder"); // put all the pdf files in a folder
File[] listOfFiles = folder.listFiles(); // get all the files as an array

    for (File file : listOfFiles) { // cycle through this array 
        if (file.isFile()) { // for every file
             try { //do the same 
                 PDFParser parser = new PDFParser(new FileInputStream(file));
                 parser.parse();
                 cosDoc = parser.getDocument();
                 pdfStripper = new PDFTextStripper();
                 pdDoc = new PDDocument(cosDoc);
                 pdfStripper.setStartPage(1);
                 pdfStripper.setEndPage(pdDoc.getNumberOfPages()); // if always till the last page
                 parsedText += pdfStripper.getText(pdDoc) +  System.lineSeparator(); // append the text to the String
                }catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
               } 
       }
  }

【讨论】:

  • 非常感谢!!作为跟进,我想知道是否有一种方法可以单独保存新的解析文件而不是一个大文本文件。
  • 很高兴能帮上忙 :) 您可以在每次循环后将“parsedText”保存到文件文本中,而不是将其附加到文本中
  • 谢谢!我会试试的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2019-11-15
  • 2013-11-25
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
相关资源
最近更新 更多