0

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

文件目录 = 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()

4

1 回答 1

1

这对我来说可以直接从它的 URL 打印出来

    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);
于 2018-03-12T07:17:15.507 回答