Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save PDF from Webview on Android

I want to save my webview to a PDF file. I know that I can print the WebView with WebView.createPrintDocumentAdapter() and PrintManager.print(). But I need a way to save the PDF, that is generated internally by the PrintDocumentAdapter, directly without any user interactions, because I need the file for further processing inside my app.

Any ideas?

like image 279
Andreas Avatar asked Oct 20 '22 22:10

Andreas


1 Answers

I realise this question is quite old now. But I have just realised how this can be sensibly done.

Essentially as per the question you can use the createPrintDocumentAdapter method mentioned above and pass the result to your own "fake" PrintManager implementation which simply overrides the onWrite method to save the output to your own file. The snippet below shows how to take any PrintDocumentAdapter and send the output from it to a 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's quite a few nulls passed into the adapters methods but I have checked the Chromium source code and these variables are never used so the nulls are ok.

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

like image 121
Brett Cherrington Avatar answered Oct 27 '22 23:10

Brett Cherrington