Show Pdf Generated From Html Page In Bootstrap Modal Without Downloading
Is there any way to generate a PDF file from HTML page/content and the PDF should be shown in bootstrap modal without downloading directly. I tried using jsPDF, but couldn't do as
Solution 1:
I reckon I have found a solution to your problem. Basically it takes a screenshot of your page with html2canvas
then it adds that image to to new jsPDF('p', 'pt', 'letter');
. Then it creates a bloburl
from the canvas to display it in an html <object data="bloburl">
in your modal. I have also added another function that makes it possible to download the pdf as well.
The relevant javascript:
//This will be the pdf objectlet pdfFinal = nullfunctiondownloadPDF() {
pdfFinal.save("file.pdf");
}
functionshowPDF() {
//Create screenshot of bodyhtml2canvas(document.body, {scale: 2,scrollY: -window.scrollY}).then(canvas => {
document.body.appendChild(canvas);
var imgData = canvas.toDataURL('image/png');
//add the image to pdfvar pdf = newjsPDF('L', 'pt', [canvas.width, canvas.height]);
pdf.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
//set the pdfFinal to be later downloaded
pdfFinal = pdf;
//Get and set the output of the pdflet output = pdf.output('bloburl');
document.getElementById("pdfObj").height = canvas.height / 4;
document.getElementById("pdfObj").data = output;
});
}
This code would have to be included in you <head>
:
<metacharset="utf-8"><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script><scriptsrc="https://html2canvas.hertzen.com/dist/html2canvas.js"></script><scriptsrc="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
This modal code from (for simplicities sake) w3schools:
<divclass="container"><buttontype="button"onclick="showPDF();"class="btn btn-info btn-lg"data-toggle="modal"data-target="#myModal">Open Modal</button><divclass="modal fade"id="myModal"role="dialog"><divclass="modal-dialog"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal">×</button><h4class="modal-title">Modal Header</h4></div><divclass="modal-body"><p>Here is your pdf.</p></div><center><objectid="pdfObj"data=""type="application/pdf"width="90%"height="550"></object></center><divclass="modal-footer"><buttontype="button"class="btn btn-info"onclick="downloadPDF();">Download</button><buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button></div></div></div></div></div>
Hope this helps! If not please comment
Edit
Now the entire page fits on the pdf. Changes: Added scaling for higher resolution
Post a Comment for "Show Pdf Generated From Html Page In Bootstrap Modal Without Downloading"