Tuesday 19 February 2019

Using JsPdf to generate pdf from html

Today i felt a need to save my html data to pdf. For the purpose jsPdf with jsPdf-auto is a good combination.
Here is the code that is working with me now.


//base function that i called on button click.

function exportReportTable() {
    toDataURL($("#imgUrl").val(), function(dataUrl) {
        exportReportAsPdf(dataUrl)
    });
}

// This function converts the image to data which can be use to add as logo.

function toDataURL(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}



// function using jspdf and jspdf-auto.

function exportReportAsPdf(imgData){
    var doc = new jsPDF();

    // To display header and log on single page, uncomment the line and remove from header section.

    /*doc.addImage(imgData, 'png', 12, 5, 20, 20);
    doc.setFontSize(12);
    doc.text($("#companyName").val(), 60, 10);
    doc.text("Payment Vouchers", 80, 15);
    doc.text("Date From: " + $("#fromDate").val() + " To: " + $("#toDate").val(), 65, 20);*/

    var header = function (data) {
        doc.setTextColor(40);
        doc.setFontStyle('normal');
        doc.addImage(imgData, 'png', 12, 5, 20, 20);
        doc.setFontSize(12);
        doc.text($("#companyName").val(), 60, 10);
        doc.text("Payment Vouchers", 80, 15);
        doc.text("Date From: " + $("#fromDate").val() + " To: " + $("#toDate").val(), 65, 20);
        doc.setFontSize(10);
    };

    doc.autoTable({
        margin: {
            top: 30
        },
        html: '#reportTable',
        didDrawPage: header,
        bodyStyles: {valign: 'top'},
        styles: {overflow: 'linebreak', cellWidth: 'wrap'},
        columnStyles: {2: {cellWidth: 'auto'}} // 2 represents the 2nd column
    });
    // To add water mark
    doc = addWaterMark(doc, imgData);
    doc.save("Payment_Voucher_Report_"+ $("#fromDate").val()+"_"+$("#toDate").val()+".pdf");
}

// This function add water mark text at bottom. You can change the location and text.

function addWaterMark(doc,imgData) {
    var totalPages = doc.internal.getNumberOfPages();

    for (i = 1; i <= totalPages; i++) {
        doc.setPage(i);
        //doc.addImage(imgData, 'PNG', 40, 40, 75, 75);
        doc.setTextColor(150);
        doc.setFontSize(8);
        doc.text(140, doc.internal.pageSize.height - 10,"Report has total "+totalPages+" pages. This is "+ i+" of "+totalPages);
        //doc.text(30, 30, 'Report Text', null, 46);
    }

    return doc;
}