Add a column to PdfPTable, iTextSharp

3.4k Views Asked by At

I'm creating a PDF document using iTextSharp. I see how to create a new table with a number of columns but I can't see anyway to dynamically add a new column. The problem I have is I'm not going to know the number of columns I need straight away, so need to keep adding them

Can somebody please enlighten me or am I going to have to re-create the table each time I need to add a column?

Thanks Mat

3

There are 3 best solutions below

2
On

ITextSharp tables work in a different way to HTML tables (which I guess you're used to).

All you need to tell it is the number of columns you have and then keep adding cells.

Say you create a pdfptable with 5 columns. The 5th cell you add will be on the first row and the 6th cell will be in the 1st column on your 2nd row.

The only downside to this is if you need to add rows where not all the cells are populated but I usually get around this by just adding an empty cell or a cell with a space in it.

0
On

PdfPTable tables are immutable as far as column count goes once created.

The only workaround I can think of is to start with a Whole Bunch of columns and... nope that won't work either. You cannot even add cells to an existing row. I was thinking you could play around with the column spanning to mask your extra columns and adjust them as you added more cells to the rows, but that won't work either.

You must rebuild the table when adding columns. No way around it.

I strongly recommend you figure out how to determine your column count before creating the table in the first place... even if you have to "dry run" through your data. Use some intermediate format (String[][] or whatever) to keep your data, then build the table from that, not the data as it comes to you. Or at least track how many columns you'll need.

Given a huge amount of data, a single pass may not be practical/possible. But rebuilding your whole table several times can't be much better. That's really a performance tuning question that only you have the information to answer.

0
On

Wouldn't it then make sense to create an intermediate model which contains the table you want, and is capable of then creating the PDF table for you?

I know it sounds like a lot of work, but in the long run it should help in that you would be able to dynamically alter the rows and columns as you build them, and then at the end, simply "compile" the table and spit out the PdfPTable object?