java pdf转txt【完整代码包含jar包】
生活随笔
收集整理的這篇文章主要介紹了
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 DocumentPDDocument document = null;try {//注意參數是File。document = PDDocument.load(pdfFile);// 以原來PDF的名稱來命名新產生的txt文件textFile=fileStr.replace(".pdf",".txt");// 文件輸入流,寫入文件倒textFileoutput = 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 Documentdocument.close();}}}public static void main(String[] args) {try {//單個pdf轉txtString 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文件如下:
總結
以上是生活随笔為你收集整理的java pdf转txt【完整代码包含jar包】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dev GridView表格数据转成Da
- 下一篇: pandas基础及应用(1)