Skip to main content
Skip table of contents

How to rotate a paragraph?

Is there a way to add a paragraph with some rotation without having to add the text line by line?

I have a web site where the users upload photos and create photobooks. Also, they can add text at absolute positions, rotations, and alignments. The text can have new lines.

I've been using the iText Library to automatize the creation of the Photobooks Hight Quality PDFs that are printed latter on.

Adding the user uploaded images to the PDFs was really simple, the problem comes when I try to add the text.

In theory what I would need to do, is to define a paragraph of some defined width and height, set the users text, font, font style, alignment (center, left, right, justify), and finaly set the rotation.

For what I've read about Itext, I could create a Paragraph, set the user properties, and use a ColumnText object to set the absolute position, width and height. However it's not possible to set the rotation of anything bigger than single line.

I cant use table cells either, because the rotation method only allow degrees that are multiples of 90.

Is there a way to add a paragraph with some rotation (say 20 degrees) without having to add the text line by line using the ColumnText.showTextAligned() method and all math that involves?

Posted on StackOverflow on Mar 14, 2013 by BernalCarlos

You can do this in a couple of steps:

  • Create a PdfTemplate object; just a rectangle.
  • Draw your ColumnText on this PdfTemplate; don't worry about the rotation, just fill the rectangle with whatever content you want to add to the column.
  • Wrap the PdfTemplate inside an Image object; this is just for convenience, to avoid the math. This doesn't mean your text will be rasterized.
  • Now apply a rotation and an absolute position to the Image and add it to your document.

Your problem is now solved ;-)

If it helps anyone, this is the code i used to solve this problem (thanks to Bruno):

//Create the template that will contain the text
PdfContentByte canvas = pdfWriter.getDirectContent();
PdfTemplate textTemplate = canvas.createTemplate(imgWidth, imgHeight);

ColumnText columnText = new ColumnText(textTemplate);

columnText.setSimpleColumn(0, 0, imgWidth, imgHeight);


//Create de image wrapper for the template
Image textImg = Image.getInstance(textTemplate);

//Asign the dimentions of the image, in this case, the text
textImg.scaleAbsolute(imgWidth, imgHeight);
textImg.setRotationDegrees((float) -textComp.getRotation());
textImg.setAbsolutePosition(imgXPos, imgYPos);

//Add the text to the pdf
JavaScript errors detected

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

If this problem persists, please contact our support.