简体   繁体   English

使用 PdfDocument 将 webview 转换为 pdf

[英]webview into pdf using PdfDocument

I want to convert webview into PDF document and save the document in external storage.我想将 webview 转换为 PDF 文档并将文档保存在外部存储中。 The pdf should be similar to the one which we can generate we we print the webview and chose save as pdf instead of printing. pdf 应该与我们可以生成的类似,我们打印 webview 并选择另存为 pdf 而不是打印。

Code for Webview: Webview 的代码:

    WebView ww = (WebView) findViewById(R.id.ww);
    ww.getSettings().setUserAgentString("Mozilla/5.0 Chrome/53.0.2785.116");
    ww.getSettings().setDefaultTextEncodingName("en-US,en;q=0.8");
    WebSettings webSettings = ww.getSettings();
    webSettings.setJavaScriptEnabled(true);
    ww.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    ww.getSettings().setBuiltInZoomControls(true);
    ww.getSettings().setDisplayZoomControls(false);
    ww.getSettings().setLoadWithOverviewMode(true);
    ww.getSettings().setUseWideViewPort(true);
    ww.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

You can convert the webview into a bitmap and then into a PDF document.您可以将 webview 转换为 bitmap,然后转换为 PDF 文档。 The advantage of not converting directly to PDF is that you can scale the image to fit the PDF in any way you want.不直接转换为 PDF 的优点是您可以以任何您想要的方式缩放图像以适合 PDF。

This code converts a webview into a pdf page and then shares it, asking the user to select his printer app:此代码将 webview 转换为 pdf 页面,然后共享它,要求用户 select 他的打印机应用程序:

public static void sharePdfFile(WebView webView, Context context)
{
    Bitmap bitmap = webviewToBitmap( webView );
    PrintedPdfDocument pdf =  bitmapToPdf( bitmap, context );
    File file = pdfToFile( pdf, context );
    shareFile( file,"application/pdf", context );
}

private static void shareFile(File file, String contentType, Context context)
{
    Uri uri = FileProvider.getUriForFile(
        context,
        context.getPackageName() + ".fileprovider",
        file);
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType(contentType);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Toast.makeText(
        context,
        "Choose your printer app",
        Toast.LENGTH_LONG
    ).show();
    context.startActivity( shareIntent );
}

private static File pdfToFile(PrintedPdfDocument printedPdfDocument, Context context)
{
    File file = new File(context.getFilesDir(), "share.pdf");
    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        printedPdfDocument.writeTo(outputStream);
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    printedPdfDocument.close();
    return file;
}


private static PrintedPdfDocument bitmapToPdf(Bitmap bitmap, Context context)
{
    PrintAttributes printAttributes = new PrintAttributes.Builder()
        .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
        .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
        .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
        .setResolution(new PrintAttributes.Resolution("1", "label", 300, 300))
        .build();
    PrintedPdfDocument printedPdfDocument = new PrintedPdfDocument(context, printAttributes);
    PdfDocument.Page pdfDocumentPage = printedPdfDocument.startPage(1);
    Canvas pdfCanvas = pdfDocumentPage.getCanvas();
    bitmap = scaleBitmapToHeight(bitmap, pdfCanvas.getHeight());
    pdfCanvas.drawBitmap(bitmap, 0f, 0f, null);
    printedPdfDocument.finishPage(pdfDocumentPage);
    return printedPdfDocument;
}

private static Bitmap webviewToBitmap(WebView webView) {
    webView.measure(
        View.MeasureSpec.makeMeasureSpec(
            0,
            View.MeasureSpec.UNSPECIFIED
        ),
        View.MeasureSpec.makeMeasureSpec(
            0,
            View.MeasureSpec.UNSPECIFIED
        )
    );
    int webViewWidth = webView.getMeasuredWidth();
    int webViewHeight = webView.getMeasuredHeight();
    webView.layout(0,0, webViewWidth, webViewHeight );
    Bitmap bitmap = Bitmap.createBitmap(webViewWidth, webViewHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawBitmap(bitmap, 0, bitmap.getHeight(), new Paint());
    webView.draw(canvas);
    return bitmap;
}

private static Bitmap scaleBitmapToHeight(Bitmap bitmap, int maxHeight) {
    int height = bitmap.getHeight();
    if(height > maxHeight) {
        int width = bitmap.getWidth();
        float scalePercentage = ((float)maxHeight) / height;
        return Bitmap.createScaledBitmap(bitmap, (int) (width * scalePercentage), maxHeight, false);
    }
    return bitmap;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM