Skip to main content
Skip table of contents

How to rotate a single line of text?

How do I rotate text using the central point?

I'm converting a document which is created with a online editor. I need to be able to rotate the text using it's central point and not (0,0).

Since Image rotates using the centre I assumed this would work but it doesn't. Anyone has a clue how to rotate text using the central point in itext?

 

float fw = bf.getWidthPoint(text, textSize);
float fh = bf.getAscentPoint(text, textSize)
    - bf.getDescentPoint(text, textSize);
PdfTemplate template = content.createTemplate(fw, fh);
 
Rectangle r = new Rectangle(0,0,fw, fw);
r.setBackgroundColor(BaseColor.YELLOW);
template.rectangle(r);
 
template.setFontAndSize(bf, 12);
template.beginText();
template.moveText(0, 0);
template.showText(text);
template.endText();
 
Image tmpImage = Image.getInstance(template);
tmpImage.setAbsolutePosition(Utilities.millimetersToPoints(x),
    Utilities.millimetersToPoints(
        pageHeight - (y + Utilities.pointsToMillimeters(fh))));
tmpImage.setRotationDegrees(0);
document.add(tmpImage);

 

Posted on StackOverflow on Aug 1, 2013 by user1236552

The easiest way to achieve this is to use showTextAligned() method that is provided in the Canvas class. The second and the third arguments are the coordinates of the central point of your text and the last argument is the rotation angle. Please note that it is not about PdfCanvas class, there we use beginText(), moveText(), showText(), endText(), etc.

PdfPage page = pdfDoc.addNewPage();
PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
new Canvas(canvas, pdfDoc, page.getPageSize())
        .showTextAligned("CONFIDENTIALLY", 100, 50, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);

Click How to rotate a single line of text? if you want to see how to answer this question in iText 5.

JavaScript errors detected

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

If this problem persists, please contact our support.