user3242119
user3242119

Reputation: 43

Create Table in Itext Pdf in java

I am creating a table in PDF in java using itext. I want to place it in top right corner. Here is my code snippet. When I execute the below code, table is aligned in the bottom right of pdf but i want it on Top right corner.

PdfPTable table = new PdfPTable(1);
table.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.setWidthPercentage(160 / 5.23f);
PdfPCell cell = new PdfPCell(new Phrase(" Date" , NORMAL));
cell.setBackgroundColor(BaseColor.BLACK);
cell.setBorderWidth(2f);
table.addCell(cell);
PdfPCell cellTwo = new PdfPCell(new Phrase("10/01/2015"));
cellTwo.setBorderWidth(2f);
table.addCell(cellTwo);

Upvotes: 0

Views: 3502

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

You have omitted the line that actually adds the table to the document.

Suppose that you have:

document.add(table);

In that case, iText will add it at the current position of the cursor. If no content was added yet, the table will be added at the top right. The top right is determined by the top margin and the right margin, but if those aren't 0, you may have the impression that the table isn't added at the top right.

You could also have:

PdfContentByte canvas = writer.getDirectContent();
table.writeSelectedRows(0, -1, document.right() - tablewidth, document.top(), canvas);

However, in that case you'd have to define the width of the table differently:

table.setTotalWidth(tableWidth);

I don't know how wide you want your table. You're using a rather odd formula to define the width percentage.

If this doesn't answer your question, please clarify by updating your question. Currently, it isn't entirely clear what you're doing. Your problem can't be reproduced. See the RightCornerTable example:

enter image description here

If my eyes don't fool me, the table is shown in the top-right corner when I use your code snippet and not in the bottom right as you claim...

Upvotes: 1

Related Questions