Vue.js jsPDF Tutorial to Export HTML Table to PDF/XLS/CSV Documents in Javascript Full Project For Beginners

  • Post author:
  • Post category:Vue
  • Post comments:0 Comments

 

 

Welcome folks today in this blog post we will be exporting html table to pdf/xls/csv documents in javascript using jspdf library in vue.js.All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<div id="app">
    <div class="query-container mt-3">
        <div class="row">
            <div class="col-3 pl-5">
                <label class="mr-3">From Date :</label>
                <input class="form-control" type="date" v-model="fromDate" value="" placeholder="" />
            </div>
            <div class="col-3">
                <label>To Date :</label>
                <input class="form-control" type="date" v-model="toDate" value="" placeholder="" />
            </div>
            <div class="col-6">
                <div @click="getReport()" class="btn btn-success">
                    <i class="fa fa-search"></i>
                    Find
                </div>
                <div class="downloads" v-if="items.length>0">
                    <div @click="exportReport('pdf')" class="btn btn-warning">
                        <i class="fa fa-file-pdf-o"></i>
                        Export PDF
                    </div>
                    <div @click="exportReport('xls', 'maintable', 'salesreport')" class="btn btn-warning">
                        <i class="fa fa-file-excel-o"></i>
                        Export XLS
                    </div>
                    <div @click="exportReport('csv', 'maintable', 'salesreport')" class="btn btn-warning">
                        <i class="fa fa-file-o"></i>
                        Export CSV
                    </div>
                </div>
            </div>
            
        </div>

    </div>
    <br>
    <div class="table-container" v-if="items.length>0">
        <table class="table" id="maintable">
            <thead>
                <tr>
                    <th >Action</th>
                    <th >#</th>
                    <th >ID</th>
                    <th >Value</th>
                    <th >Date</th>
                    <th >Type</th>
                    <th >Trans ID</th>
                    <th >By</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th ></th>
                    <th >Total #{{items.length}}</th>
                    <th ></th>
                    <th >Total Rs.{{totalAmount}}</th>
                    <th ></th>                  
                    <th ></th>
                    <th ></th>
                    <th ></th>
                    <th ></th>
                </tr>
            </tfoot>
            <tbody>
                <tr v-for="item in items">
                    <td @click="deleteItem(item)"><a href="javascript:void(0);" class="fa fa-undo"></a></td>
                    <td>{{items.indexOf(item)+1}}</td>
                    <th>{{item.id}}</th>
                    <td>Rs.{{item.value}}</td>
                    <td>{{getDateOf(item.date)}}</td>
                    <th>{{item.type}}</th>
                    <td>{{item.transactionId}}</td>
                    <td>{{item.transactionBy}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>

 

 

 

Now make a script.js file and copy paste the following code

 

 

script.js

 

 

new Vue({
    el: "#app",
    data: {
        pdf: new jsPDF(),
        fromDate: "",
        toDate: "",
        totalAmount: "500",
        items: [
            {
                _id: "j30nsf02mn230234knsdf",
                id: "RC100",
                value: 100,
                type: "recharge",
                date: "Mon Jul 02 2018 13:17:11 GMT+0530 (India Standard Time)",
                transactionId: "ab12sd12123asd",
                transactionBy: "McDonald"
            },
            {
                _id: "k30nsf02mn000234knsdg",
                id: "RC200",
                value: 200,
                type: "Register",
                date: "Mon Jul 02 2018 13:17:11 GMT+0530 (India Standard Time)",
                transactionId: "rb12sd16123asq",
                transactionBy: "McDonald"
            }
        ]
    },
    watch: {
        items: function(val) {
            this.totalAmount = _.sumBy(this.items, "value");
        }
    },
    methods: {
        exportReport(type, table_id, file_name) {
            var xport = {
                _fallbacktoCSV: true,
                toXLS: function(tableId, filename) {
                    this._filename = typeof filename == "undefined" ? tableId : filename;
                    if ((this._getMsieVersion() || this._isFirefox()) && this._fallbacktoCSV) {
                        return this.toCSV(tableId);
                    } else if (this._getMsieVersion() || this._isFirefox()) {
                        alert("Not supported browser");
                    }

                    //Other Browser can download xls
                    var htmltable = document.getElementById(tableId);
                    var html = htmltable.outerHTML;

                    this._downloadAnchor(
                        "data:application/vnd.ms-excel" + encodeURIComponent(html),
                        "xls"
                    );
                },
                toCSV: function(tableId, filename) {
                    this._filename = typeof filename === "undefined" ? tableId : filename;
                    // Generate our CSV string from out HTML Table
                    var csv = this._tableToCSV(document.getElementById(tableId));
                    // Create a CSV Blob
                    var blob = new Blob([csv], { type: "text/csv" });

                    // Determine which approach to take for the download
                    if (navigator.msSaveOrOpenBlob) {
                        // Works for Internet Explorer and Microsoft Edge
                        navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
                    } else {
                        this._downloadAnchor(URL.createObjectURL(blob), "csv");
                    }
                },
                _getMsieVersion: function() {
                    var ua = window.navigator.userAgent;

                    var msie = ua.indexOf("MSIE ");
                    if (msie > 0) {
                        // IE 10 or older => return version number
                        return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)), 10);
                    }

                    var trident = ua.indexOf("Trident/");
                    if (trident > 0) {
                        // IE 11 => return version number
                        var rv = ua.indexOf("rv:");
                        return parseInt(ua.substring(rv + 3, ua.indexOf(".", rv)), 10);
                    }

                    var edge = ua.indexOf("Edge/");
                    if (edge > 0) {
                        // Edge (IE 12+) => return version number
                        return parseInt(ua.substring(edge + 5, ua.indexOf(".", edge)), 10);
                    }

                    // other browser
                    return false;
                },
                _isFirefox: function() {
                    if (navigator.userAgent.indexOf("Firefox") > 0) {
                        return 1;
                    }

                    return 0;
                },
                _downloadAnchor: function(content, ext) {
                    var anchor = document.createElement("a");
                    anchor.style = "display:none !important";
                    anchor.id = "downloadanchor";
                    document.body.appendChild(anchor);

                    // If the [download] attribute is supported, try to use it

                    if ("download" in anchor) {
                        anchor.download = this._filename + "." + ext;
                    }
                    anchor.href = content;
                    anchor.click();
                    anchor.remove();
                },
                _tableToCSV: function(table) {
                    // We'll be co-opting `slice` to create arrays
                    var slice = Array.prototype.slice;

                    return slice
                        .call(table.rows)
                        .map(function(row) {
                            return slice
                                .call(row.cells)
                                .map(function(cell) {
                                    return '"t"'.replace("t", cell.textContent);
                                })
                                .join(",");
                        })
                        .join("\r\n");
                }
            };
            if (type === "pdf") {
                topPDF();
            } else if (type === "xls") {
                xport.toXLS(table_id, file_name);
            } else {
                xport.toCSV(table_id, file_name);
            }
            function toPDF() {
                var self = this;

                var pdf = new jsPDF("p", "pt", "a4");

                source = $(".table")[0];

                specialElementHandlers = {
                    "#bypassme": function(element, renderer) {
                        return true;
                    }
                };
                margins = {
                    top: 80,
                    bottom: 60,
                    left: 10,
                    width: 700
                };

                pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top,
                    {
                        // y coord
                        width: margins.width, // max width of content on PDF
                        elementHandlers: specialElementHandlers
                    },

                    function(dispose) {
                        pdf.save("Test.pdf");
                    },
                    margins
                );
            }
        },
        getReport() {
            alert(new Date(this.fromDate) + "~~~" + new Date(this.toDate));
        },
        deleteItem(item) {
            this.items.pop();
        },
        getDateOf(date) {
            var dateVal = new Date(date);
            var month = dateVal.getMonth() + 1;
            var day = dateVal.getDate();
            var year = dateVal.getFullYear();
            var data = day + "/" + month + "/" + year;
            return data;
        }
    },
    beforeMount() {},
    mounted() {
        this.totalAmount = _.sumBy(this.items, "value");
    }
});

Leave a Reply