我希望将我的WebView保存为PDF文件。我知道可以使用WebView.createPrintDocumentAdapter()和PrintManager.print()打印WebView。但是,我需要一种直接保存由PrintDocumentAdapter内部生成的PDF文件的方法,而无需任何用户交互,因为我需要该文件在我的应用程序内进行进一步处理。
有什么想法吗?
有什么想法吗?
我知道这个问题现在已经很老了。但是我刚刚意识到如何合理地完成这项工作。
基本上,您可以使用上面提到的createPrintDocumentAdapter
方法,并将结果传递给您自己的“伪”PrintManager实现,该实现简单地覆盖onWrite方法以将输出保存到您自己的文件中。下面的代码片段展示了如何获取任何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);
}
如您所见,有很多空值传递到适配器方法中,但我已经检查了Chromium源代码,这些变量从未被使用,因此空值是可以的。
我在这里创建了一篇博客文章,介绍了如何实现: http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
WebViewClient
(reference),并将其设置在你的WebView
上。WebViewClient
中,你应该重写shouldOverrideUrlLoading(WebView view, String url)
方法。从这里开始,当PDF被点击时,你可以手动下载它。
android.print
包中的一个类中,因为它使用了包级别的受保护方法/类。 - Brett Cherrington