Search code examples
javascriptreactjsjspdfjspdf-autotable

Spacing in all pages JSPDF


I added a Header & Footer in JSPDF using help from the following link. Adding Header & Footer for all screens in JSPDF

The Issue that I get is the spacing between the header and table is getting reflected only in the first page of the downloaded PDF.

You can check the example reproduced here https://codesandbox.io/s/upbeat-cannon-cfiry?file=/src/App.js.

I need to help in getting the same space for all pages between table and Header. Thanks

Code :

import jsPDF from "jspdf";
import "jspdf-autotable";
import { datas } from "./data";
import { renderToString } from "react-dom/server";
import PdfDocument from "./PdfDocument";
export default function App() {
  const columns = [
    { title: "Rank", dataKey: "Rank" },
    { title: "Name", dataKey: "Name" },
    { title: "count", dataKey: "count" }
  ];

  var rows = datas?.map((data) => ({
    Rank: data?.Rank,
    Name: data?.Name,
    count: data?.count
  }));

  const downloadPdf = () => {
    var doc = new jsPDF("p", "pt");
    doc.setFontSize(20);
    doc.setTextColor(40);
    doc.setFontStyle("normal");
    doc.autoTable(columns, rows, {
      startY: 70,

      margin: { horizontal: 10 },
      styles: { overflow: "linebreak" },
      bodyStyles: { valign: "top" },
      columnStyles: { email: { columnWidth: "wrap" } },
      theme: "striped",
      showHead: "everyPage",
      didDrawPage: function (data) {
        // Header
        doc.setFontSize(16);
        doc.setTextColor("#161C22");
        doc.text("Table", data.settings.margin.left, 35);
        doc.text("Brand", 465, 34);

        // Footer
        let str = "" + doc.internal.getNumberOfPages();
        doc.setFontSize(10);

        // jsPDF 1.4+ uses getWidth, <1.4 uses .width
        let pageSize = doc.internal.pageSize;
        let pageHeight = pageSize.height
          ? pageSize.height
          : pageSize.getHeight();
        doc.text("Footer text", data.settings.margin.left, pageHeight - 10);
        doc.text(575, 830, str);
      }
    });

    doc.save("random.pdf");
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={downloadPdf}> Download PDF </button>
    </div>
  );
}

Solution

  • Consider adding

    data.settings.margin.top = 70;
    

    at the beginning of didDrawPage function.