tousif Noor
tousif Noor

Reputation: 395

JSPDF : Genearte pdf from object of array and display like Lables

I want to generate PDF from object of array and display like this which I have attached in image.PDF data in Lable view .how I can achieve this while my output is in row wise.

  htmlStr += '<table id="customers" class="table-wide">';
htmlStr += '<thead ></thead>';
htmlStr += '<tbody ></tbodyid>';
htmlStr += '</table>';
this.html = $(htmlStr);

Upvotes: 0

Views: 4765

Answers (1)

Purushoth
Purushoth

Reputation: 2793

I think you have to do it on your own. jsPDF-Autotable is not good option for this scenario. Following is something like a scratch it's not a perfect solution. Please work on it further.

Actually we are going to create grid cards until the page width and height.

If height reaches, add new page doc.addPage().

If width reaches, add new row.

    var data = [{
      "Name": "Ronan",
      "Email": "[email protected]",
      "Company": "Malesuada Malesuada Ltd"
    }, {
      "Name": "Calvin",
      "Email": "[email protected]",
      "Company": "Donec Egestas Foundation"
    }, {
      "Name": "Kane",
      "Email": "[email protected]",
      "Company": "Arcu Institute"
    }, {
      "Name": "Kasper",
      "Email": "[email protected]",
      "Company": "Tempor LLP"
    }];
    
    
  

     var doc = new jsPDF('p', 'pt', 'a4');
//Dimension of A4 in pts: 595 × 842

var pageWidth = 595;
var pageHeight = 842;

var pageMargin = 20;

pageWidth -= pageMargin * 2;
pageHeight -= pageMargin * 2;

var cellPadding = 10;
var cellWidth = 180;
var cellHeight = 70;
var lineHeight = 20;

var startX = pageMargin;
var startY = pageMargin;


doc.setFontSize(12);

var page = 1;

function createCard(item) {

  //cell projection
  var requiredWidth = startX + cellWidth + (cellPadding * 2);

  var requiredHeight = startY + cellHeight + (cellPadding * 2);



  if (requiredWidth <= pageWidth) {

    textWriter(item, startX + cellPadding, startY + cellPadding);

    startX = requiredWidth;
    //  startY += cellHeight + cellPadding;

  } else {


    if (requiredHeight > pageHeight) {
      doc.addPage();
      page++;
      doc.setPage(page);

      startY = pageMargin;
    } else {
      startY = requiredHeight;
    }

    startX = pageMargin;


    textWriter(item, startX + cellPadding, startY + cellPadding);

    startX = startX + cellWidth + (cellPadding * 2);
  }

}

function textWriter(item, xAxis, yAxis) {
  doc.text(item.Name, xAxis, yAxis);
  doc.text(item.Email, xAxis, yAxis + lineHeight);
  doc.text(item.Company, xAxis, yAxis + (lineHeight * 2));
}


for (var i = 0; i < data.length; i++) {
  createCard(data[i]);
}

doc.save('grid.pdf');

For reference https://jsfiddle.net/Purushoth/jodfkz59/

Upvotes: 2

Related Questions