在Android上从Webview创建PDF

euoag5mw  于 2023-01-24  发布在  Android
关注(0)|答案(3)|浏览(203)

所以我正在尝试从WebView创建PDF。现在我可以从WebView创建图像,但是我在将文档分割成许多页面时遇到了一些问题。
首先,我从webview创建一个位图:

public static Bitmap screenShot(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return bitmap;
    }

第二步,创建并显示PDF:

public void criaPdf(){
        Bitmap bitmap = Utils.screenShot(mContratoWebview);

        Document doc = new Document();

        File dir = new File(getFilesDir(), "app_imageDir");

        if(!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, "contratoPdf.pdf");

        try {
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

            byte[] byteArray = stream.toByteArray();
            Image image = Image.getInstance(byteArray);
            image.scaleToFit(PageSize.A4.getHeight(), PageSize.A4.getWidth());

            doc.newPage();
            doc.add(image);
        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally {
            doc.close();
        }

        mPdfView.fromFile(file)
                .pages(0, 1) // all pages are displayed by default
                .enableSwipe(true)
                .load();
        mPdfView.setVisibility(View.VISIBLE);
}

这是我目前得到的:

所以我的问题是:* * Webview的内容太大,PDF无法容纳。如何解决此问题?**

rhfm7lfc

rhfm7lfc1#

WebView具有生成PDF的内置功能,可通过使用PrintManager服务来使用。对于您的使用情况,我建议您将WebView的PrintAdapter的最终输出(PDF文件)写入/存储到本地文件中,然后从那里开始。
此链接将引导您了解详细信息和实施。http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
您可以通过对上述解决方案进行一些小的调整来实现API级别19(KitKat)兼容性。
这应该可以解决你的问题,但如果你遇到任何问题的实施让我知道。

afdcj2ne

afdcj2ne2#

要创建pdf从webview你需要android〉kitkat -〉软件开发包〉=19

btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {

                createWebPrintJob(webView);
            } else {


            }

        }
    });

////函数:

private void createWebPrintJob(WebView webView) {

    PrintManager printManager = (PrintManager) this
            .getSystemService(Context.PRINT_SERVICE);

    PrintDocumentAdapter printAdapter =
            webView.createPrintDocumentAdapter();

    String jobName = getString(R.string.app_name) + " Print Test";

    if (printManager != null) {
        printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());
    }
}

我在从webview创建图像时遇到问题:))))

hgc7kmma

hgc7kmma3#

在我的例子中,我解决了这个问题,首先将webview转换成位图,然后缩放位图以适合pdf页面。
至于打印部分,我认为简单地共享pdf并让用户选择打印机软件会更灵活,因为这比简单地保存为pdf更有用。
如果你想打印几页,我认为创建不同的位图并将其分配到不同的pdf页面更容易管理。
下面是将webview转换为单个pdf页面然后共享的代码:

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;
}

相关问题