使用itextsharp从PDF获取fontsize

时间:2013-05-02 04:49:21

标签: c# itextsharp

从PDF中提取文本时,我也需要提取字体大小。首先,我提取了这样的内容:

iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(
  curBaseline[Vector.I1],
  curBaseline[Vector.I2],
  topRight[Vector.I1],
  topRight[Vector.I2]);

在此我无法获得确切的字体大小。之后我尝试使用renderinfo.gs.fontsize;。在这个renderinfo.gs.fontsize中,我会得到一些文本字体大小,但我很少得到确切的字体大小。我将获得的字体大小为“1.0”。谁能告诉我我使用的方法是正确的。如果NO,则使用iTextSharp提取字体大小的其他方法。我使用的是iTextSharp 5.4版本。提前谢谢。

  using System;
    using System.Collections;
  // code java to C# conversion   
    public void renderText(TextRenderInfo renderInfo)
    {
        LineSegment curBaseline = renderInfo.Baseline;
        LineSegment curAscentline = renderInfo.AscentLine;
        Rectangle rect = new Rectangle(curBaseline.StartPoint.get(ArrayList.I1), curBaseline.StartPoint.get(ArrayList.I2), curAscentline.EndPoint.get(ArrayList.I1), curAscentline.EndPoint.get(ArrayList.I2));

        try
        {
            Console.Write("  [{0,6:F2}, {1,6:F2}, {2,6:F2}] \"{3}\" ({4} at {5,6:F2})\n", rect.Width, rect.Height, getEffectiveFontSize(renderInfo), renderInfo.Text, renderInfo.Font.FullFontName[0], getFontSize(renderInfo));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.Write(e.StackTrace);
        }
    }

    float getEffectiveFontSize(TextRenderInfo renderInfo) throws System.ArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException
    {
        Method convertHeight = typeof(TextRenderInfo).getDeclaredMethod("convertHeightFromTextSpaceToUserSpace", float.TYPE);
        convertHeight.Accessible = true;
        return (float?)convertHeight.invoke(renderInfo, getFontSize(renderInfo));
    }

    float getFontSize(TextRenderInfo renderInfo) throws SecurityException, NoSuchFieldException, System.ArgumentException, IllegalAccessException
    {
        Field gsField = typeof(TextRenderInfo).getDeclaredField("gs");
        gsField.Accessible = true;
        GraphicsState gs = (GraphicsState) gsField.get(renderInfo);
        return gs.FontSize;
    }

1 个答案:

答案 0 :(得分:-3)

希望这会有用

`
Font arial = FontFactory.GetFont("Arial", 28, Color.GRAY);
Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, new Color(125, 88, 15));
Font palatino = FontFactory.GetFont("palatino linotype italique",BaseFont.CP1252, BaseFont.EMBEDDED,
  10,
  Font.ITALIC,
  Color.GREEN
  );
Font smallfont = FontFactory.GetFont("Arial", 7);
Font x = FontFactory.GetFont("nina fett");
x.Size = 10;
x.SetStyle("Italic");
x.SetColor(100, 50, 200);`

可用于设置字体大小