Android实现系统打印功能实现系统打印功能
主要为大家详细介绍了Android实现系统打印功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Android实现系统打印的具体代码,供大家参考,具体内容如下
一、打印图片一、打印图片
使用PrintHelper类,如:
private void doPhotoPrint() {
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.droids);
photoPrinter.printBitmap("droids.jpg - test print", bitmap);
}
可以在应用的菜单栏中调用该方法,当printBitmap()方法调用时,Android系统的打印界面
会弹出,用户可以设置一些参数,然后进行打印或取消。
二、打印自定义文档二、打印自定义文档
1.连接到PrintManager类:
private void doPrint() {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) getActivity()
.getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = getActivity().getString(R.string.app_name) + " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
null); //
}
注:注:print函数第二个参数为继承了抽象类PrintDocumentAdapter 的适配器类,第三个参数为 PrintAttributes对象,
可以用来设置一些打印时的属性。
2.创建打印适配器类
打印适配器与Android系统的打印框架进行交互,处理打印的生命周期方法。打印过程主要有以下生命周期方法:
onStart():当打印过程开始的时候调用;
onLayout():当用户更改打印设置导致打印结果改变时调用,如更改纸张尺寸,纸张方向等;
onWrite():当将要打印的结果写入到文件中时调用,该方法在每次onLayout()调用后会调用一次或多次;
onFinish():当打印过程结束时调用。
注:注:关键方法有onLayout()和onWrite(),这些方法默认都是在主线程中调用,因此如果打印过程比较耗时,应该在后台线程中
进行。
3.覆盖onLayout()方法
在onLayout()方法中,你的适配器需要告诉系统框架文本类型,总页数等信息,如:
@Override
public void onLayout(PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
// Create a new PdfDocument with the requested page attributes
mPdfDocument = new PrintedPdfDocument(getActivity(), newAttributes);
// Respond to cancellation request
if (cancellationSignal.isCancelled() ) {
callback.onLayoutCancelled();
return;
}
// Compute the expected number of printed pages
int pages = computePageCount(newAttributes);
评论0