I have been building a polling application. People are able to create their polls and get data regarding the question(s) they ask. I would like to add the functionality to l
This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.
As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left,
this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}
.
This method wraps the prerequisites in a promise and calls pdf.save()
in the finally()
method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.
// Get List of paged elements.
let elems = document.querySelectorAll('.elemClass');
let pdf = new jsPDF("portrait", "mm", "a4");
// Fix Graphics Output by scaling PDF and html2canvas output to 2
pdf.scaleFactor = 2;
// Create a new promise with the loop body
let addPages = new Promise((resolve,reject)=>{
elems.forEach((elem, idx) => {
// Scaling fix set scale to 2
html2canvas(elem, {scale: "2"})
.then(canvas =>{
if(idx < elems.length - 1){
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);
pdf.addPage();
} else {
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);
console.log("Reached last page, completing");
}
})
setTimeout(resolve, 100, "Timeout adding page #" + idx);
})
addPages.finally(()=>{
console.log("Saving PDF");
pdf.save();
});
npm install jspdf --save
//code on react
import jsPDF from 'jspdf';
var doc = new jsPDF()
doc.fromHTML("<div>JOmin</div>", 1, 1)
onclick //
doc.save("name.pdf")