使用iTextSharp将边框和背景颜色添加到PdfF​​ormField

时间:2013-04-05 12:13:14

标签: c# colors background itextsharp

我想为我的PdfFormField添加边框和背景颜色。现在,只有在我向文本字段写入内容之后才会激活背景颜色,但在此之前它只是白色。而且我无法出现边界。

这是我的代码:

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 < widths.Length; k++)
        //{
        //if (widths[k] != 0)
        //widths[k] = width;
        //}
        font.ForceWidthsOutput = true;
        string all = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-*/+.,\"'():;,?./!$+=_{[]}&éèàêîâ";

        //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);
}

1 个答案:

答案 0 :(得分:1)

使用以下代码,希望它能起作用

PdfFormField field = .......;
field.setMKBorderColor(BaseColor.BLACK);
field.setMKBackgroundColor(BaseColor.BLUE);