Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling PDF-Form-Fields with iTextSharp

Tags:

c#

itext

I try to fill a PDF form with C#. But somehow it does not work. The problem: the fields object (in the line: fields.SetField("Name", "Peter");) seems to be null.

Here is my code:

public static void FillForm()
{
    String pdfTemplate = @"c:\Users\Hagen\Desktop\formular.pdf";
    String newFile = @"c:\Users\Hagen\Desktop\formular_fertig.pdf";
    PdfReader pdfReader = new PdfReader(pdfTemplate);
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
    AcroFields fields = pdfStamper.AcroFields;
    fields.SetField("Name", "Peter");
    pdfStamper.Close();
}
like image 299
user1498095 Avatar asked Aug 09 '26 19:08

user1498095


1 Answers

I remember having a similar problem when I first tried to fill in form fields. The line you have that initializes the pdfStamper;

PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

Try adding ReadWrite permissions to the stamper object like so.

PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create, FileAccess.ReadWrite));

That MIGHT be your problem. I don't recall exactly how I fixed this problem myself, but that is what jumps out to me initially. It may very well be trying to write in the field value, but the stamper doesn't have the FileAccess it requires to accomplish this.

Hope this helps

like image 119
Mike Varosky Avatar answered Aug 11 '26 08:08

Mike Varosky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!