6

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.

Scotty H
  • 6,432
  • 6
  • 41
  • 94
  • 1
    See [this question](http://stackoverflow.com/q/30319228/231316) which explains PDF coordinate systems. The short answer is that in most simple PDF the x,y is relative to the lower left corner. – Chris Haas Feb 08 '16 at 23:20

1 Answers1

11

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);
    }
}
mkl
  • 90,588
  • 15
  • 125
  • 265