To Convert URL to PDF And Print Using JavaScript, we can use hidden <iframe>
.
Here we do a complete code example, where we will see how we can print an external URL as a PDF without opening it on the same page.
In web development sometimes we have to show some pages as PDF or download HTML pages as PDF via URL using JS.
This is the important concept of the conversion of URL to PDF by using JavaScript.
Here is the complete source code to Convert External URL to PDF And Print Using JavaScript,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<script type="text/javascript"> function closePrint () { document.body.removeChild(this.__container__); } function setPrint () { this.contentWindow.__container__ = this; this.contentWindow.onbeforeunload = closePrint; this.contentWindow.onafterprint = closePrint; // Required for IE this.contentWindow.focus(); this.contentWindow.print(); } function printPage(sURL) { var oHideFrame = document.createElement("iframe"); oHideFrame.onload = setPrint; oHideFrame.style.position = "fixed"; oHideFrame.style.right = "0"; oHideFrame.style.bottom = "0"; oHideFrame.style.width = "0"; oHideFrame.style.height = "0"; oHideFrame.style.border = "0"; oHideFrame.src = sURL; document.body.appendChild(oHideFrame); } </script> <p> <span onclick="printPage('https://YOUR_URL.COM/');">Print external page!</span> </p> |
Code Highlights:
- Here we create 3 functions, the first is for print window close operation, and the second is for events work on the print window
- And the last function (printPage(sURL)) is for creating a hidden iframe which is used to print or we can save it as a PDF.
- On
printPage(sURL)
the function we can define the style of the print PDF file. - By using the same function we can manage the height, width, border, and alignment of the generated PDF for print.
- At last, we created a span (you can choose the button) where we call onclick() function to call the print function with URL as an argument.
How to Use
Copy the complete source code and paste it into your project.
Use onclick function to call the complete print PDF function with a button or text click.
Note:
Sometimes you get the CORS error which occurs because of different domains, so you have to first set the CORS permission on the URL that you want to print.
It is also helpful when you want to print a PDF file using JavaScript without opening it and print directly to the default printer.
I hope you get a complete understanding of the code.
Please let me know if you are facing any issues with the implementation.
Happy Coding..!