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.
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:
More 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With