Android 5.0以上使用原生的打印功能的方式来实现将webview的html转pdf

Android 5.0以上使用原生的打印功能的方式来实现将webview的html转pdf

  • 功能
    • 部分代码

功能

在使用webview加载一些html时,可能涉及到将html转成pdf文件方便预览,在Android5.0版本之后可以使用原生带的打印功能模块来实现。

部分代码

private void webViewToPdf(WebView webView, final String pdfFilePath) {
        //创建DexMaker缓存目录
        try {
            File pdfFile = new File(pdfFilePath);
            if (pdfFile.exists()) {
                pdfFile.delete();
            }
            pdfFile.createNewFile();
            descriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_WRITE);
            // 设置打印参数
            PrintAttributes.MediaSize isoA4 = PrintAttributes.MediaSize.ISO_A4;
            PrintAttributes attributes = new PrintAttributes.Builder()
                    .setMediaSize(isoA4)
                    .setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 240, 240))
                    .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                    .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
                    .build();
            // 计算webview打印需要的页数
            int numberOfPages = (int) ((webView.getContentHeight() * 240 / (isoA4.getHeightMils())));
            ranges = new PageRange[]{new PageRange(0, numberOfPages)};
            // 创建pdf文件缓存目录
            // 获取需要打印的webview适配器
            printAdapter = webView.createPrintDocumentAdapter();
            // 开始打印
            printAdapter.onStart();
            printAdapter.onLayout(attributes, attributes, new CancellationSignal(),
                    getLayoutResultCallback(new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if (method.getName().equals("onLayoutFinished")) {
                                // 监听到内部调用了onLayoutFinished()方法,即打印成功
                                onLayoutSuccess(getWriteResultCallback(new InvocationHandler() {
                                    @Override
                                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                        if (method.getName().equals("onWriteFinished")) {
                                            Toast.makeText(MainActivity.this, "导出成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(context, PdfReaderActivity.class);
                                            intent.putExtra("pdf", pdfFilePath);
                                            startActivity(intent);
                                        } else {
                                            Toast.makeText(MainActivity.this, "导出失败", Toast.LENGTH_SHORT).show();
                                        }
                                        return null;
                                    }
                                }));
                            } else {
                                // 监听到打印失败或者取消了打印
                                Toast.makeText(MainActivity.this, "导出失败,请重试", Toast.LENGTH_SHORT).show();
                            }
                            return null;
                        }
                    }), new Bundle());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void onLayoutSuccess(PrintDocumentAdapter.WriteResultCallback callback) {
        printAdapter.onWrite(ranges, descriptor, new CancellationSignal(), callback);
    }

    private void onLayoutSuccess() throws IOException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            PrintDocumentAdapter.WriteResultCallback callback = getWriteResultCallback(new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) {
                    if (method.getName().equals("onWriteFinished")) {
                        Toast.makeText(MainActivity.this, "导出成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "导出失败", Toast.LENGTH_SHORT).show();
                    }
                    return null;
                }
            });
            printAdapter.onWrite(ranges, descriptor, new CancellationSignal(), callback);
        }
    }

    public static PrintDocumentAdapter.LayoutResultCallback getLayoutResultCallback(InvocationHandler invocationHandler) throws IOException {
        return ProxyBuilder.forClass(PrintDocumentAdapter.LayoutResultCallback.class)
                .handler(invocationHandler)
                .build();
    }

    public static PrintDocumentAdapter.WriteResultCallback getWriteResultCallback(InvocationHandler invocationHandler) throws IOException {
        return ProxyBuilder.forClass(PrintDocumentAdapter.WriteResultCallback.class)
                .handler(invocationHandler)
                .build();
    }


你可能感兴趣的:(Android)