使用Android中的Print Manager将字节数组打印为PDF

时间:2018-02-24 20:49:31

标签: android android-print-framework

我正在从互联网上以字节数组的形式检索PDF。一旦我收到它,我就可以使用这种方法将其转换为文件:

File dir = Environment.getExternalStorageDirectory();

    File assist = new File(Environment.getExternalStorageDirectory() + "/Sample.pdf");
    try {
        InputStream fis = new FileInputStream(assist);

        long length = assist.length();
        if (length > Integer.MAX_VALUE) {
            Log.e("Print error", "Too large");
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        return new File(dir, "mydemo.pdf");

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

现在我有了这个文件,我该怎么办?在官方开发网站上:https://developer.android.com/training/printing/custom-docs.html它没有提供具体的信息,当我给它File时,打印管理器是否有办法为我们处理这个问题?或者我是否必须手动创建适配器?如果是这样,我将如何获得页数(我读到的是必须的)以及我将在onWrite()中做些什么?

1 个答案:

答案 0 :(得分:1)

这适用于我直接从其网址

打印
    PrintDocumentAdapter pda = new PrintDocumentAdapter() {

    @Override
    public void onWrite(PageRange[] pages, final ParcelFileDescriptor destination, CancellationSignal cancellationSignal, final WriteResultCallback callback) {

        !!THIS MUST BE RUN ASYNC!!

        InputStream input = null;
        OutputStream output = null;

        try {
            input = new URL(YOUR URL HERE).openStream();
            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 ee) {
            //TODO Handle Exception
        } catch (Exception e) {
            //TODO Handle Exception
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {

        if (cancellationSignal.isCanceled()) {
            callback.onLayoutCancelled();
            return;
        }
        PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("NAME OF DOCUMENT").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
        callback.onLayoutFinished(pdi, true);
    }
};

PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
printManager.print("JOB NAME", pda, null);