[]
        
(Showing Draft Content)

Drawing Tables in PDF

You can also draw tables with PdfDocument class.

To do so, you need to use the rect and stroke methods of the PdfPaths object. You can access the PdfPaths object from the PdfDocument.paths property.


The rect method takes several arguments including the x and y coordinates of the where to begin the rectangle, and width and height dimensions of the rectangle to draw. The stroke can be invoked without parameters to perfoming the drawing of the rectangle path. These two methods can be chained like this:

doc.paths
    .rect(x, y, colWidth, rowHeight)
    .stroke();

The drawText method can also be used to draw text in the cells and define the dimensions of the text. The addPage method is used to add a new page if a row exceeds the page bounds.

Example

This code example creates a table with 50 rows and 3 columns. It also draws text from a data collection into cells of the table as they are created. It accounts for page overflow also

let colWidth = 100, 
    rowHeight = 18, 
    data = getData(50), 
    dataKeyMap = ['id', 'product', 'country'], 
    y = 0;

for (let i = 0; i < 50; i++) {
    for (let j = 0; j < dataKeyMap.length; j++) {
        let x = j * colWidth;
        
        doc.paths
            .rect(x, y, colWidth, rowHeight)
            .stroke();
        
        doc.drawText(data[i][dataKeyMap[j]] + '', x + 2, y + 2, {
            height: rowHeight,
            width: colWidth
        });
    }
    
    y += rowHeight;
    
    if (y >= doc.height) {
        y = 0;
        doc.addPage();
    }
}
Result

pdf-table-page-overflow