Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
Scotty H Avatar asked Feb 08 '16 21:02

Scotty H


1 Answers

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);
    }
}
like image 100
mkl Avatar answered Sep 27 '22 19:09

mkl