Android实现系统打印功能
本文实例为大家分享了Android实现系统打印的具体代码,供大家参考,具体内容如下
一、打印图片
使用PrintHelper类,如:
privatevoiddoPhotoPrint(){
PrintHelperphotoPrinter=newPrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
Bitmapbitmap=BitmapFactory.decodeResource(getResources(),
R.drawable.droids);
photoPrinter.printBitmap("droids.jpg-testprint",bitmap);
}
可以在应用的菜单栏中调用该方法,当printBitmap()方法调用时,Android系统的打印界面
会弹出,用户可以设置一些参数,然后进行打印或取消。
二、打印自定义文档
1.连接到PrintManager类:
privatevoiddoPrint(){
//GetaPrintManagerinstance
PrintManagerprintManager=(PrintManager)getActivity()
.getSystemService(Context.PRINT_SERVICE);
//Setjobname,whichwillbedisplayedintheprintqueue
StringjobName=getActivity().getString(R.string.app_name)+"Document";
//Startaprintjob,passinginaPrintDocumentAdapterimplementation
//tohandlethegenerationofaprintdocument
printManager.print(jobName,newMyPrintDocumentAdapter(getActivity()),
null);//
}
注:print函数第二个参数为继承了抽象类PrintDocumentAdapter的适配器类,第三个参数为PrintAttributes对象,
可以用来设置一些打印时的属性。
2.创建打印适配器类
打印适配器与Android系统的打印框架进行交互,处理打印的生命周期方法。打印过程主要有以下生命周期方法:
- onStart():当打印过程开始的时候调用;
- onLayout():当用户更改打印设置导致打印结果改变时调用,如更改纸张尺寸,纸张方向等;
- onWrite():当将要打印的结果写入到文件中时调用,该方法在每次onLayout()调用后会调用一次或多次;
- onFinish():当打印过程结束时调用。
注:关键方法有onLayout()和onWrite(),这些方法默认都是在主线程中调用,因此如果打印过程比较耗时,应该在后台线程中进行。
3.覆盖onLayout()方法
在onLayout()方法中,你的适配器需要告诉系统框架文本类型,总页数等信息,如:
@Override
publicvoidonLayout(PrintAttributesoldAttributes,
PrintAttributesnewAttributes,
CancellationSignalcancellationSignal,
LayoutResultCallbackcallback,
Bundlemetadata){
//CreateanewPdfDocumentwiththerequestedpageattributes
mPdfDocument=newPrintedPdfDocument(getActivity(),newAttributes);
//Respondtocancellationrequest
if(cancellationSignal.isCancelled()){
callback.onLayoutCancelled();
return;
}
//Computetheexpectednumberofprintedpages
intpages=computePageCount(newAttributes);
if(pages>0){
//Returnprintinformationtoprintframework
PrintDocumentInfoinfo=newPrintDocumentInfo
.Builder("print_output.pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(pages);
.build();
//Contentlayoutreflowiscomplete
callback.onLayoutFinished(info,true);
}else{
//Otherwisereportanerrortotheprintframework
callback.onLayoutFailed("Pagecountcalculationfailed.");
}
}
注:onLayout()方法的执行有完成,取消,和失败三种结果,你必须通过调用PrintDocumentAdapter.LayoutResultCallback类的适当回调方法表明执行结果,onLayoutFinished()方法的布尔型参数指示布局内容是否已经改变。
onLayout()方法的主要任务就是计算在新的设置下,需要打印的页数,如通过打印的方向决定页数:
privateintcomputePageCount(PrintAttributesprintAttributes){
intitemsPerPage=4;//defaultitemcountforportraitmode
MediaSizepageSize=printAttributes.getMediaSize();
if(!pageSize.isPortrait()){
//Sixitemsperpageinlandscapeorientation
itemsPerPage=6;
}
//Determinenumberofprintitems
intprintItemCount=getPrintItemCount();
return(int)Math.ceil(printItemCount/itemsPerPage);
}
4.覆盖onWrite()方法
当需要将打印结果输出到文件中时,系统会调用onWrite()方法,该方法的参数指明要打印的页以及结果写入的文件,你的方法实现需要将页面的内容写入到一个多页面的PDF文档中,当这个过程完成时,需要调用onWriteFinished()方法,如:
@Override
publicvoidonWrite(finalPageRange[]pageRanges,
finalParcelFileDescriptordestination,
finalCancellationSignalcancellationSignal,
finalWriteResultCallbackcallback){
//Iterateovereachpageofthedocument,
//checkifit'sintheoutputrange.
for(inti=0;i
drawPage()方法实现:
privatevoiddrawPage(PdfDocument.Pagepage){
Canvascanvas=page.getCanvas();
//unitsareinpoints(1/72ofaninch)
inttitleBaseLine=72;
intleftMargin=54;
Paintpaint=newPaint();
paint.setColor(Color.BLACK);
paint.setTextSize(36);
canvas.drawText("TestTitle",leftMargin,titleBaseLine,paint);
paint.setTextSize(11);
canvas.drawText("Testparagraph",leftMargin,titleBaseLine+25,paint);
paint.setColor(Color.BLUE);
canvas.drawRect(100,100,172,172,paint);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。