Search code examples
javascriptcssreactjsjspdfjspdf-autotable

How to specify coordinates or provide margins for the autoTable in jsPdf for React js?


I'm using jsPdf library to generate a pdf in React. But I'm unable to provide margins to the autoTable if there are more that one table in the single page!

Here is the code:-

import React from "react";

var { jsPDF } = require("jspdf");
require("jspdf-autotable");

function ShowPdf() {
  const [head] = React.useState(["Name", "Email", "Country"]);
  const [body] = React.useState([
    ["David", "[email protected]", "Sweden"],
    ["David", "[email protected]", "Sweden"],
    ["David", "[email protected]", "Sweden"],
    ["David", "[email protected]", "Sweden"],
    ["David", "[email protected]", "Sweden"],
  ]);
  const generatePDF = () => {
    let doc = new jsPDF("p", "pt", "a4");

    doc.setFont("Calibri", "bold");
    doc.setFontSize(14);
    doc.setTextColor(14, 3, 64);
    doc.text("Table 1", 20, 140);
    doc.line(20, 142, 550, 142);

    doc.text("Table 2", 20, 300);
    doc.line(20, 302, 550, 302);

    doc.autoTable({
      margin: { top: 150, left: 20, bottom: 30 },
      head: [head],
      body: [body[0], body[1], body[2], body[3], body[4]],
    });

    doc.autoTable({
      margin: { top: 400, left: 20, bottom: 30 },
      head: [head],
      body: [body[0], body[1], body[2], body[3], body[4]],
    });

    window.open(doc.output("bloburl"), "_blank");
  };
  return (
    <div>
      <button onClick={generatePDF} type="primary">
        Generate PDF
      </button>
    </div>
  );
}

export default ShowPdf;

Margin is working for the first table but for the second table providing or changing top margin is not reflecting any change!

Can I provide x and y coordinates fot jsPdf autotable?

enter image description here


Solution

  • Got the answer! We can use startY to provide y coordinates to the table.