iTextSharp在页面上居中文本

时间:2016-05-25 12:28:10

标签: itextsharp

我无法将文字置于页面的中心位置。我究竟做错了什么?我已经尝试了几种方法来获取页面,但似乎没有任何方法使文本集中在页面上.....

            BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfReader reader = new PdfReader("C:\\temp\\Certificate12.pdf");
            var pageSize = reader.GetPageSize(1);

            iTextSharp.text.Rectangle rec2 = new iTextSharp.text.Rectangle(PageSize.LETTER);

            PdfStamper stamper = new PdfStamper(reader, stream1);

            PdfContentByte canvas = stamper.GetUnderContent(1);

            canvas.BeginText();
            canvas.SetFontAndSize(bf, 24);

            string nameText = "First Name Last Name";
            int textWidth = (int)nameText.Length;

            int canvasWidth = (int)canvas.PdfDocument.PageSize.Width;
            float xStart = (canvasWidth / 2) - (textWidth / 2);

            canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, nameText, xStart, pageSize.GetTop(Utilities.MillimetersToPoints(145)), 0);

1 个答案:

答案 0 :(得分:0)

首先,如果您将ShowTextAlignedALIGN_CENTER一起使用,iTextSharp会为您设置文本中心,因此您根本不需要处理文本宽度。您只需要告诉它将文本居中于哪个中心点。

因此,您可以将文字放在页面中心,如下所示:

BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
    Rectangle pageSize = reader.GetPageSize(1);
    PdfContentByte canvas = stamper.GetUnderContent(1);

    string nameText = "First Name Last Name";

    canvas.BeginText();
    canvas.SetFontAndSize(bf, 24);
    canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, nameText, (pageSize.Left + pageSize.Right) / 2, pageSize.GetTop(Utilities.MillimetersToPoints(145)), 0);
    canvas.EndText();
}