简体   繁体   English

有没有办法打印出网页的特定div为pdf?

[英]Is there a way to print out a specific div of a webpage as pdf?

I want to be able to print out a specific div as a PDF and JPG. 我希望能够打印出特定的div作为PDF和JPG。 I used the following code while running phantomjs: 我在运行phantomjs时使用了以下代码:

var bb = page.evaluate(function() {
  return document.getElementsByTagName("fieldset")[7].getBoundingClientRect();
});

page.clipRect = {
  top: bb.top,
  left: bb.left,
  width: bb.width,
  height: bb.height
};

This works fine for PNG but for PDF it just prints the whole page. 这适用于PNG,但对于PDF,它只打印整个页面。 Does anyone know why this is happening and how to solve it? 有谁知道为什么会这样,以及如何解决它? If someone know of any other way to solve this, even something not involving phantomjs or some fronted solution, I'll be highly obliged if they share. 如果有人知道解决这个问题的任何其他方法,即使是不涉及幻影或某些前端解决方案的事情,如果他们分享,我将非常感激。

Edit I'm looking for a workaround to this problem, any frontend or backend solutions are acceptable.However some of the previous questions regarding this topic provide suggestions that involve html2canvas or jsPdf but those have problems with resolution so any other answers solutions will be appreciated. 编辑我正在寻找解决这个问题的方法,任何前端或后端解决方案都是可以接受的。但是之前关于这个主题的一些问题提供了涉及html2canvas或jsPdf的建议,但那些解决方案有问题,所以任何其他答案解决方案将不胜感激。

I needeed to send div to PDF, I use this code and work fine for me. 我需要将div发送到PDF,我使用此代码并为我工作正常。 (need JQuery). (需要JQuery)。

  function testPdf(){ //send the div to PDF html2canvas($("#DIV_ID_HERE"), { // DIV ID HERE onrendered: function(canvas) { var imgData = canvas.toDataURL('image/png'); var doc = new jsPDF('landscape'); doc.addImage(imgData, 'PDF', 10, 10); doc.save('sample-file.pdf'); //SAVE PDF FILE } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.debug.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script> <div id="DIV_ID_HERE"> Test - This div to pdf <br><input type="button" value="print" onclick="testPdf();"> <div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM