博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android Pdf文档的生成、显示与打印
阅读量:7069 次
发布时间:2019-06-28

本文共 4587 字,大约阅读时间需要 15 分钟。

hot3.png

Android 6.0带来了好多功能,PDF的读取展示就是其中一项

一.PDF文档的生成

 DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); // create a new document PdfDocument document = new PdfDocument();//当然,我们也可以使用PrintedPdfDocument,后者继承自前者 // crate a page descriptionfor(int i=0;i

二.PDF文档读取与显示(配合ViewPager使用)

ParcelFileDescriptor pfdesc =  ParcelFileDescriptor.open(new File('/storage/cache/mypage.pdf',ParcelFileDescriptor.MODE_READ_ONLY));PdfRender pdfRender = new PdfRender(pfdesc);List
 mlist = new ArrayList
();  //此处职位示例,正式项目请使用懒加载,否则可能导致OOMif(pdfRender.getPageCount()>0){   for(int i=0;i

三.打印PDF文档

打印pdf先要生成pdf打印文档,其次需要使用打印管理器

 PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE); printManager.print(String printJobName, PrintDocumentAdapter documentAdapter, PrintAttributes attributes)

当然,我们需要完成PrintDocumentAdapter

public class MyPrintDocumentAdapter extends PrintDocumentAdapter{	Context context;    	private int pageHeight;    	private int pageWidth;    	public PdfDocument myPdfDocument;     	public int totalpages = 4;			public MyPrintDocumentAdapter(Context context)	{		this.context = context;	}			@Override	public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal,		                 LayoutResultCallback callback,		                 Bundle metadata) {		                 	myPdfDocument = new PrintedPdfDocument(context, newAttributes); //创建可打印PDF文档对象		    	pageHeight =                 newAttributes.getMediaSize().getHeightMils()/1000 * 72; //设置尺寸	pageWidth =                 newAttributes.getMediaSize().getWidthMils()/1000 * 72;		    	if (cancellationSignal.isCanceled() ) {		callback.onLayoutCancelled();		return;	}		    	if (totalpages > 0) {	   PrintDocumentInfo.Builder builder = new PrintDocumentInfo		  .Builder("print_output.pdf") 		  .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)		  .setPageCount(totalpages);  //构建文档配置信息		                	   PrintDocumentInfo info = builder.build();	   callback.onLayoutFinished(info, true);	 } else {	   callback.onLayoutFailed("Page count is zero.");	 }	}					@Override	public void onWrite(final PageRange[] pageRanges,final ParcelFileDescriptor destination,final CancellationSignal cancellationSignal,		              final WriteResultCallback callback) {		              		for (int i = 0; i < totalpages; i++) {		if (pageInRange(pageRanges, i)) //保证页码正确	   	{		     PageInfo newPage = new PageInfo.Builder(pageWidth,                          pageHeight, i).create();		    			     PdfDocument.Page page =                           myPdfDocument.startPage(newPage);  //创建新页面		     if (cancellationSignal.isCanceled()) {  //取消信号			  callback.onWriteCancelled();			  myPdfDocument.close();			  myPdfDocument = null;			  return;		     }		     drawPage(page, i);  //将内容绘制到页面Canvas上		     myPdfDocument.finishPage(page);  		}	}	    	try {		myPdfDocument.writeTo(new FileOutputStream(		            destination.getFileDescriptor()));	} catch (IOException e) {		callback.onWriteFailed(e.toString());		return;	} finally {		myPdfDocument.close();		myPdfDocument = null;	}	callback.onWriteFinished(pageRanges);              	}	private boolean pageInRange(PageRange[] pageRanges, int page)	{		for (int i = 0; i
= pageRanges[i].getStart()) &&                                       (page <= pageRanges[i].getEnd())) return true; } return false; } //页面绘制(渲染) private void drawPage(PdfDocument.Page page,                               int pagenumber) {     Canvas canvas = page.getCanvas();                    //这里是页码。页码不能从0开始     pagenumber++;          int titleBaseLine = 72;     int leftMargin = 54;     Paint paint = new Paint();     paint.setColor(Color.BLACK);     paint.setTextSize(40);     canvas.drawText(                     "Test Print Document Page " + pagenumber,                                                   leftMargin,                                                   titleBaseLine,                                                    paint);     paint.setTextSize(14);     canvas.drawText("Android PDF 文档打印", leftMargin, titleBaseLine + 35, paint);     if (pagenumber % 2 == 0)      paint.setColor(Color.RED);     else      paint.setColor(Color.GREEN);          PageInfo pageInfo = page.getInfo();               canvas.drawCircle(pageInfo.getPageWidth()/2,                                     pageInfo.getPageHeight()/2,                                      150,                                      paint);  }}.

转载于:https://my.oschina.net/ososchina/blog/636397

你可能感兴趣的文章
[Android]在Dagger 2中使用RxJava来进行异步注入(翻译)
查看>>
是技术还是态度,网易的视频Title
查看>>
ES 處於“initializing”狀態,此時主節點正在嘗試將分片分配到集群中的數據節點。 如果您看到分片仍處於初始化或未分配狀態太長時間,則可能是您的集群不穩定的警告信號。...
查看>>
切换RequiredFieldValidator和RegularExpressionValidator提示信息的控件
查看>>
基于类的封装[基础]
查看>>
android studio插件提升工作效率
查看>>
What is VMR(Video Mixing Render)-From MSDN
查看>>
Linux下安装nmap扫描工具
查看>>
git 创建branch分支【转】
查看>>
北京某公司.NET面试题
查看>>
解决异常“SqlParameterCollection 只接受非空的 SqlParameter 类型对象。”
查看>>
PostgreSQL通过mysql_fdw访问MySQL数据库
查看>>
REST风格的原则
查看>>
Struts分页的一个实现
查看>>
[LintCode] Nuts & Bolts Problem 螺栓螺母问题
查看>>
53.2. group_concat() 列传行
查看>>
I.MX6 SHT20 Linux 驱动移植
查看>>
7.4. String
查看>>
使用PHP配置文件
查看>>
【Java数据结构学习笔记之二】Java数据结构与算法之栈(Stack)实现
查看>>