0

我正在尝试使用 iTextSharp 阅读 PDF 模板,然后自动填写表格。该模板是使用 LiveCycle Developer 创建的。我不知道下面的代码有什么问题,但它并没有改变表单值。

有人可以告诉我我做错了什么吗?很难为 iText 的 C# 版本找到好的文档。

private void button_fill_Click(object sender, EventArgs e)
{
     OpenFileDialog ofd = new OpenFileDialog();
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         using (MemoryStream ms = new MemoryStream())
         {
             PdfReader pdfReader = new PdfReader(ofd.FileName);
             PdfStamper pdfStamp = new PdfStamper(pdfReader, ms);
             AcroFields fields = pdfStamp.AcroFields;
             foreach (KeyValuePair<string, AcroFields.Item> f in fields.Fields)
             {
                 // this message is never displayed
                 MessageBox.Show("key: " + f.Key);  
             }

             //textfields
             // this one is working, and showing the value saved in the template
             MessageBox.Show("FakeDatabase_Table1_Company: " + fields.GetField("FakeDatabase_Table1_Company")); 
             // this part returns a false value, and not changing the field
             MessageBox.Show("Set: " + fields.SetField("FakeDatabase_Table1_Company", "Testing")); 

             try
             {
                 fields.SetField("FakeDatabase_Table1_Company", "Coca-Cola");
             }
             catch (Exception e2) { MessageBox.Show(e2.Message); }

             pdfReader.Close();
             pdfStamp.FormFlattening = true;
             pdfStamp.FreeTextFlattening = true;
             pdfStamp.Writer.CloseStream = false;
             pdfStamp.Close();
             Process.Start(ofd.FileName);
        }
    }
}

try/catch 从不​​输出任何东西.. 也没有设置任何东西

4

1 回答 1

0

事实证明代码很好。问题是pdf是动态的。自从我将 pdf 更改为静态后,我的代码现在几乎可以工作了。我现在可以在 AcroFields 中阅读,这就是给我带来问题的原因。它实际上并没有保存带有填充值的表单,但这是我到目前为止所拥有的。

public void loadPDF(String path)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                PdfReader pdfReader = new PdfReader(path);
                PdfStamper pdfStamp = new PdfStamper(pdfReader, ms);
                AcroFields fields = pdfStamp.AcroFields;
                List<String> Keys = new List<string>();
                Boolean empty = true;
                foreach (var field in fields.Fields)
                {
                    empty = false;
                    Keys.Add(field.Key);
                }
                if (empty) MessageBox.Show("The template does not have any form fields in it.");
                foreach (String k in Keys)
                {
                    fields.SetField(k, "Testing");
                }

                pdfReader.Close();
                pdfStamp.FormFlattening = true;
                pdfStamp.FreeTextFlattening = true;
                pdfStamp.Writer.CloseStream = false;
                pdfStamp.Close();
                Process.Start(path);
            }
        }
于 2012-07-07T20:09:01.227 回答