Javascript 如何将 HTML 页面转换为 PDF 然后下载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46012054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert HTML page to PDF then download it?
提问by ajay
回答by Ivan
As explained in this postyou can use the jsPDFlibrary to do that.
正如这篇文章中所解释的,您可以使用jsPDF库来做到这一点。
Make sure to include both jQueryand jsPDFin your file.
Also get html2canvasJSto convert the document elements to canvas in order to fix the CSS.
还可以使用html2canvasJS将文档元素转换为画布以修复 CSS。
JS:
JS:
let doc = new jsPDF('p','pt','a4');
doc.addHTML(document.body,function() {
doc.save('html.pdf');
});
HTML:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<div id="content">
<h1 style="color:red">Hello World</h1>
<p>this is a PDF</p>
</div>
Demo:JSFiddle
演示:JSFiddle
You can also trigger the download with a button (see initial post for details)
您还可以使用按钮触发下载(有关详细信息,请参阅初始帖子)
回答by Kirit
Download the latest version of jsPDF.
Include the following Scripts in your project:
- jspdf.js
- jspdf.plugin.from_html.js
- jspdf.plugin.split_text_to_size.js
- jspdf.plugin.standard_fonts_metrics.js
下载最新版本的jsPDF。
在您的项目中包含以下脚本:
- jspdf.js
- jspdf.plugin.from_html.js
- jspdf.plugin.split_text_to_size.js
- jspdf.plugin.standard_fonts_metrics.js


