实现调用系统打印服务来打印PDF文件,直接上代码
注:必须android系统中存在打印服务才可调用
调用PrintManager
PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE);
//一些属性设置 PrintAttributes.Builder builder = new PrintAttributes.Builder(); builder.setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME); builder.setMinMargins(new PrintAttributes.Margins(300, 200, 300, 200)); PrintAttributes.MediaSize temp = PrintAttributes.MediaSize.ISO_A4; temp.asLandscape(); builder.setMediaSize(temp);
//创建打印适配器 MyPrintPdfAdapter,MyPrintPdfAdapter为自定义,代码在下文
//path为文件路径
MyPrintPdfAdapter myPrintAdapter = new MyPrintPdfAdapter(context, path);
//调用print,会弹出系统打印预览页面,自己选择可用的打印机,再点击打印即可
printManager.print(path , myPrintAdapter, builder.build());
2、自定义MyPrintPdfAdapter继承PrintDocumentAdapter,并重写onLayout()和onWrite()方法,必须重写,否则打印窗口无法预览文件,也无法打印
直接贴代码
private class MyPrintPdfAdapter extends PrintDocumentAdapter { private final Context context; private final String mFilePath; MyPrintPdfAdapter(Context context, String file) { this.context = context; this.mFilePath = file; this.finishCallback = finishCallback; } @Override public void onStart() { super.onStart(); } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, PrintDocumentAdapter.LayoutResultCallback callback, Bundle extras) { if (cancellationSignal.isCanceled()) { callback.onLayoutCancelled(); return; } File file = new File(mFilePath); if (!file.exists()) { callback.onLayoutFailed("文档页数为0"); return; } PrintDocumentInfo info = new PrintDocumentInfo.Builder("name") .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .build(); callback.onLayoutFinished(info, true); } @Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { InputStream input = null; OutputStream output = null; if (cancellationSignal.isCanceled()) { callback.onWriteCancelled(); return; } 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 (Exception e) { e.printStackTrace(); } finally { try { output.close(); } catch (IOException e) { e.printStackTrace(); } try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFinish() { super.onFinish(); //点击打印按钮会调用 } }
3、有时还想获取当前打印机打印状态,通过查看源码,在
PrintJobInfo类中,定义了以下几种状态
PrintJobInfo.STATE_QUEUED、 PrintJobInfo.STATE_STARTED、 PrintJobInfo.STATE_BLOCKED、 PrintJobInfo.STATE_COMPLETED、 PrintJobInfo.STATE_FAILED、 PrintJobInfo.STATE_CANCELED、 PrintJobInfo.STATE_CREATED
具体说明,在自行在PrintJobInfo类中查看