[英]how to download HTML page as pdf in Android?
我是 Android 开发的新手。 我只使用html、css 和 jquery创建了一个应用程序。 当我们点击一个按钮时,一个特定的 DOM 元素应该下载为 pdf。
要以pdf 格式下载DOM 元素,我使用了JSPDF 。 它在 chrome 中正常工作。 同样在android应用程序中不起作用。
然后经过一些浏览,我发现 JSPDF在 android app 中不起作用。 所以要下载 pdf,我使用了@JavascriptInterface和DownloadManager 。
当我使用 HTTP 提供正确的 url 时,它可以正常工作,但是如果我将 URL 从 JS 发送到 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();
}
}
}
该库使用 wkhtmltopdf、Apache Exec 和同步的二进制文件,以实现强大的、线程安全的 HTML 到 PDF 转换过程。
它包括适用于 Windows、Mac 和 Linux 的二进制文件,并将根据当前操作系统决定使用哪个。 您可以选择通过设置 WKHTMLTOPDF_BINARY 环境变量来提供您自己的 wkhtmltopdf 二进制文件。
限制 该库旨在简化 wkhtmltopdf 在 Java 中的使用,这意味着该库仅限于该工具可以执行的操作,并且还共享该工具可能包含的任何错误。
这个库是用 Java 8 编写和编译的。如果您需要针对较低的 Java 版本,请从源代码编译。
将此添加到您的项目和 build.gradle 文件中:
在存储库下添加
maven { url "https://jitpack.io" }
,确保它是在依赖项下声明的最后一个 repo
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) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.