ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
  • HOW TO EXTRACT TEXT FROM IMAGE USING Angular(OCR with Tesseract.js / OCR using Angular)?
  • Angular 7: Create new project using Angular 7
  • How to use the bootstrap(ngx-bootstrap) 4 in angular 7?
  • Validate a form in real time with JQuery Validation Plugin and Regex
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

Generate PDF from HTML with CSS by using JavaScript and JQuery

JavaScript AJAX about 7 years ago || 12/2/2018 || 29.3 K View

  • Hide

In this Article, I am going to show how to generate pdf from html with CSS by using JavaScript and JQuery.

Let’s create a HTML form with data and a button;

<input type="button" id="create_pdf" value="Generate PDF">
<form class="form" style="max-width: none; width: 1005px;">
    <h3>DEMO</h3>
    <p style="font-size: large">
        Convert HTML TO PDF:
    </p>
    <table class="table table-border">
        <tbody>
            <tr>
                <th>S.N.</th>
                <th>Employee Name</th>
                <th>Address</th>
                <th>Company</th>
            </tr>
            <tr>
                <td>1</td>
                <td>Mike</td>
                <td>USA</td>
                <td>Microsoft</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Manoj Ranjit</td>
                <td>India</td>
                <td>Tata Motors</td>
            </tr>
            <tr>
                <td>3</td>
                <td>xìng</td>
                <td>China</td>
                <td>Alibaba</td>
            </tr>
            <tr>
                <td>4</td>
                <td>Akari</td>
                <td>Japan</td>
                <td>Mitsubishi </td>
            </tr>
            <tr>
                <td>5</td>
                <td>Binod</td>
                <td>Nepal</td>
                <td>CG </td>
            </tr>
        </tbody>
    </table>
</form>

Now, Let’s add bootstrap for style

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

Also add JQuery.js and JSPdf.js

<script src="https://code.jquery.com/jquery-1.12.4.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>

Also, add html2canvas

<script>
    (function ($) {
        $.fn.html2canvas = function (options) {
            var date = new Date(),
            $message = null,
            timeoutTimer = false,
            timer = date.getTime();
            html2canvas.logging = options && options.logging;
            html2canvas.Preload(this[0], $.extend({
                complete: function (images) {
                    var queue = html2canvas.Parse(this[0], images, options),
                    $canvas = $(html2canvas.Renderer(queue, options)),
                    finishTime = new Date();

                    $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
                    $canvas.siblings().toggle();

                    $(window).click(function () {
                        if (!$canvas.is(':visible')) {
                            $canvas.toggle().siblings().toggle();
                            throwMessage("Canvas Render visible");
                        } else {
                            $canvas.siblings().toggle();
                            $canvas.toggle();
                            throwMessage("Canvas Render hidden");
                        }
                    });
                    throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
                }
            }, options));

            function throwMessage(msg, duration) {
                window.clearTimeout(timeoutTimer);
                timeoutTimer = window.setTimeout(function () {
                    $message.fadeOut(function () {
                        $message.remove();
                    });
                }, duration || 2000);
                if ($message)
                    $message.remove();
                $message = $('<div ></div>').html(msg).css({
                    margin: 0,
                    padding: 10,
                    background: "#000",
                    opacity: 0.7,
                    position: "fixed",
                    top: 10,
                    right: 10,
                    fontFamily: 'Tahoma',
                    color: '#fff',
                    fontSize: 12,
                    borderRadius: 12,
                    width: 'auto',
                    height: 'auto',
                    textAlign: 'center',
                    textDecoration: 'none'
                }).hide().fadeIn().appendTo('body');
            }
        };
    })(jQuery);
</script>

Also add one function:

<script>
    (function () {
        var
         form = $('.form'),
         cache_width = form.width(),
         a4 = [595.28, 841.89]; // for a4 size paper width and height

        $('#create_pdf').on('click', function () {
            $('body').scrollTop(0);
            createPDF();
        });
        //create pdf
        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('bhavdip-html-to-pdf.pdf');
                form.width(cache_width);
            });
        }

        // create canvas object
        function getCanvas() {
            form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
            return html2canvas(form, {
                imageTimeout: 2000,
                removeContainer: true
            });
        }

    }());
</script>

Here is final html file

<html>
<head>
    <title>Convert HTML To PDF</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
</head>
<body>
    <input type="button" id="create_pdf" value="Generate PDF">
   <form class="form" style="max-width: none; width: 1005px;">
    <h3>DEMO</h3>
    <p style="font-size: large">
        Convert HTML TO PDF:
    </p>
    <table class="table table-border">
        <tbody>
            <tr>
                <th>S.N.</th>
                <th>Employee Name</th>
                <th>Address</th>
                <th>Company</th>
            </tr>
            <tr>
                <td>1</td>
                <td>Mike</td>
                <td>USA</td>
                <td>Microsoft</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Manoj Ranjit</td>
                <td>India</td>
                <td>Tata Motors</td>
            </tr>
            <tr>
                <td>3</td>
                <td>xìng</td>
                <td>China</td>
                <td>Alibaba</td>
            </tr>
            <tr>
                <td>4</td>
                <td>Akari</td>
                <td>Japan</td>
                <td>Mitsubishi </td>
            </tr>
			<tr>
                <td>5</td>
                <td>Binod</td>
                <td>Nepal</td>
                <td>CG </td>
            </tr>
        </tbody>
    </table>
</form>

</body>

</html>
<script>
    (function () {
        var
         form = $('.form'),
         cache_width = form.width(),
         a4 = [595.28, 841.89]; // for a4 size paper width and height

        $('#create_pdf').on('click', function () {
            $('body').scrollTop(0);
            createPDF();
        });
        //create pdf
        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('bhavdip-html-to-pdf.pdf');
                form.width(cache_width);
            });
        }

        // create canvas object
        function getCanvas() {
            form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
            return html2canvas(form, {
                imageTimeout: 2000,
                removeContainer: true
            });
        }

    }());
</script>
<script>
    (function ($) {
        $.fn.html2canvas = function (options) {
            var date = new Date(),
            $message = null,
            timeoutTimer = false,
            timer = date.getTime();
            html2canvas.logging = options && options.logging;
            html2canvas.Preload(this[0], $.extend({
                complete: function (images) {
                    var queue = html2canvas.Parse(this[0], images, options),
                    $canvas = $(html2canvas.Renderer(queue, options)),
                    finishTime = new Date();

                    $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
                    $canvas.siblings().toggle();

                    $(window).click(function () {
                        if (!$canvas.is(':visible')) {
                            $canvas.toggle().siblings().toggle();
                            throwMessage("Canvas Render visible");
                        } else {
                            $canvas.siblings().toggle();
                            $canvas.toggle();
                            throwMessage("Canvas Render hidden");
                        }
                    });
                    throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
                }
            }, options));

            function throwMessage(msg, duration) {
                window.clearTimeout(timeoutTimer);
                timeoutTimer = window.setTimeout(function () {
                    $message.fadeOut(function () {
                        $message.remove();
                    });
                }, duration || 2000);
                if ($message)
                    $message.remove();
                $message = $('<div ></div>').html(msg).css({
                    margin: 0,
                    padding: 10,
                    background: "#000",
                    opacity: 0.7,
                    position: "fixed",
                    top: 10,
                    right: 10,
                    fontFamily: 'Tahoma',
                    color: '#fff',
                    fontSize: 12,
                    borderRadius: 12,
                    width: 'auto',
                    height: 'auto',
                    textAlign: 'center',
                    textDecoration: 'none'
                }).hide().fadeIn().appendTo('body');
            }
        };
    })(jQuery);
</script>

Output:

After clicking "Generate PDF" Button we will get generated pdf. Which is:

 

  • 0
  • 0
  • 1
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Anthony M. Healey

Anthony M. Healey

Touch of Creativity and a bit of active on brain power

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey