jsPDF-AutoTable icon indicating copy to clipboard operation
jsPDF-AutoTable copied to clipboard

Existing Column omission

Open jdr430 opened this issue 11 years ago • 18 comments

I generate some tables using SQL INNER JOIN from different tables on my DB. I have noticed that the plugin omits columns that already exist? Original Table table_real

Pdf Table

pdf_table

Notice only 12 columns on the pdf table instead of 14 as the columns type and outcomeId_fk have only been printed once. How can I fix this?

jdr430 avatar Apr 17 '15 11:04 jdr430

Yes, that is by design. However you can init the table with indexes instead of keys. This is undocumented at the moment, but I'm working on a more complete documentation of the initialization options. Here is a basic example:

var cols = ["Header 1", "Header 2", "Header 3"];
var data = [
    ["Row 1", "Row 1", "Row 1"],
    ["Row 1", "Row 1", "Row 1"],
    ["Row 1", "Row 1", "Row 1"]
];
var doc = new jsPDF('p', 'pt');
doc.autoTable(cols, data, {});
doc.save("table.pdf");

simonbengtsson avatar Apr 17 '15 12:04 simonbengtsson

I am using autoTableHtmlToJson which only returns one dataset I am not sure how I can retrieve the headers and the data from data returned from autoTableHtmlToJson .

jdr430 avatar Apr 17 '15 13:04 jdr430

Right now you would have to format the dataset returned from autoTableHtmlToJson manually. Like this

var json = doc.autoTableHtmlToJson(document.getElementById("basic-table"));
var cols = [], data = [];
for(var i = 0; i < json.length; i++)  {
    var row = json[i];
    var newRow = [];
    for (var key in row) {
        if (row.hasOwnProperty(key)) {
            if(i === 0) {
                cols.push(key);
            }
            newRow.push(row[key]);
        }
    }
    data.push(newRow);
});
doc.autoTable(cols, data, {startY: 60});
doc.save("table.pdf");

simonbengtsson avatar Apr 17 '15 14:04 simonbengtsson

Not recognising the .forEach function for some weird reason.

jdr430 avatar Apr 17 '15 14:04 jdr430

Removed it from the example, but I think I use it in the plugin. What web browser are you using?

simonbengtsson avatar Apr 17 '15 14:04 simonbengtsson

Yes you use it in the plugin I checked to confirm. I'm using chrome Version 41.0.2272.118 m

jdr430 avatar Apr 17 '15 15:04 jdr430

I should probably add the forEach polyfill to the plugin, however in the mean time you can add it to see if it works for you. Just include the below before the plugin. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

    Array.prototype.forEach = function(callback, thisArg) {

        var T, k;

        if (this == null) {
            throw new TypeError(' this is null or not defined');
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if (typeof callback !== "function") {
            throw new TypeError(callback + ' is not a function');
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 1) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while (k < len) {

            var kValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[k];

                // ii. Call the Call internal method of callback with T as the this value and
                // argument list containing kValue, k, and O.
                callback.call(T, kValue, k, O);
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

It's sounds strange though, chrome has always had support for forEach

simonbengtsson avatar Apr 17 '15 15:04 simonbengtsson

AM I adding this to the plugin or to my own script?

jdr430 avatar Apr 17 '15 15:04 jdr430

Add it to your script, before you include the plugin. I will add it in the next version of the plugin however.

simonbengtsson avatar Apr 17 '15 15:04 simonbengtsson

That made no difference, I'll research the problem about the forEach. Thanks for your suggestions dude.

jdr430 avatar Apr 17 '15 15:04 jdr430

Messed about with the code ended up with this:

$(document).on("click", "#PDF", function () {
    var table = document.getElementById("result");
    var doc = new jsPDF('p', 'pt');
     var json = doc.autoTable(false, doc.autoTableHtmlToJson(table));
     console.log(JSON.stringify(json));
     var new_json = JSON.stringify(json);
     var cols = [], data = [];
     //json.forEach(function(row, index) {
     [].forEach.call(new_json, function(row,index) {
         var newRow = [];
         for (var key in row) {
             if (row.hasOwnProperty(key)) {
                 if(index === 0) {
                     cols.push(key);
                 }
                 newRow.push(row[key]);
             }
         }
         data.push(newRow);
     });
     doc.autoTable(cols, data, {startY: 60});
     doc.save("table.pdf");
});

The PDF file generated is really messed up though: Output is barely visible. pdf_json

jdr430 avatar Apr 17 '15 15:04 jdr430

You are drawing two tables on the same place. You should remove the first call to doc.autoTable(). Try the example I posted again. If it doesn't work for you, it would be great if you could create a jsfiddle or post more complete code.

simonbengtsson avatar Apr 17 '15 23:04 simonbengtsson

Works like a charm. Thank you very much for your help and patience!!! Great tool!

jdr430 avatar Apr 20 '15 09:04 jdr430

No worries! Let me know if you run into other issues!

simonbengtsson avatar Apr 20 '15 09:04 simonbengtsson

Hi,

I could not get overflow: linebreak to work for me. I have data as HTML, I convert it to json using autoTableHtmlToJson and then use autoTable to generate the PDF.

For example:

var res = doc.autoTableHtmlToJson(document.getElementById("basic-table"), true);

doc.autoTable(res.columns, res.data, {margins: {horizontal: 10, top: 40, bottom: 40}, startY: 370, overflow: 'linebreak', overflowColumns: false});

publish(doc.output('datauristring'));

But the column data gets truncated instead of getting word wrapped. How to achieve it?

ruhijain avatar Jun 09 '15 06:06 ruhijain

$.ajax({ type: "POST", url: "KIADB.asmx/Getreport", data: "{'zone':'" + zone + "','district':'" + district + "', " + "'industrialarea':'" + industrialarea + "'," + "'fromdate':'" + fromdate + "'," + "'todate':'" + todate + "'}", contentType: "application/json;character=utf-8", dataType: "json", success: function (data) { var data = JSON.parse(data.d);

        var columns = [
                       { title: "Industrial zone", key: "indzone" },
                       { title: "District", key: "dstr" },
                       { title: "Taluk", key: "tlk" },
                       { title: "ContactTitle", key: "vlg" },
                       { title: "Industrial area", key: "nmindar" },
                       { title: "Plot No", key: "plno" },
                       { title: "Plot area", key: "pltar" },
                       { title: "Name of allottee", key: "nmalt" },
                       { title: "Address of allottee", key: "addalt" },
                       { title: "Nature of industry", key: "ntrind" },
                       { title: "Reservation", key: "rsvr" },
                       { title: "Index", key: "indx" },
                       { title: "Plot status", key: "plst" },
                       { title: "Implimentation status", key: "implst" },
                       { title: "Date of possession", key: "dtpss" },
                       { title: "Date of allotment", key: "dtaltm" },
                       { title: "Due Date of payment", key: "ddtpmt" },
                       { title: "Date of Lease Agreement Executed", key: "dtleagrex" },
                       { title: "Stipulated time for commencement of production", key: "stcmprd" },
                       { title: "Extension of time Granted", key: "extgrt" },
                       { title: "Remarks", key: "remark" },
                       { title: "Updated Date", key: "plotupdateddate" }

        ];

         l = {
     format: 'a3',
     compress: true,
     fontSize: 8,
     autoSize: false,
     printHeaders: true
 };
         var doc = new jsPDF(l, '', '');
        doc.autoTable(columns, data, {
            styles: {
              columnWidth:'auto'
    }
        });
        doc.save('Statusreport.pdf');
    }

});

above code i am using to generate pdf but i am getting like

can any one help me how to align column

Statusreport.pdf

VeenaHosur avatar Jun 10 '16 10:06 VeenaHosur

pdf.autoTableHtmlToJson comes undefined every time although all the required libraries are already loaded. image

suraj93p avatar Apr 21 '17 05:04 suraj93p

I also ran into the same issue, and code is just as the above.

sebastiaodomingos avatar Jan 26 '18 01:01 sebastiaodomingos