How To Convert HTML To PDF

In this article, we will learn how to convert HTML to PDF.

Prerequisites

  • Basic knowledge of JavaScript

html2canvas

The script allows you to take screenshots of web pages or parts of it, directly on the user’s browser. The screenshot is based on the information available on the page.

jspdf

Generate PDF files in client-side JavaScript.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
     <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
     <table id="tblStudents" cellspacing="0" cellpadding="0">
        <tr>
            <th>Student Id</th>
            <th>Student Name</th>
            <th>Country</th>
      <th>Marks</th>
        </tr>
        <tr>
            <td>1</td>
            <td>John Hammond</td>
            <td>United States</td>
      <td>85</td>
  </tr>
        <tr>
            <td>2</td>
            <td>Mudassar Khan</td>
            <td>India</td>
      <td>75</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Suzanne Mathews</td>
            <td>France</td>
      <td>80</td>
        </tr>
        <tr>
            <td>4</td>
            <td>Robert Schidner</td>
            <td>Russia</td>
      <td>95</td>
  </tr>
    </table>
    <br />
    <input type="button" id="btnExport" value="Export" onclick="Export()" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.22/pdfmake.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
    <script type="text/javascript">
        function Export() {
            html2canvas(document.getElementById('tblStudents'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    var docDefinition = {
                        content: [{
                            image: data,
                            width: 500
                        }]
                    };
                    pdfMake.createPdf(docDefinition).download("HtmlToPdf.pdf");
                }
            });
        }
    </script>
</body>
</html>
Output

Also Check, How To Convert HTML To PDF In Angular 9

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories