Search code examples
javascriptpdfjspdfjspdf-autotable

How to center fixed width table on page horizontally? jsPDF with autotable


I'm using jsPDF with autotable, I'm trying to center the table with fixed-width on generated pdf page. I can't seem to find a solution for this, everywhere I look is just full width, I don't want my table to be full width. I tried with margins option but It's not very precise and I'm not entirely sure how to calculate margins from A4 to horizontally center my table.

Screenshot: enter image description here

document.querySelector(".report-btn").addEventListener("click", () => {
  const pdfDoc = new jsPDF();
  const list = createListforPdf(); // function to generate list

  pdfDoc.autoTable({
    theme: "grid",
    tableWidth: 100,
    styles: { halign: "center" },
    columnStyles: {
      0: { cellWidth: 85, halign: "left" },
      1: { cellWidth: 15 }
    },

    head: [["MRZ Check number", "is OK?"]],
    body: [[list[0], "YES"], [list[1], "NO"]]
  });

  pdfDoc.save();
});

Solution

  • You can calculate the margins in the following way:

    let doc = new jsPDF();
    
    let wantedTableWidth = 100;
    let pageWidth = doc.internal.pageSize.width;
    let margin = (pageWidth - wantedTableWidth) / 2;
    
    doc.autoTable({
        head: [['Name', 'Country']],
        body: [
            ['Leon', 'Sweden'],
            ['Magnus', 'Norway'],
            ['Juan', 'Argentina'],
        ],
        margin: {left: margin, right: margin}
    });
    
    doc.save('table.pdf');