'Rotate text using pdfbox

I'm trying to rotate text using pdfbox by I couldn't achieve it. I tried to set the texMatrix but my text is not rotating as intended.

Does someone have an idea of how I could turn at 90 degrees my text?

This is my code :

contentStream.beginText();

 float tx = titleWidth / 2;
 float ty = titleHeight / 2;

contentStream.setTextMatrix(Matrix.getTranslateInstance(tx, ty)); 
contentStream.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90),tx,ty));
contentStream.setTextMatrix(Matrix.getTranslateInstance(-tx, -ty));

 contentStream.newLineAtOffset(xPos, yPos);

contentStream.setFont(font, fontSize);
contentStream.showText("Tets");
contentStream.endText();

Thank You



Solution 1:[1]

This example rotates around the left baseline of the text and uses the matrix translation to position the text at the specific point. The showText() is always positioned at 0,0, which is the position before the rotation. The matrix translation then positions the text after the rotation.

If you want another rotation point of your text relocation the text rotation position in the contentStream.newLineAtOffset(0, 0)-line

float angle = 35;
double radians = Math.toRadians(angle);
for (int x : new int[] {50,85,125, 200}) 
  for (int y : new int[] {40, 95, 160, 300}) {
    contentStream.beginText();
    
    // Notice the post rotation position
    Matrix matrix = Matrix.getRotateInstance(radians,x,y);
    contentStream.setTextMatrix(matrix);

    // Notice the pre rotation position
    contentStream.newLineAtOffset(0, 0);

    contentStream.showText(".(" + x + "," + y + ")");
    contentStream.endText();
  }

To get the height and the width of the text you want to rotate use font.getBoundingBox().getHeight()/1000*fontSize and font.getStringWidth(text)/1000*fontSize.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JBWanscher