【发布时间】:2013-05-02 04:49:20
【问题描述】:
在从 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”。谁能告诉我我使用的方法是正确的。如果否,是否有任何其他方法可以使用 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;
}
【问题讨论】:
-
您还必须考虑当前的转换矩阵,请参阅我的回答 here 中的编辑。
-
@mkl 如果没有错,它在 java 中。我尝试使用 java 将代码转换为 c# 软件,但这是不可能的。任何人都可以帮助使用 csharp 吗
-
如果 c# 中的自省和反射与 Java 中的差异太大,只需复制 iTextSharp 解析器类并将所需的成员和方法公开即可。
-
@mkl 是的,我同意我使用了 render.gs.Fontsize。我在 itextsharp 解析器的 textrenderinfo 类中公开了 gs 我使用了它,但只有少数 PDF 字体 m 能够提取。剩余的 PDF 字体大小为 1.0,非常小。
-
你必须用它来缩放图形状态的字体大小的方法
ConvertHeightFromTextSpaceToUserSpace,也存在于iTextSharp中,也是私有的。也将其公开并使用它。
标签: c# itextsharp