简体   繁体   English

在Android上从Webview保存PDF

[英]Save PDF from Webview on Android

I want to save my webview to a PDF file. 我想将我的webview保存为PDF文件。 I know that I can print the WebView with WebView.createPrintDocumentAdapter() and PrintManager.print(). 我知道我可以使用WebView.createPrintDocumentAdapter()和PrintManager.print()打印WebView。 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. 但我需要一种方法来保存PDF,这是由PrintDocumentAdapter内部生成的,没有任何用户交互,因为我需要该文件在我的应用程序内进一步处理。

Any ideas? 有任何想法吗?

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. 基本上根据问题,您可以使用上面提到的createPrintDocumentAdapter方法并将结果传递给您自己的“假”PrintManager实现,该实现只是覆盖onWrite方法以将输出保存到您自己的文件中。 The snippet below shows how to take any PrintDocumentAdapter and send the output from it to a file. 下面的代码段显示了如何获取任何PrintDocumentAdapter并将其输出发送到文件。

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. 正如您所看到的那样,在适配器方法中传递了相当多的空值,但我检查了Chromium源代码,并且从未使用过这些变量,因此空值正常。

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/ 我在这里创建了一篇关于如何做到这一点的博客文章: http//www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/

Create a custom WebViewClient ( reference ) and set it on your WebView . 创建自定义WebViewClient引用 )并在WebView上设置它。

In this WebViewClient you should override shouldOverrideUrlLoading (WebView view, String url) . 在此WebViewClient您应该覆盖shouldOverrideUrlLoading (WebView view, String url) From here on you can download the PDF manually when it is clicked. 从这里开始,您可以在单击时手动下载PDF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM