I am using Java with iText in order to generate some PDFs. I need to put text in columns, so I am trying to use PdfPTable. I create it with:
myTable = new PdfPTable(n);
n
being the number of columns. The problem is that PdfPTable fills the table row by row, that is, you first give the cell in column 1 of row 1, then column 2 of row 1, and so on, but I need to do it column by column, because that is how the data is being fed to me.
I would use a Table
(which lets you specify the position) like in http://stderr.org/doc/libitext-java-doc/www/tutorial/ch05.html, but I get a "could not resolve to a type", and my Eclipse can't find the proper import.
Edit: in case my previous explanation was confusing, what I want is to fill the table in this order:
1 3 5
2 4 6
Instead of this:
1 2 3
4 5 6
Here is one way: Create a PdfPTable with the number of columns desired, in your case 3. For each iteration through your data create a PdfPTable with 1 column. Create 2 PdfPCell objects, one containing the data element you are currently on and the other containing the next value in your data. So now you have a PdfPTable with 1 column and two rows. Add this PdfPTable to the PdfPTable that has 3 columns. Continue that until you've printed all 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();
}
}