Rotating text using center in itext

社会主义新天地 提交于 2019-12-24 01:08:16

问题


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:


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.



来源:https://stackoverflow.com/questions/17998306/rotating-text-using-center-in-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!