Save PDF from Webview on Android

I want to save my webview as a PDF file. I know that I can print the WebView using WebView.createPrintDocumentAdapter () and PrintManager.print (). But I need a way to save the PDF that is generated inside the PrintDocumentAdapter directly, without any user interaction, because I need the file to be processed further inside my application.

Any ideas?

+3


source to share


2 answers


I realize this question is pretty old. But I just figured out how this can be done intelligently.

Basically, you can use the above method createPrintDocumentAdapter

and pass the result to your own "fake" PrintManager implementation, which simply overrides the onWrite method to save the output to its own file. The snippet below shows how to take any PrintDocumentAdapter

and send it from file to file.

public void print(PrintDocumentAdapter printAdapter, final File path, final String fileName) {
    printAdapter.onLayout(null, printAttributes, null, new PrintDocumentAdapter.LayoutResultCallback() {
        @Override
        public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
            printAdapter.onWrite(null, getOutputFile(path, fileName), new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {
                @Override
                public void onWriteFinished(PageRange[] pages) {
                    super.onWriteFinished(pages);
                }
            });
        }
    }, null);
}

      



As you can see, there are a lot of zeros in the adapter methods, but I checked the Chromium source code and these variables are never used, so zeros are fine.

I created a blog post on how to do this here: http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/

0


source


Create a custom WebViewClient

( reference ) and set it to WebView

.



In this WebViewClient

you have to override shouldOverrideUrlLoading (WebView view, String url)

. Here you can download the PDF manually on click.

0


source







All Articles