Convert HTML Table to PDF using JavaScript without a Plug-in

I only use a plug-in in my applications only when I don’t find easy methods to do things. No doubt, a Plug-in offer features that will help customize your apps. You can find many plug-in that would convert your HTML table to a PDF document. However, here I’ll show you how it can be done without a plug-in, that is, convert an entire HTML table to a PDF document, along with the table style, using plain JavaScript.

Convert HTML Table to PDF using plain JavaScript

You can use JavaScript window object to accomplish this task. It is very simple. Let’s see the example.

The Markup and the Script
    <title>Convert Table to PDF using JavaScript</title>
            width: 300px;
            font: 17px Calibri;
        table, th, td 
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
    <div id="tab">

        <input type="button" value="Create PDF" 
            id="btPrint" onclick="createPDF()" />
    function createPDF() {
        var sTable = document.getElementById('tab').innerHTML;

        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        var win ='', '', 'height=700,width=700');

        win.document.write('<title>Profile</title>');   // <title> FOR PDF HEADER.
        win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.
        win.document.write(sTable);         // THE TABLE CONTENTS INSIDE THE BODY TAG.

        win.document.close(); 	// CLOSE THE CURRENT WINDOW.

        win.print();    // PRINT THE CONTENTS.
Try it

All browsers support the window object. Now, this is good. I am expecting the above methods to work flawlessly in any browser.

First, I am extracting the contents from the HTML table. I have defined the style; it’s the same as the CSS style in the markup section.

Do you know: you can easily print a PDF document directly from your web page using JavaScript? Here’s the method.

Next, I am creating a window’s object. The open() method will open a new window. I am creating a HTML page in the new window and adding the style and table contents to the window. Once the page is created, I’ll close the window and print the contents of the window as it is.

Save the file as PDF. That’s it.

Also Read: How to open multiple Browser Windows using JavaScript "" Method

Thanks for reading.

← PreviousNext →

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: