Search code examples
pdf-generationjspdfjspdf-autotable

Add text in header for jspdf if (autoTable Html)


How can we add a text to the top of the pdf? I use autoTable.

 const handleDownloadPdf = async (orientation) => {
    const report = new jsPDF({
        orientation: orientation,
        unit: "pt",
        format: "a4",
    });

    report.autoTable({
        html: refExportExcel,
        margin: 15,
    })
    report.save('Report.pdf');
};

refExportExcel: It is a ref(NextJS) of the table.


Solution

  • You can use the text method before calling the autotable to add text to the topenter image description here

    import "./styles.css";
    import jsPDF from "jspdf";
    import autoTable from "jspdf-autotable";
    
    const handleDownloadPdf = () => {
      const report = new jsPDF({
        unit: "pt",
        format: "a4"
      });
      const refExportExcel = document.getElementById("myTable");
      report.text(20, 20, "This is some text at the top of the PDF.");
      report.autoTable({
        html: refExportExcel,
        margin: 35
      });
      report.save("Report.pdf");
    };
    
    export default function App() {
      return (
        <div className="App">
          <table id="myTable">
            <tr>
              <th>Company</th>
              <th>Contact</th>
              <th>Country</th>
            </tr>
            <tr>
              <td>Alfreds Futterkiste</td>
              <td>Maria Anders</td>
              <td>Germany</td>
            </tr>
            <tr>
              <td>Centro comercial Moctezuma</td>
              <td>Francisco Chang</td>
              <td>Mexico</td>
            </tr>
          </table>
          <button onClick={handleDownloadPdf}>Create</button>
        </div>
      );
    }