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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:18:18  来源:igfitidea点击:

How to convert HTML page to PDF then download it?

javascriptjquerycsshtmlpdf-generation

提问by ajay

This is my web page designed with HTML and CSS:

这是我用 HTML 和 CSS 设计的网页:

How can I download the same web page as PDF? I was trying many solutions but I am getting only content on PDF file but not with CSS style.

如何下载与 PDF 相同的网页?我尝试了很多解决方案,但我只获得了 PDF 文件的内容,而不是 CSS 样式。

Any solutions?

任何解决方案?

回答by Ivan

As explained in this postyou can use the jsPDFlibrary to do that.

正如这篇文章中所解释的,您可以使用jsPDF库来做到这一点。

Make sure to include both jQueryand jsPDFin your file.

确保包括jQueryjsPDF你的文件。

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

  1. Download the latest version of jsPDF.

  2. 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
  1. 下载最新版本的jsPDF

  2. 在您的项目中包含以下脚本:

    • jspdf.js
    • jspdf.plugin.from_html.js
    • jspdf.plugin.split_text_to_size.js
    • jspdf.plugin.standard_fonts_metrics.js