How to Print a List of Items in Rows and Columns in jsPDF
To output a list of text in columns using jsPDF, you can calculate the positioning and column breaks manually. Suppose you want the layout in four columns. Here’s an example:
// Create a new jsPDF instance
const doc = new jsPDF();
// Set the font size and column settings
const fontSize = 12;
const columnWidth = doc.internal.pageSize.getWidth() / 4;
const columnHeight = doc.internal.pageSize.getHeight() - 20; // Adjust as needed
// Define the list of items
const items = [
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
// Add more items as needed
];
// Calculate the number of columns and rows
const numColumns = 4;
const numRows = Math.ceil(items.length / numColumns);
// Loop through the items and position them in columns
let x = 10;
let y = 20;
for (let i = 0; i < items.length; i++) {
const item = items[i];
doc.setFontSize(fontSize);
doc.text(item, x, y);
// Move to the next column or start a new row
if ((i + 1) % numRows === 0) {
x += columnWidth;
y = 20;
} else {
y += columnHeight / numRows;
}
}
// Save the PDF
doc.save('pdf_with_four_columns.pdf');
In this example:
- We create a new instance of
jsPDF
. - We define the
fontSize
for the list items. - We calculate the
columnWidth
by dividing the page width by 4 (since we want four columns). - We define the
columnHeight
as the height of the page minus 20 (to leave some space at the bottom for margins). You can adjust this value as needed. - We define the list of items in the
items
array. - We calculate the
numColumns
as 4 and thenumRows
as the total number of items divided by the number of columns (usingMath.ceil
to round up). - We loop through the items and use the
text()
method to add each item at the current position (x
andy
). We increment the position based on the current column and row. - Finally, we save the PDF using the
save()
method with the desired filename.
By executing this code, a PDF document will be generated with the list of items displayed in four columns. The items will be positioned and divided into columns based on the calculated positioning logic. You can adjust the font size, column width, column height, and other parameters to fit your specific requirements.