ItextSharp水平对齐问题与固定的Y坐标

时间:2022-09-04 21:10:36

I am using ItextSharp lib for writing pdf. I have to print the name of the student on a pdf certificate template. I am not able to center align the student name with fixed y co-ordinate.

我正在使用ItextSharp lib来编写pdf。我必须在pdf证书模板上打印学生的姓名。我无法将学生姓名与固定的y坐标对齐。

 private byte[] CreatePDF2(UserCourseViewModel userCourse)
    {
        PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("/Templates/Certificate.pdf")), null);
        Rectangle size = reader.GetPageSizeWithRotation(1);
        Document doc = new Document(size);

        using (MemoryStream output = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(doc, output);
            doc.Open();


            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page,0,0);
                cb.SetFontAndSize(BaseFont.CreateFont(), 24);
                cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Student Name", (size.Width) / 2, 350, 0);
            }
            finally
            {
                cb.EndText();
            }


            doc.Close();


            return output.ToArray();
        }

The Y-Coordinate seems to be correct by the x coordinate is surely not at the center. I am unable to figure out a way where irrespective of the student name it will always be horizontally centered on the certificate. I am open to any other tool as my requirement is very simple I just need to open the pdf template and write the Student Name on the course certificate. (ITextSharp seems to be too complicated for this task)

Y坐标似乎是正确的x坐标肯定不在中心。我无法找到一种方式,无论学生名称如何,它总是在证书上水平居中。我对任何其他工具持开放态度,因为我的要求很简单我只需要打开pdf模板并在课程证书上写下学生姓名。 (ITextSharp对于此任务似乎太复杂了)

1 个解决方案

#1


0  

This works for me, for aligning a paragraph.

这适用于我,用于对齐段落。

    cb.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

#1


0  

This works for me, for aligning a paragraph.

这适用于我,用于对齐段落。

    cb.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);