Rose Lancy

Rose Lancy

1577690338

How To Convert HTML To PDF using JavaScript

In this blog, I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and jQuery. We have to add two external JS files for converting the PDF -  JSPDF.js and html2canvas.js.

Creating an HTML Page for converting the HTMl to PDF

Add the following table in your HTML page.

<form class="form" style="max-width: none; width: 1005px;">  
  
  
        <h2 style="color: #0094ff">Hello</h2>  
        <h3>a bit about this Project:</h3>  
        <p style="font-size: large">  
            I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and J query.  
        </p>  
        <table>  
            <tbody>  
                <tr>  
                    <th>Company</th>  
                    <th>Contact</th>  
                    <th>Country</th>  
                </tr>  
                <tr>  
                    <td>Alfreds Futterkiste</td>  
                    <td>Maria Anders</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>Centro comercial Moctezuma</td>  
                    <td>Francisco Chang</td>  
                    <td>Mexico</td>  
                </tr>  
                <tr>  
                    <td>Ernst Handel</td>  
                    <td>Roland Mendel</td>  
                    <td>Austria</td>  
                </tr>  
                <tr>  
                    <td>Island Trading</td>  
                    <td>Helen Bennett</td>  
                    <td>UK</td>  
                </tr>  
                <tr>  
                    <td>Laughing Bacchus Winecellars</td>  
                    <td>Yoshi Tannamuri</td>  
                    <td>Canada</td>  
                </tr>  
                <tr>  
                    <td>Magazzini Alimentari Riuniti</td>  
                    <td>Giovanni Rovelli</td>  
                    <td>Italy</td>  
                </tr>  
            </tbody>  
        </table>  
  
  
    </form>  

Add the style of this HTML page.

<style>  
        table {  
            font-family: arial, sans-serif;  
            border-collapse: collapse;  
            width: 100%;  
        }  
  
        td, th {  
            border: 1px solid #dddddd;  
            text-align: left;  
            padding: 8px;  
        }  
  
        tr:nth-child(even) {  
            background-color: #dddddd;  
        }  
    </style>  

Add the “Print” button in this page, above the form tag.

<input type="button" id="create_pdf" value="Generate PDF">  

Add the following script in HTML page for converting it to pdf.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>  
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>  

Add other two scripts for converting the document.

<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>  
    /* 
 * jQuery helper plugin for examples and tests 
 */  
    (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>  

Now, let’s see the output.

This is image title

Click on the "Generate PDF " button and get the PDF file like this.

This is image title

Conclusion

You can easily add the Export to PDF functionality in the web page without depending on the server-side script. The PDF creation functionality can be enhanced with jsPDF configuration options as per your needs. Thank you for reading !

#JavaScript #HTML #PDF #Convert

What is GEEK

Buddha Community

How To Convert HTML To PDF using JavaScript

kartik singh

1595827923

Hi, Thanks for sharing this.

How can we add page break when we have a long dynamic content?

Rose Lancy

Rose Lancy

1577690338

How To Convert HTML To PDF using JavaScript

In this blog, I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and jQuery. We have to add two external JS files for converting the PDF -  JSPDF.js and html2canvas.js.

Creating an HTML Page for converting the HTMl to PDF

Add the following table in your HTML page.

<form class="form" style="max-width: none; width: 1005px;">  
  
  
        <h2 style="color: #0094ff">Hello</h2>  
        <h3>a bit about this Project:</h3>  
        <p style="font-size: large">  
            I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and J query.  
        </p>  
        <table>  
            <tbody>  
                <tr>  
                    <th>Company</th>  
                    <th>Contact</th>  
                    <th>Country</th>  
                </tr>  
                <tr>  
                    <td>Alfreds Futterkiste</td>  
                    <td>Maria Anders</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>Centro comercial Moctezuma</td>  
                    <td>Francisco Chang</td>  
                    <td>Mexico</td>  
                </tr>  
                <tr>  
                    <td>Ernst Handel</td>  
                    <td>Roland Mendel</td>  
                    <td>Austria</td>  
                </tr>  
                <tr>  
                    <td>Island Trading</td>  
                    <td>Helen Bennett</td>  
                    <td>UK</td>  
                </tr>  
                <tr>  
                    <td>Laughing Bacchus Winecellars</td>  
                    <td>Yoshi Tannamuri</td>  
                    <td>Canada</td>  
                </tr>  
                <tr>  
                    <td>Magazzini Alimentari Riuniti</td>  
                    <td>Giovanni Rovelli</td>  
                    <td>Italy</td>  
                </tr>  
            </tbody>  
        </table>  
  
  
    </form>  

Add the style of this HTML page.

<style>  
        table {  
            font-family: arial, sans-serif;  
            border-collapse: collapse;  
            width: 100%;  
        }  
  
        td, th {  
            border: 1px solid #dddddd;  
            text-align: left;  
            padding: 8px;  
        }  
  
        tr:nth-child(even) {  
            background-color: #dddddd;  
        }  
    </style>  

Add the “Print” button in this page, above the form tag.

<input type="button" id="create_pdf" value="Generate PDF">  

Add the following script in HTML page for converting it to pdf.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>  
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>  

Add other two scripts for converting the document.

<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>  
    /* 
 * jQuery helper plugin for examples and tests 
 */  
    (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>  

Now, let’s see the output.

This is image title

Click on the "Generate PDF " button and get the PDF file like this.

This is image title

Conclusion

You can easily add the Export to PDF functionality in the web page without depending on the server-side script. The PDF creation functionality can be enhanced with jsPDF configuration options as per your needs. Thank you for reading !

#JavaScript #HTML #PDF #Convert

CSS Boss

CSS Boss

1606912089

How to create a calculator using javascript - Pure JS tutorials |Web Tutorials

In this video I will tell you How to create a calculator using javascript very easily.

#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html

Vincent Lab

Vincent Lab

1605177921

Generate PDFs From HTML & CSS with Node.js using Puppeteer

#javascript #node.js #generate pdf using javascript #intermediate #node pdf #pdf

Angela  Dickens

Angela Dickens

1596090180

Commonly Used HTML Tags with Examples

HTML tags are keywords used in HTML to display web-pages with certain properties. They are further used for defining HTML elements. An HTML element consists of a starting tag, some content, and an ending tag. The web browser reads the HTML document from top to bottom, left to right. Each HTML tag defines a new property that helps in rendering the website.

HTML Tags

HTML Tags

The ‘<>’ brackets contain an HTML tag. There are two types of HTML tags- empty tags or singleton tags and container tags. Singleton tags or empty tags do not contain any content such as an image or a paragraph and hence do not need to be closed, whereas container tags should be closed.

Syntax

  1. Some Content

Examples of:

Empty tag: 
,


,etc.

Container tags: 

Paragraph

Link

  1. <!DOCTYPE>
  2. Paragraph

  3. Heading

  4. Bold
  5. Italic
  6. Underline

Output-

HTML Tags example

Head tags:

,<style>,<script>,<link>,<meta> and <base>. <p>Text-formatting tags:</p> <p><h>,<b>,<strong>,<small>,<pre>,<i>,<em>,<sub>,<sup>,<ins>,<dfn>,<del>,<div> and <span>.</p> <p>Link tags:</p> <p><a>, <base>.</p> <p>List tags:</p> <ul>, <ol>, <li>, <dl>, <dd> <p>Table tags:</p> <table> ,<tr> , <td>, <th>, <thead>, <tbody>, <tfoot>. <p>Form tags:</p> <form>, <input>, <select>, <option>, <button>, <label>, <fieldset>, <textarea>. <p>Scripting tags:</p> <script>, <noscript> Image and Object tags: <img>, <figure>, <figcaption>, <area>, <map>, <object>. Here is an alphabetical list of tags used in HTML.

#html tutorials #html image tags #html link tags #html list tags #html tags #html

Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:

1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.

2. Every database seller needs an approach to separate its item from others.

Right now, contrasts are noted where fitting.

#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language