为 JSPDF 中的所有屏幕添加 Header 和页脚

Adding Header & Footer for all screens in JSPDF

我正在尝试在下载 PDF 时在所有屏幕中添加 header 和页脚。我使用 jspdf-autotable 添加了带有模拟数据的 table 并且能够下载它。但是 header 只出现在下载的 PDf

的最后一页

我需要一些帮助才能在所有屏幕中获取 Header 和带页码的页脚。请帮忙。

沙箱中的代码:https://codesandbox.io/s/upbeat-cannon-cfiry?file=/src/App.js:0-1257

代码在这里:

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 提供了一个钩子列表,用于自定义 table.

的内容和样式

您可以使用 didDrawPage 挂钩将页眉和页脚添加到您的页面。你可以这样做:

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);
  }
});

结果: