Android使用iText生成pdf檔案並讀取pdf內容
阿新 • • 發佈:2019-01-26
一、何為iText
iText是著名的開放原始碼的站點sourceforge的一個專案,可用來生成Pdf檔案和讀取Pdf檔案內容.
二、使用iText生成Pdf檔案
1.將jar包放到自己的專案中,然後進行專案的編輯
2.生成Pdf檔案的程式碼:
Document doc = new Document();//建立一個document物件 FileOutputStream fos; try { fos = new FileOutputStream(new File(pdf_address)); //pdf_address為Pdf檔案儲存到sd卡的路徑 PdfWriter.getInstance(doc, fos); doc.open(); doc.setPageCount(1); doc.add(new Paragraph(result, setChineseFont())); //result為儲存的字串 ,setChineseFont()為pdf字型 // 一定要記得關閉document物件 doc.close(); fos.flush(); fos.close(); handler.sendEmptyMessage(PDF_SAVE_RESULT); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
/** * 設定PDF字型(較為耗時) */ public Font setChineseFont() { BaseFont bf = null; Font fontChinese = null; try { // STSong-Light : Adobe的字型 // UniGB-UCS2-H : pdf 字型 bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); fontChinese = new Font(bf, 12, Font.NORMAL); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fontChinese; }
三、讀取Pdf檔案內容
/** * 讀取Pdf檔案的內容 * @param path :檔案地址 */ public void readPdfContent(String path){ try { PdfReader pr = new PdfReader(path); int page = pr.getNumberOfPages(); String content = ""; for(int i = 1 ;i<page+1;i++){ content += PdfTextExtractor.getTextFromPage(pr, i); //遍歷頁碼,讀取Pdf檔案內容 } } catch (IOException e) { e.printStackTrace(); } }