iTextSharp ShowTextAligned锚点

Sco*_*y H 6 c# pdf pdf-generation itextsharp

我目前正在使用iTextSharp的ShowTextAligned方法成功地将文本添加到PDF .该方法看起来像这样(C#):

public void ShowTextAligned(
    int alignment,
    string text,
    float x,
    float y,
    float rotation
)
Run Code Online (Sandbox Code Playgroud)

但是,目前还不清楚我们制作的文本的锚点在哪里.我们提供xy,但这些是否对应于文本矩形的左上角,左下角或其他?这也受线间距的影响?

我查看了这个网站上的文档,但它不是很清楚.请参阅PdfContentByte类/ PdfContentByte方法/ ShowTextAligned方法.

mkl*_*mkl 9

显然,锚点取决于对齐的类型.如果您的锚点位于文本的左侧,则说右对齐是没有意义的.

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

从而:

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

更直观:

目视

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

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)