Reputation: 400
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?
Upvotes: 7
Views: 9505
Reputation: 306
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/
Upvotes: 6
Reputation: 5604
Create a custom WebViewClient
(reference) and set it on your WebView
.
In this WebViewClient
you should override shouldOverrideUrlLoading (WebView view, String url)
. From here on you can download the PDF manually when it is clicked.
Upvotes: -1