简体   繁体   中英

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. I used the following code while running 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. 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.

I needeed to send div to PDF, I use this code and work fine for me. (need 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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