I'm Trying to add a header and footer in all screens while downloading PDF. I have added table with mock data using jspdf-autotable and able to download it. But the header is coming only in last page of the downloaded PDf
I need some help in getting Header and footer with page number in all screens. Kindly help.
Code in sandbox : https://codesandbox.io/s/upbeat-cannon-cfiry?file=/src/App.js:0-1257
Code here :
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 = () => {
const string = renderToString(<PdfDocument />);
var doc = new jsPDF("p", "pt");
doc.setFontSize(20);
doc.setTextColor(40);
doc.setFontStyle("normal");
doc.autoTable(columns, rows, {
startY: doc.autoTable() + 70,
margin: { horizontal: 10 },
styles: { overflow: "linebreak" },
bodyStyles: { valign: "top" },
columnStyles: { email: { columnWidth: "wrap" } },
theme: "striped",
showHead: "everyPage"
});
doc.fromHTML(string);
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>
);
}
AutoTable
provides a list of hooks for customizing the content and styling of the table.
You can use didDrawPage
hook for adding Header and Footer to your pages. You can do something like this:
doc.autoTable(columns, rows, {
startY: doc.autoTable() + 70,
margin: { horizontal: 10 },
styles: { overflow: "linebreak" },
bodyStyles: { valign: "top" },
columnStyles: { email: { columnWidth: "wrap" } },
theme: "striped",
showHead: "everyPage",
didDrawPage: function (data) {
// Header
doc.setFontSize(20);
doc.setTextColor(40);
doc.text("Report", data.settings.margin.left, 22);
// Footer
var str = "Page " + doc.internal.getNumberOfPages();
doc.setFontSize(10);
// jsPDF 1.4+ uses getWidth, <1.4 uses .width
var pageSize = doc.internal.pageSize;
var pageHeight = pageSize.height
? pageSize.height
: pageSize.getHeight();
doc.text(str, data.settings.margin.left, pageHeight - 10);
}
});
Result: