java pdf轉txt【完整代碼包含jar包】

一、POM
二、代碼
三、效果

一、POM文件

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

二、代碼

package com.ct.util;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.*;

public class Pdf2TextUtil {


    /**
     * 傳入一個pdf文件str(文件路徑)
     * @param fileStr
     * @throws Exception
     */
    public static String readPdf(String fileStr) throws Exception {
        // 是否排序
        boolean sort = false;
        File pdfFile=new File(fileStr);
        // 輸入文本文件名稱
        String textFile = null;
        // 編碼方式
        String encoding = "UTF-8";
        // 開始提取頁數
        int startPage = 1;
        // 結束提取頁數
        int endPage = Integer.MAX_VALUE;
        // 文件輸入流,生成文本文件
        Writer output = null;
        // 內存中存儲的PDF Document
        PDDocument document = null;
        try {

            //注意參數是File。
            document = PDDocument.load(pdfFile);

            // 以原來PDF的名稱來命名新產生的txt文件
            textFile=fileStr.replace(".pdf",".txt");

            // 文件輸入流,寫入文件倒textFile
            output = new OutputStreamWriter(new FileOutputStream(textFile),encoding);
            // PDFTextStripper來提取文本
            PDFTextStripper stripper = null;
            stripper = new PDFTextStripper();
            // 設置是否排序
            stripper.setSortByPosition(sort);
            // 設置起始頁
            stripper.setStartPage(startPage);
            // 設置結束頁
            stripper.setEndPage(endPage);
            // 調用PDFTextStripper的writeText提取並輸出文本
            stripper.writeText(document, output);

            System.out.println(" pdf轉txt成功!");
            return textFile;
        } finally {
            if (output != null) {
                // 關閉輸出流
                output.close();
            }
            if (document != null) {
                // 關閉PDF Document
                document.close();
            }
        }
    }

    public static void main(String[] args) {
        try {
            //單個pdf轉txt
            String filePath="G:\\test\\分子結構模糊識別文獻\\Current challenges in development of.pdf";
            String txtStr = readPdf(filePath);

//            //遍歷讀取文件夾下的文件
//            String strPath="G:\\test\\publication-tran1";
//            List<File> fileList = FileUtil.getFileList(strPath);
//            for (int i=0;i<fileList.size();i++){
//                try {
//                    String txtStr = readPdf(fileList.get(i).getAbsolutePath());
//                } catch (Exception e) {
//                    System.out.println("出錯:"+fileList.get(i).getAbsolutePath());
//                }
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、效果

運行後生成的txt文件如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章