需要将应用中生成的PDF直接打印出来
构建PDFDocumentAdapter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| public class PDFDocumentAdapter extends PrintDocumentAdapter {
private static final String TAG = "PDFDocumentAdapter"; Context context; String pdfPath; File pdfFile;
public PDFDocumentAdapter(Context context, String pdfPath) { this.context = context; this.pdfPath = pdfPath; }
public PDFDocumentAdapter(Context context, File pdfFile) { this.context = context; this.pdfFile = pdfFile; }
@Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) { if (cancellationSignal.isCanceled()) { callback.onLayoutCancelled(); InsToastUtil.showInBottom("取消打印"); } else { PrintDocumentInfo.Builder builder = new PrintDocumentInfo.Builder(" file name"); builder.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN) .build(); callback.onLayoutFinished(builder.build(), !newAttributes.equals(oldAttributes)); } }
@Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { InputStream in = null; OutputStream out = null; try { File file; if (pdfFile != null) { file = pdfFile; }else { file = new File(pdfPath); } in = new FileInputStream(file); out = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[16384]; int size;
while ((size = in.read(buf)) >= 0 && !cancellationSignal.isCanceled()) { out.write(buf, 0, size); }
if (cancellationSignal.isCanceled()) { callback.onWriteCancelled(); InsToastUtil.showInBottom("取消打印"); } else { callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES}); InsToastUtil.showInBottom("打印完成"); } } catch (Exception e) { callback.onWriteFailed(e.getMessage()); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
|
打印
1 2 3 4 5 6 7 8 9 10 11 12
|
private void print() { PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE); try { PrintDocumentAdapter printAdapter = new PDFDocumentAdapter(this, Static.getRootFolderPath() + File.separator + "test.pdf"); printManager.print("Document", printAdapter, new PrintAttributes.Builder().build()); } catch (Exception e) { e.printStackTrace(); } }
|

需要手动添加打印机,即可打印,但是打印过程中存在纸张尺寸不匹配问题