Extract font height and rotation from PDF files wi

2019-08-29 05:30发布

问题:

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.