Scott H February 2016

iTextSharp ShowTextAligned Anchor Point

I'm currently successfully adding text to a PDF using iTextSharp's ShowTextAligned method. The method looks like this (C#):

public void ShowTextAligned(
    int alignment,
    string text,
    float x,
    float y,
    float rotation
)

However, it is unclear where the anchor point is for the text we're making. We provide x and y, but does these correspond to the upper left corner of the text rectangle, the lower left corner, or something else? Also is this impacted by line spacing?

I looked at the documentation at this website, but it isn't very explanatory. See PdfContentByte Class / PdfContentByte Methods / ShowTextAligned Method.

Answers


mkl February 2016

Obviously the anchor point depends on the kind of alignment. It does not make sense to say you right-align if your anchor point is at the left side of the text.

Furthermore, text operations usually align relative to the baseline.

Thus:

  • For left aligned text the anchor point is the left-most point of the text baseline.
  • For center aligned text the anchor point is the middle point of the text baseline.
  • For right aligned text the anchor point is the right-most point of the text baseline.

More visually:

Visually

This has been generated using:

[Test]
public void ShowAnchorPoints()
{
    Directory.CreateDirectory(@"C:\Temp\test-results\content\");
    string dest = @"C:\Temp\test-results\content\showAnchorPoints.pdf";

    using (Document document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create, FileAccess.Write));
        document.Open();

        PdfContentByte canvas = writer.DirectContent;

        canvas.MoveTo(300, 100);
        canvas.LineTo(300, 700);
        canvas.MoveTo(100, 300);
        canvas.LineTo(500, 300);
        canvas.MoveTo(100, 400);
        canvas.LineTo(500, 400);
        canvas.MoveTo(100, 500);
        canvas.LineTo(500, 500);
        canvas.Stroke();

        ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("Left aligned"), 300, 500, 0);
        ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("Center aligned"), 300, 400, 0);
        ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, new Phrase("Right aligned"), 300, 300, 0);
    }
}

Post Status

Asked in February 2016
Viewed 3,190 times
Voted 11
Answered 1 times

Search




Leave an answer