How to generate PDF from div content

jquery code to generate pdf from div with automatic height and width –

<button id=”generatePDFbtn”>Generate PDF</div>
<div id=”content”>hello</div>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js”></script>
<script>
$(document).on(“click”, “#generatePDFbtn”, function() {
        html2canvas(document.getElementById(“content”)).then(function(canvas) {
            var imgData = canvas.toDataURL(“image/jpeg”, 1.0);
            var pdf = new jsPDF(‘p’, ‘mm’, [400, 480]);
            pdf.addImage(imgData, ‘JPEG’, 0, 0, 400, 480);
            pdf.save(“search-result.pdf”);
        });
    });
</script>

JQuery / Javascript Interview Questions

Ques: What is difference between setInterval () and setTimeout () ?

Ans: setInterval(expression, time) – It will run the code or function in the time interval.
Example –
setInterval(function(){ alert(“Hello”); }, 1000);
This will alert “Hello” after every 1 second(1000 milliseconds).

setTimeout() – It will run after the time.
Example –
setTimeout(function(){ alert(“Hello”); }, 1000);
This will alert “Hello” once only after 1 second(1000 milliseconds).

Ques: When will be the fourth argument to open() function ?

Ans: When the second argument named as existing window.

Append or insert an element(div) after another element(div)

Insert an element (div) after another element(div) –
JQuery .after() and .insertAfter() functions can be used to append or insert an after other element.
Both performs the same task. The only difference between them is syntax.

In .after(), the first selector is that element after which other element will be inserted while in .insertAfter(), the second selector is that after which the element will be appended(inserted).

Let us take an example we have to insert an element after a paragraph tag –
So, it can be done in 2 ways –
<p>This is dummy text.</p>

With .after() –
$(“p”).after(“<p>The above is dummy text.</p>”);

With .insertAfter() –
$(” <p>The above is dummy text.</p>”). insertAfter (“p”);

Both of the above will insert new paragraph( The above is dummy text. ) after above paragraph( This is dummy text. ).

Read contents from input type file

Read input type file contents –
File content can be read using FileReader function of javascript. Here is an example for explanation –

Create HTML (input field and a div where we have to show the content of file) –

<input type=”file” name=”inputfile” onchange=”readinputfile()”>
<div class=”showfilecontent”></div>

Now call JS function –

const reader = new FileReader()
function readinputfile (input) {
const input = input.files[0]
reader.readAsText(input)
}
reader.onload = function (e) {
document.querySelector(‘. showfilecontent ‘).innerText = e.target.result;
}