How to populate a PdfPTable column by column instead of row by row using iText

I use Java with iText to create some PDF files. I need to put text in columns, so I'm trying to use PdfPTable. I create it with:

myTable = new PdfPTable(n); 

n is the number of columns. The problem is that PdfPTable fills the table row by row, that is, you first indicate the cell in column 1 of row 1, then in column 2 of row 1, etc., but I need to do this column by column, because this is how the data is transmitted to me.

I would use Table (which allows you to specify the position), as in http://stderr.org/doc/libitext-java-doc/www/tutorial/ch05.html , but I get the message "can not allow type", and mine Eclipse cannot find the correct import.

Edit: in case my previous explanation is confusing, I want to populate the table in the following order:

 1 3 5 2 4 6 

Instead of this:

 1 2 3 4 5 6 
+4
source share
1 answer

Here is one way: create a PdfPTable with the number of desired columns in your case 3. For each iteration through your data, create a PdfPTable with 1 column. Create 2 PdfPCell objects, one of which contains the data item that you are currently using, and the other that contains the following value in your data. So now you have a PdfPTable with 1 column and two rows. Add PdfPTable to PdfPTable, which has 3 columns. Continue until you have printed all of your data. Better explained with code:

 public class Clazz { public static final String RESULT = "result.pdf"; private String [] data = {"1", "2", "3", "4", "5", "6"}; private void go() throws Exception { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(RESULT)); doc.open(); PdfPTable mainTable = new PdfPTable(3); PdfPCell cell; for (int i = 0; i < data.length; i+=2) { cell = new PdfPCell(new Phrase(data[i])); PdfPTable table = new PdfPTable(1); table.addCell(cell); if (i+1 <= data.length -1) { cell = new PdfPCell(new Phrase(data[i + 1])); table.addCell(cell); } else { cell = new PdfPCell(new Phrase("")); table.addCell(cell); } mainTable.addCell(table); } doc.add(mainTable); doc.close(); } } 
+3
source

All Articles