Rotating text using center in itext

2019-07-17 01:41发布

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);

1条回答
男人必须洒脱
2楼-- · 2019-07-17 02:18

Why are you using beginText(), moveText(), showText(), endText()? Those methods are to be used by developers who speak PDF syntax fluently. Other developers should avoid using those low-level methods, because they are bound to make errors.

For instance: you're using the setFontAndSize() method outside a text object. That method is forbidden in graphics state, you can only use it in text state. Although Adobe Reader will probably tolerate it, Acrobat will complain when doing a syntax check.

Developers who don't speak PDF syntax fluently are advised to use convenience methods as demonstrated in the TextMethods example. Take a look at text_methods.pdf. The text "Away again Center" is probably what you need.

However, there's even an easier way to achieve what you want. Just use the static showTextAligned() method that is provided in the ColumnTextclass. That way you don't even need to use beginText(), setFontAndSize(), endText():

ColumnText.showTextAligned(template,
    Element.ALIGN_CENTER, new Phrase(text), x, y, rotation);

Using the showTextAligned() method in ColumnText also has the advantage that you can use a phrase that contains chunks with different fonts.

查看更多
登录 后发表回答