Extract font height and rotation from PDF files with iText/iTextSharp

旧街凉风 提交于 2019-12-25 04:30:16

问题


I created some code to extract text and font height from a PDF file using iTextSharp, but does not handle text rotation. How can that information be extracted/computed?

Here is the code:

// 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);
    }
}

回答1:


The information you need, i.e. the text rotation, is not directly available via a TextRenderInfo member but it does have the method

/**
 * 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()

Most likely by text rotation you mean the rotation of this line against a horizontal one. Doing some easy math, therefore, you can calculate the rotation from this LineSegment.

PS: Looking at your code you actually already use the ascent line and descent line. You can use any of these lines as well instead of the base line.



来源:https://stackoverflow.com/questions/19858472/extract-font-height-and-rotation-from-pdf-files-with-itext-itextsharp

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