Convert HTML to PDF Using Javascript Example Tutorial

Share this Article
Reading Time: 7 minutes
668 Views

Inside this article we will understand i.e Convert HTML to PDF Using Javascript Example Tutorial. We will use Javascript FileReader concept to do this. Article contains classified information about How to use js PDF Library to generate PDF from HTML.

There is no third party plugin involvement to generate a PDF file from HTML. There are very simple steps we need to follow to do this.

This tutorial will guide you completely about generating a PDF from HTML in Javascript. You can use any third party plugin for this but we will do using Core functions (js PDF) of Javascript.

Learn More –

Let’s get started.

Application Programming

Let’s create a folder with name html-pdf in your localhost directory. In this project folder, create two files: index.html and convert.js

So, here it will be like –

Folder Name (html-pdf) –

  • index.html
  • convert.js

Open index.html and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Convert HTML to PDF Using jQuery Example Tutorial</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>

    <div class="container">
        <h3>Convert HTML to PDF Using jQuery Example Tutorial</h3>
        <div class="panel panel-primary">
            <div class="panel-heading">Convert HTML to PDF Using jQuery Example Tutorial</div>
            <div class="panel-body">
                <form name="foo" method="post" class="input-form" enctype="multipart/form-data">
                    <div style="margin-bottom: 25px" class="input-group">
                        <label class="form-label">Upload HTML file: </label>
                        <input type="file" id="fileUpload" name="file" class="form-control" accept=".html,.htm">
                    </div>
                    <div class="preview">
                        <div id="previewHtmlContent"></div>
                    </div>
                    <div style="margin-bottom: 25px" class="input-group">
                        <input type="button" value="Show Preview" class="btn btn-info" id="previewHtml"><span id="error-message" class="error"></span>
                        <input type="button" value="Create PDF" class="btn btn-info hidden" id="convertHtmlToPDF">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.2.1/html2canvas.min.js"></script>
    <script src="convert.js"></script>
</body>

</html>

Above code will provide you the complete interface where you can upload your .html file and convert it into .pdf files.

Now, let’s move towards it’s functional section.

Open convert.js file and add this complete code into it.

// Preview button click event
$(document).on('click', '#previewHtml', function() {
    previewHTMLFile();
});

// Convert HTML to PDF
$(document).on('click', '#convertHtmlToPDF', function() {
    converHTMLToPDF();
});

// Show HTML preview function
function previewHTMLFile() {

    var filePath = $('#fileUpload').get(0).files[0];
    var fileContents;
    $("#error-message").html("");
    $("#fileUpload").css("border", "#a6a6a6 1px solid");
    if ($(filePath).length != 0) {
        var reader = new FileReader();
        reader.onload = function(e) {
            fileContents = e.target.result;
            $(".preview").show();
            $("#previewHtmlContent").html(fileContents);
            $("#previewHtml").addClass('hidden');
            $("#convertHtmlToPDF").removeClass('hidden');
        }
        reader.readAsText(filePath);
    } else {
        $("#error-message").html("required.").show();
        $("#fileUpload").css("border", "#d96557 1px solid");
    }
}

// Function to convert HTML to PDF
function converHTMLToPDF() {
    const { jsPDF } = window.jspdf;
    var pdf = new jsPDF('l', 'mm', [1200, 1210]);
    var pdfjs = document.querySelector('#previewHtmlContent');
    pdf.html(pdfjs, {
        callback: function(pdf) {
            pdf.save("onlinewebtutor.pdf");
        },
        x: 10,
        y: 10
    });
}

Above code is the complete code to handle Preview function before generating HTML to PDF. Also, it handles when you hit to generate to PDF.

Now,

Suppose we have this pdf-format.html file which contains a simple HTML code structure.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>HTML File Format</title>
    <meta charset="utf-8" />
</head>

<body>

    <h3>Hi, Everyone</h3>

    <h4>Welcome To Online Web Tutor</h4>

    <p><b>Buy Premium Courses - Skillshike</b></p>

    <p>
        Provides professionally developed web development courses over PHP, CodeIgniter, CakePHP, Laravel, Node js, Express js, MySQL, RESTful APIs, Authentication, etc. Master the Coding Skills to Become an Expert in Web Development. A lifetime of knowledge
        at your fingertips.
    </p>

</body>

</html>

Application Testing

Open your browser.

Next,

Your project URL will be like this.

URL: http://localhost/html-pdf/index.html

It gives the interface where you can upload your HTML file which needs to be converted into PDF file.

Once you select your .html file, click on Show Preview button.

You can see, it has generated the Preview of your HTML file.

Now,

To generate PDF of it, click on Create PDF button. Then, it downloads a file with name onlinewebtutor.pdf into your system.

If you open it, you will see something like this.

We hope this article helped you to learn Convert HTML to PDF Using Javascript Example Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Get PHP Web Development Courses on Offer in just ₹299
Get PHP Web Development Courses on Offer in just ₹299