iTextSharp ShowTextAligned 锚点

iTextSharp ShowTextAligned Anchor Point

我目前正在使用 iTextSharp 的 ShowTextAligned 方法成功地将文本添加到 PDF。该方法如下所示 (C#):

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

但是,我们不清楚我们正在制作的文本的锚点在哪里。我们提供了 xy,但是它们对应于文本矩形的左上角、左下角还是其他什么?这也受行距影响吗?

我查看了此 website 的文档,但解释性不强。请参阅 PdfContentByte Class/PdfContentByte 方法/ShowTextAligned 方法。

显然锚点取决于对齐方式。如果你的锚点在文本的左侧,说你右对齐是没有意义的。

此外,文本操作通常相对于基线对齐。

因此:

  • 对于左对齐文本,锚点是文本基线的最左边的点。
  • 对于居中对齐的文本,锚点是文本基线的中间点。
  • 对于右对齐文本,锚点是文本基线最右边的点。

更直观:

这是使用以下方法生成的:

[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);
    }
}