How to Create a Table using jsPDF

Use jspdf-autotable library

To create a table in jsPDF, you can use the doc.autoTable() function. Here’s an example that demonstrates how to generate a simple table:

// Create a new jsPDF instance
const doc = new jsPDF();

// Define the table columns and rows
const columns = ["Name", "Age", "Country"];
const rows = [
  ["John Doe", 30, "USA"],
  ["Jane Smith", 25, "Canada"],
  ["Bob Johnson", 40, "UK"],
];

// Set the table options
const options = {
  startY: 20, // Vertical position to start the table (in mm)
};

// Generate the table
doc.autoTable(columns, rows, options);

// Save the PDF
doc.save('table.pdf');

In this example, we create a new instance of jsPDF. We define the table columns as an array of strings (columns) and the table rows as a 2D array (rows), where each inner array represents a row of data.

We set the table options using the options object. In this case, we specify startY to set the vertical position of the table. You can adjust this value to position the table where desired.

The doc.autoTable() function is used to automatically generate the table based on the provided columns, rows, and options.

Finally, we save the generated PDF file using doc.save('table.pdf').

By executing this code, a PDF document with a simple table will be generated and saved as “table.pdf”. The table will display the provided data with the specified columns and rows. You can modify the columns, rows, and table options to fit your specific requirements.

Add jspdf-autotable library

To add the jspdf-autotable library to your JavaScript project, you need to include the library script file in your HTML file. Here’s an example of the complete JavaScript code that includes the jspdf-autotable library:

<!DOCTYPE html>
<html>
<head>
  <title>Using jsPDF with autoTable</title>
</head>
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.0/jspdf.umd.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.14/jspdf.plugin.autotable.min.js"></script>
  <script>
    // Create a new jsPDF instance
    const doc = new jsPDF();

    // Define the table columns and rows
    const columns = ["Name", "Age", "Country"];
    const rows = [
      ["John Doe", 30, "USA"],
      ["Jane Smith", 25, "Canada"],
      ["Bob Johnson", 40, "UK"],
    ];

    // Set the table options
    const options = {
      startY: 20, // Vertical position to start the table (in mm)
    };

    // Generate the table
    doc.autoTable(columns, rows, options);

    // Save the PDF
    doc.save('table.pdf');
  </script>
</body>
</html>

In this example, we include the necessary <script> tags within the HTML file to import both the jspdf library and the jspdf-autotable plugin. The URLs provided in the <script> tags point to the latest versions of the libraries from a CDN (Content Delivery Network).

Then, within the <script> block, we proceed with the rest of the code. It follows the same structure as mentioned before, using the jsPDF instance, defining the table columns and rows, setting the options, generating the table with doc.autoTable(), and saving the PDF with doc.save().

By running this complete code in an HTML file, the jspdf-autotable library will be successfully imported, and the PDF document with the table will be generated and saved as “table.pdf”.

Use the Drawing Functions of jsPDF

If you prefer to output a table without using the jspdf-autotable library, you can manually format and draw the table using the drawing functions provided by jsPDF. Here’s an example of how to create a basic table without the jspdf-autotable library:

// Create a new jsPDF instance
const doc = new jsPDF();

// Define the table headers and data
const headers = ["Name", "Age", "Country"];
const data = [
  ["John Doe", "30", "USA"],
  ["Jane Smith", "25", "Canada"],
  ["Bob Johnson", "40", "UK"],
];

// Set the table starting position
let y = 20;

// Set the column widths
const columnWidths = [60, 20, 40];

// Set the table styles
const headerStyle = { fillColor: "#000000", textColor: "#ffffff" };
const rowStyle = { fillColor: "#f2f2f2" };

// Draw the table headers
headers.forEach((header, index) => {
  doc.setFillColor(headerStyle.fillColor);
  doc.setTextColor(headerStyle.textColor);
  doc.setFontStyle("bold");
  doc.rect(y, 10, columnWidths[index], 10, "F");
  doc.text(header, y + 2, 15);
  y += columnWidths[index];
});

y = 20;

// Draw the table rows
data.forEach((row) => {
  row.forEach((cell, index) => {
    doc.setFillColor(rowStyle.fillColor);
    doc.setTextColor(0, 0, 0);
    doc.setFontStyle("normal");
    doc.rect(y, 20, columnWidths[index], 10, "F");
    doc.text(cell, y + 2, 25);
    y += columnWidths[index];
  });
  y = 20;
});

// Save the PDF
doc.save("table.pdf");

In this example, we define the table headers in the headers array and the table data in the data array.

We set the starting position of the table with y = 20. The columnWidths array specifies the width of each column.

Next, we define the styles for the table headers (headerStyle) and table rows (rowStyle).

We iterate over the headers and draw the header cells using doc.rect() and doc.text() functions. Similarly, we iterate over each row of data, draw the row cells, and populate the cell content using the same functions.

Finally, we save the generated PDF file using doc.save('table.pdf').

By executing this code, a PDF document with a manually formatted table will be generated and saved as “table.pdf”. You can adjust the column widths, table styles, and other aspects of the table to suit your specific requirements.

Drawing Rectangle

The doc.rect() function in jsPDF is used to draw rectangles on the PDF document. It takes several parameters to define the position, size, and style of the rectangle. Here are the parameters used in the example:

javascriptCopy codedoc.rect(x, y, width, height, style);
  • x: The x-coordinate of the starting point of the rectangle.
  • y: The y-coordinate of the starting point of the rectangle.
  • width: The width of the rectangle.
  • height: The height of the rectangle.
  • style: The style of the rectangle. It can be specified as "F" (fill), "S" (stroke), or "DF" (fill and stroke).

In the example code provided, doc.rect() is used to draw the table cells. The y parameter represents the vertical position of the top-left corner of the rectangle, and the width and height parameters determine the size of each cell. The style parameter is set to "F" to fill the rectangle with the specified color.

You can adjust the values of x, y, width, height, and style according to your specific requirements to draw rectangles of different sizes, positions, and styles in your PDF document.

To set the stroke width (line thickness) when using the doc.rect() function in jsPDF, you can use the setLineWidth() method provided by jsPDF. Here’s an example:

const strokeWidth = 1; // Desired width in points (default 0.2)
// Set the stroke width
doc.setLineWidth(strokeWidth);

Comments

comments