[英]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.