當前位置:編程學習大全網 - 源碼下載 - 怎樣用iText讀取pdf文件

怎樣用iText讀取pdf文件

用iText讀取pdf文件舉例:(1)在Eclipse中新建壹個Java工程。(2)下載相應的iText-5.0.2.jar並放到對應的lib目錄下。在工程中創建包並創建測試類,該類包含壹個inspect方法用於從壹個PDF中獲取文本,它接受兩個參數,分別是PDF文件路徑和輸出流,指定要提取的PDF文件的路徑和讀取PDF所用的輸出流,比如:PDF路徑為E://text.pdf。然後調用iText提供的PdfReader類和PdfTextExtractor類,將PDF格式的文本提取出來並寫入txt文件中。部分代碼如下:import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import com.itextpdf.text.DocumentException;import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.parser.PdfTextExtractor;public class PDF { /** The resulting text file with info about a PDF. */ public static final String RESULT = "d:/ceshi.txt";//存放由pdf轉換成txt文件的路徑。 /** * Main method. * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws DocumentException, IOException { PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT));//txt文件寫入流 String string = "E:/text.pdf";//pdf文件路徑 inspect(writer,string); //調用讀取方法 writer.close(); } /** * Inspect a PDF file and write the info to a txt file * @param writer Writer to a text file * @param filename Path to the PDF file * @throws IOException */ public static void inspect(PrintWriter writer, String filename) throws IOException { PdfReader reader = new PdfReader(filename); //讀取pdf所使用的輸出流 int num = reader.getNumberOfPages();//獲得頁數 String content = ""; //存放讀取出的文檔內容 for (int i = 1; i < num; i++) { content += PdfTextExtractor.getTextFromPage(reader, i); //讀取第i頁的文檔內容 } writer.write(content);//寫入文件內容 writer.flush(); }}

  • 上一篇:怎麽用VB做8位CRC程序
  • 下一篇:Android 屏幕適配神器ScreenMatch
  • copyright 2024編程學習大全網