java讀取pdf文件內容


使用JAVA從PDF中獲取文字信息,目前只能讀取文字型PDF。圖片型PDF尚在研究
1.導入Maven依賴

<dependency>
  <groupId>org.apache.pdfbox</groupId>
  <artifactId>pdfbox</artifactId>
</dependency>

2.示例代碼

package com.example.pdfuntil;

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.FileWriter;
import java.io.IOException;

public class ReadPdf {
    public static void main(String[] args) {
        String inputPath = "C:/example/PdfTest/pdf_demo1.pdf";
        String outputPath = "C:/example/PdfTest/demo.txt";
        readPdf(inputPath, outputPath);
    }

    public static void readPdf(String inputPath, String outputPath) {
        try (PDDocument document = PDDocument.load(new File(inputPath))) {

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();

                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                String[] lines = pdfFileInText.split("\\r?\\n");

                FileWriter fw = new FileWriter(outputPath);

                for (String line : lines) {
                    System.out.println(line);
                    fw.write(line + "\n");
                }

                fw.close();

                document.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM