为什么setFieldProperty返回false?

时间:2013-04-11 22:40:29

标签: c# fonts itextsharp

我的代码将文本设置为字段没有问题,但是当我尝试更改字体时,它返回false。我尝试了一些其他字段属性,例如文本大小,结果相同。我做错了什么?

public string Build()
    {
        Font font = FontFactory.GetFont(FontFactory.COURIER, 8f, Font.BOLD);
        foreach (var i in this.pdfFields)
        {
            bool worked = this.acroFields.SetFieldProperty(i.Name, "textfont", font.BaseFont, null);
            worked = this.acroFields.SetField(i.Name, i.Value);
        }//foreach

        this.pdfStamper.FormFlattening = false;
        this.pdfStamper.Close();

        return this.newFile;
    }//Build

附录

    private string templateFile;
    private string newFile;

    private PdfReader pdfReader;
    private PdfStamper pdfStamper;
    private AcroFields acroFields;
    private List<PDFField> pdfFields;

    public PDFer(string templateFile, string newFile)
    {
        this.templateFile = templateFile;
        this.newFile = newFile;

        this.pdfReader = new PdfReader(this.templateFile);
        this.pdfStamper = new PdfStamper(pdfReader, new FileStream(this.newFile, FileMode.Create));
        this.acroFields = pdfStamper.AcroFields;

        this.pdfFields = new List<PDFField>();
    }//PDFer

    public void AddTextField(string name, string value)
    {
        this.pdfFields.Add(new PDFTextField(name, value));
    }//AddTextField

    public void AddCheckBox(string name, bool isChecked)
    {
        this.pdfFields.Add(new PDFCheckBox(name, isChecked));
    }//AddCheckBox

    public float getWidth(string s)
    {
        Chunk c = new Chunk(s);
        return c.GetWidthPoint();
    }//getWidth

1 个答案:

答案 0 :(得分:3)

设置文本大小时,该值必须为Float值。如果它是int,则表示您使用了错误的方法。设置字体时,需要一个真正的BaseFont对象。我认为您的font.BaseFontnull。我会像这样创建BaseFont:

BaseFont.CreateFont(BaseFont.COURIER, BaseFont.WINANSI, BaseFont.EMBEDDED);

请注意,由于COURIER是标准类型1字体之一,因此将忽略EMBEDDED。