title: Adding borders and background color with iTextSharp to PdfFormField
body: <p>I want to add borders and background color to my PdfFormField. Now background color is activated only after I write something to text field but before that it is just white. And I can't get borders to show up.</p>
  
  <p>This is my code:</p>
  
  <pre><code>public void addField(PdfWriter writer, string name, int x, int y, int w, int h, PdfContentByte cb, int maxSize, string text, BaseFont font, int border)
          {
          Rectangle rec = new Rectangle(x, y-h, x+w, y);
          // Change the font Widths
          //BaseFont font = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          float fontSize = 12;
  
          //int[] widths = font.Widths;
          //for (int k = 0; k &lt; widths.Length; k++)
          //{
          //if (widths[k] != 0)
          //widths[k] = width;
          //}
          font.ForceWidthsOutput = true;
          string all = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-*/+.,\"'():;,?./!$+=_{[]}&amp;éèàêîâ";
  
          //Color textColor = BaseColor.RED;
          // Create the Acroform TextField
  
          PdfFormField field = PdfFormField.CreateTextField(writer, PdfFormField.SINGLELINE, PdfFormField.PLAINTEXT, maxSize);
          field.FieldName = name;
          field.DefaultValueAsString = text;
  
          //ield.GetTextField();
          field.MKBackgroundColor = BaseColor.RED;
  
          //field.BackgroundColor = new GrayColor(0.75f);
          //field.BorderColor = GrayColor.GRAYBLACK;
          //field.BorderWidth = 1;
          //field.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
  
          field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
          field.SetPage();
          writer.AddAnnotation(field);
  
          // Position the field on the page
          field.SetWidget(rec, PdfAnnotation.HIGHLIGHT_INVERT);
  
          // Create apperance so the field Size and font match what we want
          PdfAppearance tp = cb.CreateAppearance(rec.Right-rec.Left, rec.Top-rec.Bottom);
          PdfAppearance da = (PdfAppearance)tp.Duplicate;
          da.SetFontAndSize(font, fontSize);
          da.SetColorFill(BaseColor.RED);
          field.DefaultAppearanceString = da;
  
          // Fill the default value of the field
  
          tp.BeginVariableText();
          tp.SaveState();
          tp.Rectangle(rec);
          tp.Clip();
          tp.NewPath();
          tp.BeginText();
          tp.SetFontAndSize(font, fontSize);
          tp.SetColorFill(BaseColor.BLACK);
          tp.SetTextMatrix(100,100);
          tp.ShowText(all);
          tp.SetTextMatrix(2,(rec.Top-rec.Bottom)/2-(fontSize*0.3f));
          tp.ShowText(text);
          tp.EndText();
          tp.RestoreState();
          tp.EndVariableText();
  
          field.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
  }
  </code></pre>