乐趣区

关于android:Android将网页转换为PDF的初步实现

「Android」将网页转换为 PDF 的初步实现

获取指标网页 URL

    // 须要转换为网页 URL
    private static final String URL = "https://www.baidu.com";

获取 WebView 对象

    // 获取 WebView 对象
    mWebView = findViewById(R.id.demo_webView);

初始化 WebView 对象

    // 初始化 WebView 对象
    private void initWebView() {WebSettings settings = mWebView.getSettings();
        settings.setAllowContentAccess(true);
        settings.setBuiltInZoomControls(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        settings.setJavaScriptEnabled(true);
        // 开启 Application Cache 性能
        settings.setAppCacheEnabled(true);
        // 设置适配
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {super.onPageStarted(view, url, favicon);
                Log.d(TAG, "onPageStarted");
            }
            @Override
            public void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);
                Log.d(TAG, "onPageFinished");
                // 网页加载实现后
                // 将浏览器网页转换为 PDF
                captureBrowser(mWebView, WebViewActivity.this);
            }
        });
        mWebView.loadUrl(URL);
    }

将浏览器网页转换为 PDF

    /**
     * 将浏览器网页转换为 PDF
     *
     * @param webView webView
     * @param context context
     */
    public static void captureBrowser(WebView webView, Context context) {Log.d(TAG, "captureBrowser:");
        try {
            // 创立存储文件
            File pdfFile = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/PDF.pdf");
            if (pdfFile.exists()) {pdfFile.delete();
            }
            pdfFile.createNewFile();
            sDescriptor = 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, 500, 500))
                .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
                .build();
            // 计算须要的页数
            int numberOfPages = (webView.getContentHeight() * 500 / (isoA4.getHeightMils()));
            sRanges = new PageRange[] {new PageRange(0, numberOfPages)};
            // 获取 webView 适配器
            sPrintAdapter = webView.createPrintDocumentAdapter("PDF");
            // 开始打印
            sPrintAdapter.onStart();
            sPrintAdapter.onLayout(attributes, attributes, new CancellationSignal(),
                new PrintDocumentAdapter.LayoutResultCallback() {
                    @Override
                    public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {sPrintAdapter.onWrite(sRanges, sDescriptor, new CancellationSignal(),
                            new PrintDocumentAdapter.WriteResultCallback() {
                                @Override
                                public void onWriteFinished(PageRange[] pages) {Log.d(TAG, "onWriteFinished: PdfWrite is Finished");
                                    super.onWriteFinished(pages);
                                }
                            });
                        super.onLayoutFinished(info, changed);
                    }
                }, null);
        } catch (FileNotFoundException e) {e.printStackTrace();
        } catch (IOException e) {e.printStackTrace();
        }
    }
退出移动版