一、简介
Android4.4(KitKat,api-19)系统内置了打印框架,通过安装对应打印机的打印插件,就可以容易实现打印功能;
关于 图片、webview、layout及截屏相关的打印方式,已有很多相关教程;该篇使用介绍使用简单方式,实现对现成pdf文档进行打印。
二、实现
1.安装打印插件
1) 在应用市场,搜索对应打印机的打印服务插件,安装;
2) 推荐使用“Mopria PrintService”打印服务插件;
“Mopria Print Service”为Mopria联盟推出的一款Android设备打印服务应用,官网为/zh-cn;可以支持大部分的打印设备。
3)安装完成后,系统设置 –>高级设置 -> 打印–> 打印服务,可以看到“Mopria Print Service”,点击进入,选择打开,会自动搜索网络中的打印机。
“打印”菜单,在不同的手机,位置可能会有差异。
2.代码实现
1)调用系统打印
private void doPdfPrint(String filePath) {PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);MyPrintPdfAdapter myPrintAdapter = new MyPrintPdfAdapter(filePath);printManager.print("jobName", myPrintAdapter, null);}
2)MyPrintPdfAdapter
public class MyPrintPdfAdapter extends PrintDocumentAdapter {private String mFilePath;public MyPrintPdfAdapter(String file) {this.mFilePath = file;}@Overridepublic void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal,LayoutResultCallback callback, Bundle extras) {if (cancellationSignal.isCanceled()) {callback.onLayoutCancelled();return;}PrintDocumentInfo info = new PrintDocumentInfo.Builder("name").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();callback.onLayoutFinished(info, true);}@Overridepublic void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal,WriteResultCallback callback) {InputStream input = null;OutputStream output = null;try {input = new FileInputStream(mFilePath);output = new FileOutputStream(destination.getFileDescriptor());byte[] buf = new byte[1024];int bytesRead;while ((bytesRead = input.read(buf)) > 0) {output.write(buf, 0, bytesRead);}callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {try {output.close(); } catch (IOException e) {e.printStackTrace();}try {input.close();} catch (IOException e) {e.printStackTrace();}}}}
Demo下载地址
打印插件“Mopria PrintService”下载地址