Android使用iText生成pdf文件并读取pdf内容

一、何为iText

iText是著名的开放源码的站点sourceforge的一个项目,可用来生成Pdf文件和读取Pdf文件内容.

我将iTextpdf的Jar包放在http://download.csdn.net/detail/xuwenneng/9669969 ,点击可前往下载.

二、使用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();
		}
	}

四、项目地址

http://download.csdn.net/detail/xuwenneng/9670114

github地址:https://github.com/xuwennengcan/MyPdf

猜你喜欢

转载自blog.csdn.net/xuwenneng/article/details/52995392
今日推荐