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

Muh*_*aat 3 javascript pdf phantomjs

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
};
Run Code Online (Sandbox Code Playgroud)

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.

ser*_*zzo 5

我需要将 div 发送到 PDF,我使用此代码并且对我来说工作正常。(需要 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
        }
    });

}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)