Skip to main content
Skip table of contents

How to add a table in the top-right corner of the page?

I'm creating a table in PDF using iText. I want to place it in top right corner.

 Here is my code snippet:

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);
When I execute this code, the table is aligned at the bottom-right of the page, but i want it on top-right corner.

Posted on StackOverflow on Oct 30, 2015 by user3242119

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.

I wrote the RightCornerTable example in an attempt to reproduce:

Table in upper-right corner

Table in upper-right corner

As you can see, I can't reproduce the problem: the table is shown in the top-right corner.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.