iTextSharp Textfield setting the font to Bold

前端 未结 2 1445
有刺的猬
有刺的猬 2021-01-21 02:08

For a textfield object, I would like to change the style to bold. I have already created the arial font since it is not a default font for the BaseFont object. Apparently the Te

相关标签:
2条回答
  • I'm not sure if this will work in all cases, but I created this helper method for adding a form field. It abstracts away calculating upper right X and Y values and also deals with making the font bold.

    It hides some of the nasty implementation details from the caller.

    Credit to @jon-skeet for helping me solving the bold font problem!

            private static void AddFormField(PdfWriter pdfWriter,
                float lowerLeftX,
                float lowerLeftY,
                float width,
                float height,
                string fieldName,
                Font font)
            {
                var upperRightX = lowerLeftX + width;
                var upperRightY = lowerLeftY - height;
                var fontName = font.Style == Font.BOLD ? $"{font.Familyname}-Bold" : font.Familyname;
                var baseFont = BaseFont.CreateFont(fontName, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                var box = new Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
    
                var field = new TextField(pdfWriter, box, fieldName)
                {
                    Font = baseFont,
                    FontSize = font.Size
                };
    
                pdfWriter.AddAnnotation(field.GetTextField());
            }
    
    0 讨论(0)
  • 2021-01-21 02:28

    Have you tried specifying arialbd.ttf as the font name? I think that will give better results anyway, as the bold font will have been tuned.

    (I'm not sure why you can't just specify a Font for a TextField, admittedly...)

    0 讨论(0)
提交回复
热议问题