Print the specific element and save it as a PDF
We are going to generate a window and save this as a pdf during runtime. This is similar to the default printing features of the system. The steps are discussed below.
- Create a new window using the ‘window. open‘ method.
- Write the innerHTML for our <div> tag, inside that window.
- Print the window
- Close the window
Example: In this example, we will use the html2pdf CDN link that will help to generate the pdf file.
HTML
<!DOCTYPE html> < html lang = "en" > < head > <!-- html2pdf CDN--> < script src = "https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js" > </ script > < style > .container { position: fixed; top: 20%; left: 28%; margin-top: -65px; margin-left: -100px; border-radius: 7px; } .card { box-sizing: content-box; width: 700px; height: 150px; padding: 30px; border: 1px solid black; font-style: sans-serif; background-color: #f0f0f0; } #button { background-color: #4caf50; border-radius: 5px; margin-left: 650px; margin-bottom: 5px; color: white; } h2 { text-align: center; color: #24650b; } </ style > </ head > < body > < div class = "container" > < button id = "button" >Generate PDF</ button > < div class = "card" id = "makepdf" > < h2 >Welcome to w3wiki</ h2 > < ul > < li > < h4 > We are going to generate a pdf from the area inside the box </ h4 > </ li > < li > < h4 > This is an example of generating pdf from HTML during runtime </ h4 > </ li > </ ul > </ div > </ div > </ body > < script > let button = document.getElementById("button"); let makepdf = document.getElementById("makepdf"); button.addEventListener("click", function () { let mywindow = window.open("", "PRINT", "height=400,width=600"); mywindow.document.write(makepdf.innerHTML); mywindow.document.close(); mywindow.focus(); mywindow.print(); mywindow.close(); return true; }); </ script > </ html > |
Output:
How to design runtime generated PDF via HTML ?
Many times, we have faced the problem of saving a particular webpage or any online specific element that needs to save in the form of a PDF file while using the browser. In that case, either we have used the 3rd party extension or any app or tools to generate it into a PDF file. In this article, we will learn to design the runtime-generated pdf file via HTML.
Let’s understand all the 3 concepts one by one with the help of examples.
Table of Content
- Print the specific element and save it as a PDF
- Using jsPDF library
- Using html2pdf library