IText无法使用Java读取PDF中的空格

时间:2017-05-30 11:34:05

标签: java itext

我正在尝试通过IText阅读PDF文件, 程序成功读取pdf文件,但无法包含空格。

程序:

  public void parse(String filename) throws IOException {
        PdfReader reader = new PdfReader(filename);
        PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(reader);
      TextExtractionStrategy strategy = null;
      for (int i=1; i<= reader.getNumberOfPages(); i++) {
           String text = PdfTextExtractor.getTextFromPage(reader, i, new LocationTextExtractionStrategy());
          System.out.println(text);

        }
    }

这里需要从pdf获取数据

here is data need to get from pdf

当程序正在读取pdf时,输出为:

  DATE MODE PARTICULARS DEPOSITS WITHDRAWALS BALANCE
   01-04-2017 B/F 54,396.82

如果你在图片中看到日期是01-04-2017,MODE有空的详细信息值是B / F,DEPOSITS和WITHDRAWALS也是空值,BALANCE是54,396.82 我需要的文本形式相同的数据

e.g .--&GT;

 DATE      MODE PARTICULARS DEPOSITS WITHDRAWALS BALANCE
 01-04-2017     B/F                              54,396.82

需要帮助,提前谢谢。

1 个答案:

答案 0 :(得分:0)

您正在从PDF中提取文本,结果是正确的,它不会缺少空格,因为原始文本中没有空格。

然而(我之前错过了,所以我正在编辑),你正在使用LocationTextExtractionStrategy,这是“表感知”。这很好,但最后getTextFromPage丢弃了表感知信息。

因此,您可以创建自己的策略实现,扩展LocationTextExtractionStrategy,添加getTabulatedText()方法以在您希望的位置插入空格的情况下吐出文本。从getResultantText()中获取灵感,看看它如何在每个单元格之间插入一个空格......在代码中,您可以根据需要插入尽可能多的空格(或制表符)。请参阅this answer for an example

MyTextExtractionStrategy strategy = new MyTextExtractionStrategy();
for (int i=1; i<= reader.getNumberOfPages(); i++) {
    String rawText = PdfTextExtractor.getTextFromPage(reader, i, strategy);
    String tabulatedText = strategy.getTabulatedText();
    System.out.println(text);
}

(也许有一个“策略”实现已经做到了,但我不知道)

相关问题