I am trying to read in a PDF template with iTextSharp, and then automate filling in the forms. The template was created with LiveCycle Developer. I do not know what is wrong with the following code, but it is not changing the form values.
Could someone please tell me what I am doing wrong? It is difficult to find good documentation for the C# version of iText.
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);
}
}
}
The try/catch never outputs anything.. nor does it set anything
It turns out the code was fine. The problem was that the pdf was dynamic. My code is now almost working since I changed the pdf to be static. I can now read in the AcroFields, which is what was giving me the issue. It is not actually saving the form with the filled in values yet, but here is what I have so far.
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);
}
}