Write text on existing pdf rotated page

Viewed 68

I am developing an application with iText 7 (7.1.14) to write a text on the top right of existing PDFs. I have a problem with rotated pages, example 90, 270. I tried to apply AffineTransform.getRotateInstance to canvas but nothing.

PdfFont bf = PdfFontFactory.createFont(FontConstants.HELVETICA);
float stringWidth = bf.getWidth(stringa,fontSize);
PdfCanvas canvas=new PdfCanvas(page, true);
float centeredPosition = pageSize.getWidth() - (pageSize.getWidth()/30);
float yCoord = (pageSize.getHeight()-fontSize-5);
float xCoord = centeredPosition-stringWidth;
canvas.beginText().setFontAndSize(bf, fontSize)
    .moveText(xCoord, yCoord)
    .showText(stringa)
    .setTextRenderingMode(pageN)
    .endText();
1 Answers

You want to add text that is displayed at the top right of the page, even after page rotation has been applied to the page.

Make sure you get the page size with the rotation taken into account, so your coordinate calculations are correct for the rotated page:

Rectangle pageSize = page.getPageSizeWithRotation();

For an A4 page with 90 degree rotation, for example, this returns 842x595 instead of 595x842.

Then "ignore" the page rotation when adding new content:

page.setIgnorePageRotationForContent(true);

This essentially applies the appropriate counterrotation for the added text, which cancels out the page rotation, so the text is seemingly not rotated.

Related