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