我是Android开发的新手。我使用o nly html,css和jquery创建了一个应用程序。当我们单击按钮时,特定DOM元素应该以pdf格式下载。
要下载 DOM元素为pdf,我已经使用了[[JSPDF。它在chrome中正常工作。同样在android应用中不起作用。
然后经过一些浏览后,我发现JSPDF在Android应用程序中将无法使用
。因此,要下载pdf,我使用了[[@JavascriptInterface和DownloadManager。 当我通过HTTP提供正确的URL时,它可以正常工作,但是如果我从JS发送URL到Java以下载pdf,则它不起作用。要将html页面下载为pdf,我必须进行哪些更改。预先感谢:)
单击按钮时调用Java函数的JS代码
$(".buttonClick").click(function () { $(".mainPage").hide(); $(".bill").show(); var doc = new jsPDF(); doc.addHTML(document.body, function () { var pdfOutput = doc.output("blob"); // window.open(URL.createObjectURL(pdfOutput)); Android.downloadPDF(URL.createObjectURL(pdfOutput)); }); });
Java代码如下:
public class CustomFunctions {
@JavascriptInterface
public void downloadPDF(String url) {
final Context c = HelperClass.getContext();
//WebView mWebView=new WebView(HelperClass.getContext());
WebView mWebView = HelperClass.getWebView();
//String userAgent=new WebView(HelperClass.getContext()).getSettings().getUserAgentString();
//String url = "http://www.africau.edu/images/default/sample.pdf";
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myPDFfile.pdf");
DownloadManager dm = (DownloadManager) c.getSystemService(c.DOWNLOAD_SERVICE);
dm.enqueue(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
限制该库旨在简化Java中wkhtmltopdf的使用,这意味着该库仅限于该工具可以执行的操作,并且还共享该工具可能包含的所有错误。
此库是使用Java 8编写和编译的。如果需要使用较低的Java版本,则可以从源代码进行编译。
将此添加到您的项目中n您的build.gradle文件:
在存储库下添加
maven { url "https://jitpack.io" }
,确保这是最后声明的回购根据依赖性
Add compile 'com.github.todd-elvers:html-to-pdf-converter:2.0.0'
在下面的示例中,我们将生成的PDF写入一个临时目录,然后将其写入某个流,然后try-with-resources块从磁盘中清除PDF
HtmlToPdfFileConverter htmlToPdfFileConverter = new HtmlToPdfFileConverter(); try (PdfFile pdfFile = htmlToPdfFileConverter.tryToConvert(html)) { pdfFile.writeToOutputStream(...); }
如果要避免执行写入临时目录的中间步骤,而是直接写入目标位置,则需要这样做:
HtmlToPdfFileConverter htmlToPdfFileConverter = new HtmlToPdfFileConverter(); File outputFile = ... try { htmlToPdfFileConverter.tryToConvert(html, outputFile); } catch(HtmlToPdfConversionException ex) { ...