【问题标题】:Extract font height and rotation from PDF files with iText/iTextSharp使用 iText/iTextSharp 从 PDF 文件中提取字体高度和旋转
【发布时间】:2013-11-08 11:51:30
【问题描述】:

我创建了一些代码来使用 iTextSharp 从 PDF 文件中提取文本和字体高度,但不处理文本旋转。如何提取/计算这些信息?

代码如下:

// Create PDF reader
var reader = new PdfReader("myfile.pdf");

for (var k = 1; k <= reader.NumberOfPages; ++k)
{
    // Get page resources
    var page = reader.GetPageN(k);
    var pdfResources = page.GetAsDict(PdfName.RESOURCES);

    // Create custom render listener, processor, and process page!
    var listener = new FunnyRenderListener();
    var processor = new PdfContentStreamProcessor(listener);
    var bytes = ContentByteUtils.GetContentBytesForPage(reader, k);
    processor.ProcessContent(bytes, pdfResources);
}

[...]

public class FunnyRenderListener : IRenderListener
{
    [...]

    void RenderText(TextRenderInfo renderInfo)
    {
        // Get text
        var text = renderInfo.GetText();

        // Get (computed) font size
        var bottomLeftPoint = renderInfo.GetDescentLine().GetStartPoint();
        var topRightPoint = renderInfo.GetAscentLine().GetEndPoint();
        var rectangle = new Rectangle(
            bottomLeftPoint[Vector.I1], bottomLeftPoint[Vector.I2],
            topRightPoint[Vector.I1], topRightPoint[Vector.I2]
        );
        var fontSize = Convert.ToDouble(rectangle.Height);

        Console.WriteLine("Text: {0}, FontSize: {1}", text, fontSize);
    }
}

【问题讨论】:

    标签: c# pdf itextsharp itext pdf-parsing


    【解决方案1】:

    您需要的信息,即文本旋转,不能通过TextRenderInfo 成员直接获得,但它确实有方法

    /**
     * Gets the baseline for the text (i.e. the line that the text 'sits' on)
     * This value includes the Rise of the draw operation - see getRise() for the amount added by Rise
     */
    public LineSegment GetBaseline()
    

    文本旋转很可能是指这条线相对于水平线的旋转。因此,做一些简单的数学运算,您可以从这个LineSegment 计算旋转。

    PS:查看您的代码,您实际上已经使用了上升线和下降线。您也可以使用这些线中的任何一条来代替基线。

    【讨论】:

    • 好的,如果文字被旋转,所有BaseLineAscentLineDescentLine都会被旋转,对吧?
    • 对。顺便说一句,这将使旋转文本的字体大小计算失败。
    • 当然!我已经使用我尝试的一些示例 PDF 看到了错误计算的高度,:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多