首页 > 解决方案 > Java:从 PDF 中提取文本并显示为标题和项目单独的数组列表

问题描述

我正在使用 PDFBOX 并从 PDF 文件中读取和保存内容。要求是文本应该在单独的数组列表中拆分为 Header 和 Item 。

PDF如下所示。

在此处输入图像描述

预期的 :

以下详细信息 PO、交货日期、供应商编号应显示在数组列表 1 中,其他详细信息如条形码、项目编号、描述、数量应显示在数组列表 2 中。

用于从 PDF 中将数据提取为 txt 的现有代码。

PDFBoxReadFromFile.java

package pdfboxreadfromfile;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.io.*;

public class PDFBoxReadFromFile {

  /**
   * @param args the command line arguments
   */

  public static void main(String[] args) {
    PDFManager pdfManager = new PDFManager();
    pdfManager.setFilePath("C:\\Users\\34\\Documents\\test.pdf");
    try {
      String text = pdfManager.toText();
      System.out.println(text);
      File file = new File("C:/Users/34/eclipse-workspace/pdfboxreadfromfile/file.txt");
      FileWriter fw = new FileWriter(file);
      PrintWriter pw = new PrintWriter(fw);
      pw.println(text);
      pw.close();



    } catch (IOException ex) {
      //System.err.println(ex.getMessage());
      Logger.getLogger(PDFBoxReadFromFile.class.getName()).log(Level.SEVERE, null, ex);

    }
  }

}

PDFManager.Java

package pdfboxreadfromfile;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class PDFManager {
  private PDFParser parser;
  private PDFTextStripper pdfStripper;
  private PDDocument pdDoc;
  private COSDocument cosDoc;

  private String Text;
  private String filePath;
  private File file;

  public PDFManager() {

  }

  public String toText() throws IOException {
    this.pdfStripper = null;
    this.pdDoc = null;
    this.cosDoc = null;

    file = new File(filePath);
    parser = new PDFParser(new RandomAccessFile(file, "r")); // update for PDFBox V 2.0

    parser.parse();
    cosDoc = parser.getDocument();
    pdfStripper = new PDFTextStripper();
    pdDoc = new PDDocument(cosDoc);
    pdDoc.getNumberOfPages();
    pdfStripper.setStartPage(0);
    pdfStripper.setEndPage(pdDoc.getNumberOfPages());
    Text = pdfStripper.getText(pdDoc);
    return Text;
  }

  public void setFilePath(String filePath) {
    this.filePath = filePath;
  }

  public PDDocument getPdDoc() {
    return pdDoc;
  }

}

爪哇

标签: javaarrayspdfbox

解决方案


推荐阅读