App Web Tutorials
  • Home
  • Contact
  • Privacy Policy
Reading: How to Instantly Convert HTML to PDF: A Foolproof JavaScript Guide for Beginners
Share
Subscribe Now
App Web TutorialsApp Web Tutorials
Font ResizerAa
Search
  • Home
  • Contact
  • Privacy Policy
Follow US
Copyright © 2017-2025 App Web Tutorials. All Rights Reserved.
ConvertGenerate PDFHTML to PDFJavaScriptTutorial

How to Instantly Convert HTML to PDF: A Foolproof JavaScript Guide for Beginners

Chetan
By Chetan
Last updated: January 15, 2025
3 Min Read
Step by Step Tutorial to Convert HTML to PDF using JavaScript
Step by Step Tutorial to Convert HTML to PDF using JavaScript
SHARE
Converting HTML to PDF using JavaScript is a straightforward process. In this tutorial, we will go over the steps required to generate a PDF file from an HTML webpage using JavaScript.We will use the jspdf library to generate the PDF.

1. First, let’s create a sample HTML page which we want to convert to PDF. We will add a button to generate the PDF in this page. You can copy and paste the following code and save it as an HTML file in your system.

<span style="color: #f8f8f2; font-family: Consolas, Monaco, andale mono, ubuntu mono, monospace;"><!DOCTYPE html>
<html>
<head>
<title>Step by Step Tutorial to Convert 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="Create 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></span>
 

Now comes the explaination part. You can skip this steps if you already knows what we did in the first step. Cheers!! 

2. Next, we define a function called createPDF() that will be called when the “Create PDF” button is clicked. This function will use the getCanvas() function to create a canvas element that will be converted to a PDF using the jsPDF() library.

3. Inside the createPDF() function, we call the getCanvas() function and pass a callback function that will receive the canvas element.In the callback function, we create a new instance of jsPDF() with default settings. Then, we use the addImage() method to add the canvas as an image to the PDF.

4. After adding the image, we call the save() method of the jsPDF() instance to download the PDF file.

Finally, we call the $(‘body’).scrollTop(0); function to scroll to the top of the page before the PDF is generated.Save the HTML file. Click on the “Create PDF” button to get the final output.

That’s it! You have a working example of how to convert HTML to PDF using JavaScript and the jsPDF() library. You can modify the HTML code and add more styles to customize the PDF  as per the requirement.

For more updates on web development tutorials, you can subscribe to our newsletters.

 

 

 

 

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Laravel .htaccess www, non-www,http and non-https redirection Master Laravel: The Ultimate Guide to .htaccess Redirects for WWW, Non-WWW, HTTP, and HTTPS
Next Article Step-by-step tutorial on how to handle a 404 error and display a custom error page in Laravel Step-by-step tutorial on how to handle a 404 error and display a custom error page in Laravel
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

FacebookLike
XFollow
InstagramFollow
Most Popular
How to Install and Use pyenv on Windows, Ubuntu, and macOS: A Complete Guide
The Ultimate Guide to Installing pyenv on Windows, Ubuntu, and macOS
January 21, 2025
How to Host a Python Flask App with SSL on WAMP Server in Windows: A Step-by-Step Guide for Beginners
January 21, 2025
Fixing SSH ‘Unprotected Private Key File’ Error in Windows 11: A Quick Guide
Easily Fix the SSH ‘Unprotected Private Key File’ Error on Windows 11 in Minutes
January 20, 2025
How to Add Eye-Catching Animations to Your HTML Website: A Step-by-Step Guide for Beginners
Power Your HTML Website with Stunning Animations: Easy Guide for Beginners
January 15, 2025
Master Git with Ease: The Ultimate Cheatsheet Every Developer Needs
Master Git with Ease: The Ultimate Cheatsheet Every Developer Needs
January 21, 2025

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!
App Web Tutorials

We provide tutorials, tips, tricks, and advice for improving programming and development skills.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?