The Wayback Machine - https://web.archive.org/web/20241118101827/https://www.geeksforgeeks.org/how-to-download-pdf-file-on-button-click-using-javascript/
Open In App

How to Download PDF File on Button Click using JavaScript ?

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes, a web page may contain PDF files that can be downloaded by the users for further use. Allowing users to download the PDF files can be accomplished using JavaScript. The below methods can be used to accomplish this task.

Using html2pdf.js library

  • First, create your basic HTML structures with some good style and add some content to the page.
  • Now, include the html2pdf library using the CDN link.
  • After that handle the event listener of the button on click to generate the pdf.
  • Here we used the save() method of html2pdf library which is used to save the generated PDF file to the user's device.

Example: The below example shows the implementation of the above-explained approach.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Download PDF on Button Click</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1>
        How to Download PDF File on Button
        Click using JavaScript
    </h1>
    <p>
        You can add your content here...
    </p>
    <div id="content">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Employee 1</td>
                    <td>30</td>
                    <td>USA</td>
                </tr>
                <tr>
                    <td>Employee 2</td>
                    <td>25</td>
                    <td>Canada</td>
                </tr>
                <tr>
                    <td>Employee 3</td>
                    <td>21</td>
                    <td>Canada</td>
                </tr>
                <tr>
                    <td>Employee 4</td>
                    <td>22</td>
                    <td>India</td>
                </tr>
            </tbody>
        </table>
    </div>
    <button id="download_Btn">
        Download Table Data
    </button>

    <!-- Include html2pdf library -->
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js">
    </script>

    <script>
        const download_button =
            document.getElementById('download_Btn');
        const content =
            document.getElementById('content');

        download_button.addEventListener
            ('click', async function () {
                const filename = 'table_data.pdf';

                try {
                    const opt = {
                        margin: 1,
                        filename: filename,
                        image: { type: 'jpeg', quality: 0.98 },
                        html2canvas: { scale: 2 },
                        jsPDF: {
                            unit: 'in', format: 'letter',
                            orientation: 'portrait'
                        }
                    };
                    await html2pdf().set(opt).
                        from(content).save();
                } catch (error) {
                    console.error('Error:', error.message);
                }
            });
    </script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    background: #21f536;
}

#content {
    max-width: 800px;
    margin: 0 auto;
}

h1 {
    color: #fff;
    font-size: 28px;
    margin-bottom: 20px;
    margin-left: 20rem;
}

p {
    color: #fff;
    font-size: 16px;
    line-height: 1.5;
    margin-left: 20rem;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

th,
td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
    cursor: pointer;
}

th {
    background-color: #f2f2f2;
}

tr:nth-child(even) {
    background-color: #f9f9f9;
}

tr:nth-child(odd) {
    background-color: #ffffff;
}

tr:hover {
    background-color: #f5f5f5;
}

td:hover {
    background-color: #f0f0f0;
}

button {
    background-color: #007bff;
    color: #fff;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    margin-left: 19rem;
}

button:hover {
    background-color: #0056b3;
}

Output:

pdf1
Output

Using pdfmake Library

  • Create the basic HTML structures with some good style and add some content in this page.
  • Include the pdfmake library using the CDN link inside the head tag.
  • After that select the table element from the HTML document. Then define the document definition for pdfmake.
  • You can set the width of the first column of the table to 50% within the docDefinition.Then trigger the download of the PDF file.

Example: The below example shows the implementation of the above-explained approach.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Table to PDF</title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/pdfmake.min.js">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/vfs_fonts.js">
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }

        h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 20px;
        }

        p {
            color: #666;
            font-size: 16px;
            margin-bottom: 20px;
        }

        table {
            border-collapse: collapse;
            width: 100%;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>

    <h1>
        How to Download PDF File on
        Button Click using JavaScript
    </h1>
    <p>
        You can add your content here...
    </p>

    <table id="my-table" border="1">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>John Doe</td>
                <td>30</td>
                <td>New York</td>
            </tr>
            <tr>
                <td>Jane Smith</td>
                <td>25</td>
                <td>Los Angeles</td>
            </tr>
            <tr>
                <td>Bob Johnson</td>
                <td>40</td>
                <td>Chicago</td>
            </tr>
        </tbody>
    </table>

    <button id="download-btn">
        Download PDF
    </button>

    <script>
        let download_button = document.
            getElementById("download-btn");
        let table =
            document.getElementById("my-table");

        download_button.addEventListener
            ("click", function () {
                const tableData = [];
                const rows = table.rows;
                for (let i = 0; i < rows.length; i++) {
                    const rowData = [];
                    const cells = rows[i].cells;
                    for (let j = 0; j < cells.length; j++) {
                        rowData.push(cells[j].innerText);
                    }
                    tableData.push(rowData);
                }

                const docDefinition = {
                    content: [
                        {
                            text: 'This is Your Employee Details',
                            style: 'header'
                        },
                        {
                            table: {
                                widths: ['50%', '*', '*'],
                                body: tableData
                            }
                        }
                    ],
                    styles: {
                        header: {
                            fontSize: 18,
                            bold: true,
                            margin: [0, 0, 0, 10]
                        }
                    }
                };

                pdfMake.createPdf(docDefinition).
                    download('table.pdf');
            });
    </script>

</body>

</html>

Output:

pdf-v2
Output : Using pdfmake Library

Using window.print() method

  • First, create a basic HTML structures with some good style and add some content in this page.
  • Use the event listener function, call window.print() to open the print dialog and you can choose to print or save the page as a PDF..

Example: The below example shows the implementation of the above-explained approach.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Download Table as PDF
    </title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f7f7f7;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        #downloadBtn {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }

        #downloadBtn:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <div class="container">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>John Doe</td>
                    <td>30</td>
                    <td>USA</td>
                </tr>
                <tr>
                    <td>Jane Smith</td>
                    <td>25</td>
                    <td>UK</td>
                </tr>
                <tr>
                    <td>Alice Johnson</td>
                    <td>35</td>
                    <td>Canada</td>
                </tr>
            </tbody>
        </table>

        <button id="downloadBtn">
            Download PDF
        </button>
    </div>

    <script>
        document.getElementById('downloadBtn').
            addEventListener('click', function () {
                window.print();
            });
    </script>

</body>

</html>

Output:

fosiGIF


Similar Reads

How to Download Image on Button Click in JavaScript?
Downloading an image on a button click in JavaScript involves creating a mechanism to trigger the download action when a user clicks a button. Below are the approaches to download image on button click in JavaScript: Table of Content Using Anchor Tag with Download AttributeUsing Fetch APIUsing Anchor Tag with Download AttributeThe "download" attrib
3 min read
How to Download Canvas as Image on Button Click in ChartJS?
In Chart.js, the charts that are generated can be converted and downloaded as images for easy sharing and reporting. By using built-in methods like toBase64Image() and the HTML canvas toBlob() method, we can enable users to download charts in formats such as PNG. These techniques provide a simple way to capture the visual data from charts and offer
4 min read
How to set radio button checked by button click in AngularJS ?
In this article, we will see how to set the radio button checked by button click in AngularJS, along with knowing its implementation through the examples. Approach: The approach is to use the ng-checked directive to check the radio button in the DOM. In the first example, a single radio button is checked by the button and In the second example, mul
2 min read
How to attach a click and double-click event to an element in jQuery ?
In this article, we will see how to attach a click and double-click event to an element in jQuery. To attach click and double-click events, click and dbclick events are used. These events are attached with the bind() method. This method is used to attach one or more event handlers for selected elements and this method specifies a function to run wh
1 min read
Difference Between @click and v-on:click in VueJS
Vue. JavaScript allows programmers to "hook" events into HTML elements using these unique event directives. One of them is the v-on directive, which is used to listen for certain events (clicks) and then run a method when that event occurs. v-on:click is the full version of the command that binds a click event to an element. That makes it obvious t
3 min read
How to Trigger a File Download when Clicking an HTML Button or JavaScript?
Triggering file downloads in JavaScript refers to initiating the download of files directly from a webpage when a user clicks a button or link. This can be achieved using HTML5's download attribute or custom JavaScript functions, allowing dynamic and user-friendly file-downloading experiences. To trigger a file download on a button click we will us
4 min read
How to change the href value of a tag after click on button using JavaScript ?
JavaScript is a high-level, interpreted, dynamically typed, and client-side scripting language. HTML is used to create static web pages. JavaScript enables interactive web pages when used along with HTML and CSS. Document Object Manipulation (DOM) is a programming interface for HTML and XML documents. DOM acts as an interface between JavaScript and
4 min read
How to change a button text on click using localStorage in Javascript ?
In this article, we will learn how to change a button text using Javascript localStorage when we click on the button achieved by adding HTML onclick event listener. Approach: HTML DOM Window localStorage allows us to store key-value pairs in our browser using an object. The name of the key should be unique and key-value pairs always be stored in st
3 min read
How to Auto Click a Button Using JavaScript?
To auto-click a button using JavaScript, you can programmatically trigger a click event on a button element. This can be useful for automating interactions or simulating user clicks without manual intervention. Example for Auto-Clicking a Button:[GFGTABS] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=
2 min read
How to download PDF file in ReactJS ?
To download pdf in React JS there are methods given in JavaScript and HTML DOM. They provide a convenient way to download files and store them in local computers. Here we will use locally stored pdf files in the project folder to use as a sample pdf downloaded by the browser. These are the approaches to download a PDF in React JS projects. Table of
3 min read
How to Add an Input Field on Button Click in JavaScript ?
JavaScript allows us to dynamically add an input field upon button click. We can use the below approaches for adding an input field on Button Click in JavaScript. Table of Content Using DOM ManipulationUsing Template Literal and InnerHTMLUsing DOM ManipulationDOM manipulation is used to dynamically create and append input fields upon clicking the "
2 min read
How to click a button to animate the paragraph element using jQuery ?
In this article, we will click a button to animate the paragraph element using jQuery. To animate the paragraph elements, we use animate() method. The animate() method is used to change the state of the element with CSS style. This method can also be used to change the CSS property to create the animated effect for the selected element. Syntax: $(s
1 min read
How to add more values to array on button click using PHP ?
In this article, we will learn to add elements to an existing array with the click of a button using PHP. PHP is a server-side language, and it only responds to requests (GET, POST, PUT, PATCH, and DELETE). The button click action happens as a part of the client-side to directly call a PHP function. We need an intermediary language to perform this
3 min read
How to use hide() method on button click using jQuery ?
jQuery has a lot of handy methods to get the work done easily. In this article, we will discuss one of them which is the hide() method. We can use this method for various purposes on our webpage and get an efficient result. The very first step will be creating an HTML file and link the jQuery library file via CDN. jQuery CDN Link: <script src="h
2 min read
How to hide block of HTML code on a button click using jQuery ?
In this article, we will learn how to hide a block of HTML code with a button click. We can do this by using the jQuery inbuilt hide() method. Let's briefly learn the functionality of this method. hide(): In CSS, we have a property display:none which basically hides the element. This hide() method in jQuery also hides the selected element. Syntax:
2 min read
How to hide/show an image on button click using jQuery ?
In this article, we will see how we can hide or show any particular image in jQuery when a button gets clicked. This is quite easy to do with some lines of jQuery code. Before we jump to the topic, let's know which methods of jQuery will be used for this. So there is a method called show() and another one is hide(), these two methods of jQuery can
3 min read
How to click a button on webpage using Selenium?
This article is all about how to click any button using Selenium on a webpage and many more concepts related to the same which are discussed below. Table of Content What is Selenium? How to click on a button using Selenium Conclusion Frequently Asked Questions on How to click a button on webpage using selenium? What is Selenium? Selenium is a widel
3 min read
How to convert a file to zip file and download it using Node.js ?
The Zip files are a common way of storing compressed files and folders. In this article, I'll demonstrate how to convert the file to zip format by using the adm-zip module (NPM PACKAGE). Uses of ADM-ZIP compress the original file and change them to zip format.update/delete the existing files(.zip format).Installation of ADM-ZIP: Step 1: Install the
3 min read
How to programmatically fire a click event for a file input element in JavaScript ?
In this article, we will learn how to programmatically fire click events on the input file element. ApproachWhenever you want to perform a click event programmatically, at your specific condition, just use the JavaScript in-built click() function by DOM object. Example: document.getElementById('your_input_type_file_element_id').click();Example 1: W
2 min read
How to load notification alert on top right corner without click of button in bootstrap ?
Bootstrap Toast component provides an easy way to mimic the functionality of push notifications. Bootstrap Toast is like an alert box that can be displayed to the user whenever an event occurs. This component has been built with CSS flexbox which makes it easy to position and align. It is not necessary to show the toast on a button click. It can be
2 min read
How to add input fields dynamically on button click in AngularJS ?
The task is to add an input field on the page when the user clicks on the button using AngularJs. Steps: The required component for the operation is created (add-inputComponent). In that component, html file (add-input.component.html) required html is written. In that HTML, the main div for input fields are there and button is created. There is a (
2 min read
How to set checkbox checked on button click in AngularJS?
In this article, we will see how to set checkboxes checked with the click of a button in AngularJS. Approach: The approach is to use the ng-checked directive to check the checkbox in the DOM. In the first example, a single checkbox is checked by the button and In the second example, multiple checkboxes are checked by the button. The ng-model direct
2 min read
How to hide an HTML element via a button click in AngularJS ?
In this article, we will see how to use a toggle button feature to hide and display an element by button click in Angular. The toggle button is a user interface control that may be useful for situations when the user wants to switch between 2 states or conditions. For instance, in our smartphone, we usually turn off/on the button to wireless connec
2 min read
How to Create Button Dynamically with Click Event in Angular ?
The task is to create a button dynamically with a click event using AngularJS, i.e., whenever someone clicks on the button then a new button gets created. The easiest way to create a button in AngularJS is to use the ng-repeat directive. We can easily hook up a repeat logic inside a button click event by using the ng-click Directive. Syntax: <el
2 min read
How to Change Button Text on Click in ReactJS ?
In this article, we will learn about diverse methods for altering button text dynamically upon clicking on the button. React, a widely embraced JavaScript library for crafting user interfaces provides several approaches to seamlessly achieve this functionality. The key lies in manipulating the component's state and adjusting its rendering logic to
3 min read
Create Dynamic Table with Auto Increment Serial Number on Button Click Event
We will see how we can auto increment the serial number of a table in html using JavaScript. We will build a button clicking on that will add a row to a table with an increasing number of rows. It will show the dynamic behavior, showing that we will use JavaScript and jQuery. These are the following methods: Table of Content Using JavaScriptUsing J
3 min read
How to Change the Color of Button on Click ?
Sometimes, on a web page, when a user clicks a button it gets difficult to understand whether the button is clicked or not. In such cases, you can change the background color of the button to indicate that the button is clicked. The below methods can be used to change background color of a button on click. Table of Content Using :active pseudo sele
2 min read
How to set alert message on button click in jQuery ?
Setting an alert message on a button click in jQuery means using jQuery to capture the button's click event and trigger a browser alert box. This alert displays a custom message to the user whenever the button is clicked. jQuery CDN Link: We have linked the jQuery in our file using the CDN link. <script src="https://code.jquery.com/jquery-3.6.0.
1 min read
How to Navigate on Path by Button Click in React Router ?
Navigation in React JS is done by implementing the routing between components using react-router-dom. To set navigation for components or events like button click, we can use the useHistory Hook provided in the react-router-dom v5. Prerequisites:NPM & Node.jsReact JSReact-Router-DomApproachNavigation in single-page applications is crucial for u
3 min read
How to create a Ripple Effect on Click the Button ?
A Ripple Effect on button click is a visual animation where a wave-like circle spreads outward from the click point, simulating a water ripple. This effect enhances user interaction feedback, making button clicks feel more dynamic and visually engaging. ApproachHTML Structure: Uses an <button> element with the class .btn for applying the ripp
2 min read
three90RightbarBannerImg