jQuery 将 Div 转换为包含图像的 PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42427507/
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-26 17:18:16  来源:igfitidea点击:

Converting Div into PDF INCLUDING images

jquery

提问by Deedub

am referencing this post Download a div in a HTML page as pdf using javascript

我正在引用这篇文章 Download a div in a HTML page as pdf using javascript

which basically uses jspdf to make a div into a pdf. I got it to work, but the only problem is I can't get it to add an image as well that would be contained in the div. In other words, I can get the text that's in the div to be a pdf but not the image inside.

它基本上使用 jspdf 将 div 转换为 pdf。我让它工作了,但唯一的问题是我无法让它添加一个包含在 div 中的图像。换句话说,我可以让 div 中的文本成为 pdf 而不是里面的图像。

回答by Tony

One solution is to use the html2canvasor rasterizeHTMLlibrary. They create a canvas of the HTML page which you can then add to the PDF using addHTML

一种解决方案是使用html2canvasorrasterizeHTML库。他们创建 HTML 页面的画布,然后您可以使用它添加到 PDFaddHTML

$('#cmd').click(function() {
  var options = {};
  var pdf = new jsPDF('p', 'pt', 'a4');
  pdf.addHTML($("#content"), 15, 15, options, function() {
    pdf.save('pageContent.pdf');
  });
});

Demo

演示

回答by Mohit Kulkarni

This code may help(It worked for me):

此代码可能有帮助(它对我有用):

<script type="text/javascript">
 $(document).ready(function () {
  setTimeout(function(){
   downloadImage();
  },1000)
 });
 
 function downloadImage(){
  html2canvas(document.querySelector("#divID")).then(canvas => {
  a = document.createElement('a'); 
  document.body.appendChild(a); 
  a.download = "test.png"; 
  a.href =  canvas.toDataURL();
  a.click();
 });
 }  
 </script>