iText - Get Font size and family of a text segment

大憨熊 提交于 2019-12-01 19:54:25
Alexis Pigeon

You can adapt the code provided in this answer, in particular this code snippet:

Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(curBaseline[Vector.I1], curBaseline[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
Single curFontSize = rect.Height;

This answer is in C#, but the API is so similar that the conversion to Java should be straightforward.

Thanks to Alexis I could convert his C# solution into Java code:

text = renderInfo.getText();

Vector curBaseline = renderInfo.getBaseline().getStartPoint();
Vector topRight = renderInfo.getAscentLine().getEndPoint();

Rectangle rect = new Rectangle(curBaseline.get(0), curBaseline.get(1), topRight.get(0), topRight.get(1));
float curFontSize = rect.getHeight();

I had some trouble using Alexis' and Prine's solution, since it doesn't deal with rotated text correctly. So this is what I do (sorry, in Scala):

val x0 = info.getAscentLine.getEndPoint
val x1 = info.getBaseline.getStartPoint
val x2 = info.getBaseline.getEndPoint
val length1 = (x2.subtract(x1)).cross((x1.subtract(x0))).lengthSquared
val length2 = x2.subtract(x1).lengthSquared
(length1, length2) match {
  case (0, 0) => 0
  case _ => length1 / length2
}

If you want the exact fontsize, use the following code in your renderText:

float fontsize = renderInfo.getAscentLine().getStartPoint().get(1)
     - renderInfo.getDescentLine().getStartPoint().get(1);

Modify this as indicated in the other answers for rorated text.

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