All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Convert HTML(CSS) To PDF Using JavaScript

Last Updated : Mar 11, 2024

How To Convert HTML(CSS) To PDF Using JavaScript

In this tutorial we will show you the solution of how to convert HTML(CSS) to pdf using JavaScript, when we execute the html file in webpage that output will converted to pdf with the help of jQuery and jsPDF libraries support.

Both jquery and jsPDF are open-source javascript libraries, jquery designed for simplifies creation, navigation of web application and jsPDF designed for generate pdf documents.

Step By Step Guide On How To Convert HTML(CSS) To Pdf Using JavaScript :-

Here we defined two methods for generate pdf. In script jquery initializing a4 size and html contents width to variable ‘form’. When Generate button clicked by user it calls createPDF() method it loads getCanvas() method.

This method returns translated html contents to pdf by using html2canvas() function it will auto fit the target dom width into PDF size.

In createPDF() function has returned values of canvas. Canvas datas converted to image type by toDataURL().

Then created new pdf it refers ‘doc’ and save it to ‘doc’ object with the name of PDF file is ‘htmlTOpdf’.

Our PDF ready for download so when user clicks the ‘Generate PDF’ button PDF will starts downloading.

<!DOCTYPE html>
<html>
<head>
<title>Converting html to pdf using javascript</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
</head>
<body>
<center>
    <div class="content" style="max-width:none;width: 1005px;">
    <h2>Student Subjectwise Marks</h2>
     <br><br>
        <table border="1">
            <tr>
                <th>NAME</th><th>ENGLISH</th> <th>MATHS</th><th>SCIENCE</th>
            </tr>
            <tr>
                <td>Arun</td><td>68 %</td><td>78 %</td><td>80 %</td>
            </tr>
            <tr>
                <td>Varun</td><td>88 %</td><td>70 %</td><td>97 %</td>
            </tr>
            <tr>
                <td>Kumar</td><td>90 %</td><td>89 %</td><td>80 %</td>
            </tr>
        </table>
        <br>
    </div>
    <input id="create_PDF" type="button" value="Generate PDF"></div>
</center>
    <script>
        var form = $('.content'),cache_width=form.width();
        a4=[595.28,841.89];
        $('#create_PDF').on('click', function () {
            $('body').scrollTop(0);
            createPDF();
        });
        function createPDF(){
            getCanvas().then(function(canvas){
                var img = canvas.toDataURL("image/png"),
                doc=new jsPDF({
                    unit:'px',
                    format:'a4'
                });
                doc.addImage(img,'JPEG',20,20);
                doc.save('htmlTOpdf.pdf');
                form.width(cache_width);
            });
        }
        function getCanvas(){
            form.width((a4[0]*1.33333)-80).css('max-width','none');
            return html2canvas(form,{
                imageTimeout: 2000,
                removeContainer: true
            });
        }
    </script>
</body>
</html>
  1. <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in.
  2. The<html> tag is used to indicate the beginning of HTML document.
  3. As above shown <head> tag is contain information about webpage and if need any external file those links are declared here. <title> tag is used for set the webpage title.
  4. we need JQuery, jsPDF libraries support so their link imported using <script>tag.
  5. Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If your not closed anyone of ending tag properly that is also affect the webpage result.
  6. <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
  7. <center> tag used for align the whole contents into center of webpage. Within <div> tag we created one table of student subjectwise marklist.
  8. For creating table we need to use <table>, <th>, <tr>, <td> these main tags. Each tag has pair of ending tags we need to close respectively.
  9. <table> represent the table.
  10. <th> represent the table head.
  11. <tr> represent the table row.
  12. <td> represent the table column.
  13. In table we used 4 rows, 4 columns with table border width ‘1’. Table contain three students marks in english, maths and science.
  14. <input> tag used as button type for generate pdf files. In pdf generating code we used two values in html document (i.e) <div> class value and input button id value.
  15. In script ‘form’ variable has whole html document width and a4 default size is initialized. On() method attaches event handlers to the currently selected set of elements in the jQuery.
  16. On() method On(‘click’) used to attach the ‘click’ event on $('#create_PDF') this selector. So $('#create_PDF').on('click', function () is begin their work when user click the button with id ‘create_PDF’.
  17. scrollTop(0) refers scrolling top end so $('body').scrollTop(0) this line refers html body top then createPDF() function called it calls getCanvas() function. In getCanvas() function first line code adjust html contents width by using variable ‘form’ to fit into a4 size.
  18. Html2canvas() method return translated html contents into PDF with ‘form’. imageTimeout defines after 2000ms timeout for loading an image.
  19. removeContainer used for cleanup the cloned DOM elements created temporarily by html2canvas. So we set to true for cleaning. Finally results are returned to createPDF() function canvas object.
  20. Canvas data converted to image type by toDataURL() with name ‘img’ and ‘new jsPDF’ creates new blank PDF refered by ‘doc’. PDF unit set to ‘px’(pixel) and format set to ‘a4’.
  21. After creation of blank PDF, addImage(img,'JPEG',20,20) used to sets image of converted html file with size, type and added to blank PDF of ‘doc’. The converted image PDF saved with name of ‘htmlTOpdf’ pdf file.
  22. As we know when using jQuery it will loads from server so we needs to run server before executing code.
  23. Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.

Conclusion :-

I hope this tutorial on how to convert HTML(CSS) to pdf using JavaScript helps you and the steps and method mentioned above are easy to follow and implement.

In conclusion now we are learn using javascript we can convert html to PDF.

Javascript is used by programmers across the world to create dynamic and interactive web content like applications and browsers. It is used as a client-side programming language.

Here using javascript we have seen few concepts and how to handle them.

In jQuery and jsPDF has more concepts we will see how to use them in future.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪