如何在Android中通过Print Manager将字节数组打印为PDF?
处理PDF文件打印的解决方案
嘿,刚好踩过这个坑!Android的PrintManager确实没有直接接收File的API,得自己写个适配器来桥接一下,其实步骤也不复杂,给你一步步说:
核心思路
PrintManager依赖PrintDocumentAdapter来获取打印内容,我们要做的就是实现一个自定义适配器,把本地PDF文件的内容读取出来,传递给打印框架。
具体步骤
1. 实现自定义PrintDocumentAdapter
这个适配器的核心是在onWrite方法里把PDF文件的字节流写入到打印输出的管道中,onLayout因为PDF的页面尺寸已经固定,直接返回成功即可:
public class PdfFilePrintAdapter extends PrintDocumentAdapter { private final File mPdfFile; public PdfFilePrintAdapter(File pdfFile) { mPdfFile = pdfFile; } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) { // PDF的页面信息已经固定,直接返回成功 PrintDocumentInfo info = new PrintDocumentInfo.Builder("PDF Document") .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .build(); callback.onLayoutFinished(info, true); } @Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { try (InputStream inputStream = new FileInputStream(mPdfFile); OutputStream outputStream = new FileOutputStream(destination.getFileDescriptor())) { // 把PDF文件内容复制到打印输出流 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES}); } catch (IOException e) { callback.onWriteFailed(e.getMessage()); } } }
2. 调用PrintManager发起打印
获取PrintManager实例,传入自定义适配器即可:
// 获取PrintManager服务 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE); // 自定义打印任务名称,会显示在打印队列里 String jobName = getString(R.string.app_name) + " PDF Print Job"; // 发起打印请求 printManager.print(jobName, new PdfFilePrintAdapter(yourPdfFile), null);
重要注意事项
- 权限问题:如果你的PDF文件存在外部公共存储(比如
Environment.getExternalStorageDirectory()),在Android 10及以上需要申请MANAGE_EXTERNAL_STORAGE权限,这权限比较敏感,更推荐把PDF文件放在应用私有外部目录(getExternalFilesDir(null)),这样不需要额外权限,安全性也更高。 - 取消信号处理:如果需要支持打印取消,可以在
onWrite里监听CancellationSignal,及时中断文件读写操作。
这样就能把你生成的PDF文件交给系统打印框架处理了,亲测有效~
内容的提问来源于stack exchange,提问作者Ali Bdeir
相关产品推荐
相关产品推荐

