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

Tags: tablesposition tableiText 7

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

In iText 7 PdfPTable and PdfPCell classes don’t exist anymore. Use Table and Cell instead.

I wrote the RightCornerTable example in an attempt to reproduce your problem:

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.

This is my code adapted for iText 7:

public void createPdf(String dest) throws Exception {
 
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc, new PageSize(300, 300));
    doc.setMargins(0, 0, 0, 0);
 
    Table table = new Table(1);
    table.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    table.setWidth(90);
    Cell cell = new Cell().add(new Paragraph(" Date").setFontColor(Color.WHITE));
    cell.setBackgroundColor(Color.BLACK);
    cell.setBorder(new SolidBorder(Color.GRAY, 2));
    table.addCell(cell);
    Cell cellTwo = new Cell().add(("10/01/2015"));
    cellTwo.setBorder(new SolidBorder(2));
    table.addCell(cellTwo);
    doc.add(table);
    doc.add(new AreaBreak());
    doc.add(table);
 
    doc.close();
}

Note that we add a table using:

doc.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 use:

table.setFixedPosition(ps.getWidth() - doc.getRightMargin() - totalWidth, ps.getHeight() - doc.getTopMargin() - totalHeight, totalWidth);

In this case you need to know the total height and width of the table. Try to manipulate with table renderer a bit:

PageSize ps = pdfDoc.getDefaultPageSize();
IRenderer tableRenderer = table.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult tableLayoutResult =
        tableRenderer.layout(new LayoutContext(new LayoutArea(0, new Rectangle(ps.getWidth(), 1000))));
float totalHeight = tableLayoutResult.getOccupiedArea().getBBox().getHeight();

Click this link if you want to see how to answer this question in iText 5.