1

我想为我的 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);
}
4

1 回答 1

1

使用以下代码我希望它有效

PdfFormField field = .......;
field.setMKBorderColor(BaseColor.BLACK);
field.setMKBackgroundColor(BaseColor.BLUE);
于 2018-10-11T06:57:05.680 回答