使用JavaScript将html导出为PDF [英] Export html to PDF with JavaScript

查看:122
本文介绍了使用JavaScript将html导出为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JavaScript将HTML导出为PDF,我看到像 jsPDF pdfMake ,但它们非常有限。例如,没有它们我可以导出HTML元素,如< hr> ,使用jsPDF样式非常有限,我看到这个问题,但答案是不能为我工作,pdfMake我无法下载pdf,只需使用 chrome

I want to export HTML to PDF with JavaScript, I saw libraries like jsPDF and pdfMake, but they are very limited. For example, with none of them I can export HTML elements, like <hr>, with jsPDF the styling is very limited, I saw this question but the answer is not working for me, with pdfMake I cannot download the pdf, just with chrome.

推荐答案

如果您可以从URL检索HTML,则可能需要检查我写的这个答案解释了如何做到这一点。

If you can retrieve the HTML from an URL you may want to check this answer that I wrote that explains how to do it.

示例:

https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=show

将锚点放入您的HTML显示PDF或将其下载到您的HTML中。

It's so easy to put an anchor in your HTML that shows the PDF or downloads it in your HTML.

此锚点将显示从 https://www.github.com page:

This anchor will show the PDF converted from the https://www.github.com page:

<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=show" target="_blank">Show PDF</a>

这个会下载它:

<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download&file_name=my_pdf">Download PDF</a>

如果你想用JavaScript试试,你可以创建一个HTML按钮,然后点击事件下载PDF。示例:

If you want to try it with JavaScript, you could create an HTML button and on click event download the PDF. Example:

HTML:

<button type="button" id="download-pdf-button">Download the PDF</button>

JavaScript:

JavaScript:

document.getElementById("download-pdf-button").addEventListener("click", function() {
    var link = document.createElement('a');
    link.href = 'https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download';
    link.download = 'file.pdf';
    link.dispatchEvent(new MouseEvent('click'));
});

查看Github的项目

希望有所帮助。

这篇关于使用JavaScript将html导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆