Android - Drawing to a PDF canvas from WebView

后端 未结 4 679
太阳男子
太阳男子 2021-01-04 01:53

I\'ve been having troubles getting PDF printing work on Android. What I\'m trying to do is render some HTML in WebView, then draw the WebView contents on a PDF canvas and fi

4条回答
  •  -上瘾入骨i
    2021-01-04 02:30

    I had the same problem.

    I solved it using very simple trick.

    Just set MediaSize to PrintAttributes.MediaSize.ISO_A1.

    The downside of this solution is the pdf size: even one-page-pdf with simple text has roughly 5MB.

    Working snippet of code (generates a pdf from a view and export it to a file):

    @TargetApi(19)
    private void generatePdf() {
        PrintAttributes.Builder builder = new PrintAttributes.Builder();
        builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
        builder.setMediaSize(PrintAttributes.MediaSize.ISO_A1); // or ISO_A0
        builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS);
        builder.setResolution(new PrintAttributes.Resolution("1", "label", 300, 300));
        PrintedPdfDocument document = new PrintedPdfDocument(this, builder.build());
        PdfDocument.Page page = document.startPage(1);
        View content = yourView;
        content.draw(page.getCanvas());
        document.finishPage(page);
        try {
            File file = new File(getExternalFilesDir(null).getAbsolutePath(), "document.pdf");
            document.writeTo(new FileOutputStream(file));
        } catch (IOException e) {
            Log.e("cannot generate pdf", e);
        }
        document.close();
    }
    

提交回复
热议问题