32

I would like to fill in form fields in a premade PDF doc, but I'm receiving a Null Refrence error with AcroForm when running.

 string fileN4 = TextBox1.Text + " LOG.pdf";

  File.Copy(Path.Combine(textBox4.Text + "\\", fileN4),
               Path.Combine(Directory.GetCurrentDirectory(), fileN4), true);

  // Open the file
  PdfDocument document = PdfReader.Open(fileN4, PdfDocumentOpenMode.Modify);

  PdfTextField currentField = (PdfTextField)(document.AcroForm.Fields["<CASENUM>"]);
  //const 
        string caseName = TextBox1.Text;
  PdfString caseNamePdfStr = new PdfString(caseName);

  //set the value of this field
  currentField.Value = caseNamePdfStr;


  // Save the document...
  document.Save(fileN4);

So PdfTextField currentField = (PdfTextField)(document.AcroForm.Fields["<CASENUM>"]); is where the error happens. It seams that AcroForm is not even recognizing the fields.

Another option would be a find and replace text in a PDF (without using itextsharp as cannot use due to licensing).

Any help would be awesome!

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
user770344
  • 473
  • 2
  • 8
  • 16

6 Answers6

35

You also need this if you are attempting to populate PDF form fields, you also need to set the NeedsAppearances element to true. Otherwise the PDF will "hide" the values on the form. Here is the VB code.

If objPdfSharpDocument.AcroForm.Elements.ContainsKey("/NeedAppearances") = False Then
    objPdfSharpDocument.AcroForm.Elements.Add("/NeedAppearances", New PdfSharp.Pdf.PdfBoolean(True))
Else
    objPdfSharpDocument.AcroForm.Elements("/NeedAppearances") = New PdfSharp.Pdf.PdfBoolean(True)
End If
Marijn
  • 10,367
  • 5
  • 59
  • 80
Marc Ferree
  • 351
  • 3
  • 2
  • 1
    Excellent tip! Thanks heaps I was looking for this everywhere – Daveo Dec 16 '12 at 07:52
  • 9
    For the lazy, here's that in C#: if (doc.AcroForm.Elements.ContainsKey("/NeedAppearances") == false) doc.AcroForm.Elements.Add("/NeedAppearances", new PdfBoolean(true)); else doc.AcroForm.Elements["/NeedAppearances"] = new PdfBoolean(true); – Slothario Jul 14 '16 at 20:16
9

I've been working on this today and I've managed to create a working solution. I've pasted my working code below. The only real differences I can see between my code and the OP's is the following:

  • I included Marc Ferree's code to set NeedAppearances (+1 and Many thanks!!)
  • I set the Text property of the field using a String variable, and not the Value property using a PdfString.

Hopefully this will be of use to somebody trying to do the same.

string templateDocPath = Server.MapPath("~/Documents/MyTemplate.pdf");
PdfDocument myTemplate = PdfReader.Open(templateDocPath, PdfDocumentOpenMode.Modify);
PdfAcroForm form = myTemplate.AcroForm;

if (form.Elements.ContainsKey("/NeedAppearances"))
{
    form.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);
}
else
{
    form.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
}

PdfTextField testField = (PdfTextField)(form.Fields["TestField"]);
testField.Text = "012345";

myTemplate.Save(Server.MapPath("~/Documents/Amended.pdf"));  // Save to new file.
paulH
  • 1,102
  • 16
  • 43
9

I got stuck with this same problem earlier today. However, I think the source code has ?updated, so if you try the method above you are going to get a NullExceptionError. Instead, for TextField you need to generate a PdfString and use testfield.Value instead of .text. Here's an example.

      static PdfAccess()
        {
            Pdf.PdfDocument doc = Pdf.IO.PdfReader.Open(@"C:\...\ Contract.pdf", Pdf.IO.PdfDocumentOpenMode.Modify);
            Pdf.AcroForms.PdfAcroForm form = doc.AcroForm;

            if (form.Elements.ContainsKey("/NeedAppearances"))
            {
                form.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);
            }
            else
            {
                form.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
            }

           var name = (Pdf.AcroForms.PdfTextField)(form.Fields["Email"]);
           name.Value = new Pdf.PdfString("ramiboy");


            doc.Save(@"C:\...\ Contract.pdf");
            doc.Close();

Ramneek Singh
  • 217
  • 3
  • 11
  • 1
    I know this was almost 3 years ago. But this answer was exactly what I needed to understand with PdfSharpCore. Appreciate the answer. – Rod Hartzell Aug 16 '22 at 21:46
6

I have just experienced something similar to this. The first pdf file I opened did not contain acroform data and resulted in a null exception as described above. The issue is not with the opening of the pdf but the reference to the Acroform member variable having a value of null. You can test your pdf using the following code example:

    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        PdfDocument _document = null;
        try
        {
            _document = PdfReader.Open(ofd.FileName, PdfDocumentOpenMode.Modify);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message,"FATAL");
            //do any cleanup and return
            return;
        }

        if (_document != null)
        {
            if (_document.AcroForm != null)
            {
                MessageBox.Show("Acroform is object","SUCCEEDED");
                //pass acroform to some function for processing
                _document.Save(@"C:\temp\newcopy.pdf");
            }
            else
            {
                MessageBox.Show("Acroform is null","FAILED");
            }
        }
        else
        {
            MessageBox.Show("Uknown error opening document","FAILED");
        }
    }

ADENDUM

I also noticed the key in this line of code should not have angle brackets

document.AcroForm.Fields["<CASENUM>"]

Change it to

document.AcroForm.Fields["CASENUM"]
Moog
  • 10,193
  • 2
  • 40
  • 66
  • I tried your code and it does come back "SUCCEEDED". But for some reason I sill getting null ref issues. What did you do it get yours to work? – user770344 Jul 27 '11 at 04:51
  • I added a small update to my solution but I'm not convinced that this would result in a null reference error at the line which you say it is happening.There is an example in the PDFSharp download, but no online. – Moog Jul 27 '11 at 06:55
  • I gave up and used iTextSharp(temporarily) I am currently looking at a hack that uses XDP files to handle the form filling which can read about it here: http://stackoverflow.com/questions/1757397/how-can-i-merge-data-into-an-xdp-file-and-return-a-pdf-via-net – Moog Jul 27 '11 at 06:56
  • I removed the angle brackets, same thing. After looking at what I wrote its actually at `currentField.Value = caseNamePdfStr;` that it throws the Null Ref error – user770344 Jul 27 '11 at 20:39
  • 1
    In that case the problem is that currentField is null. When you try to get the value the program is telling you that it can't find value because doesn't exist. Chances are the field name in your pdf is not "CASENUM". Please note this will be case sensitive – Moog Jul 27 '11 at 22:44
  • Ya i tried multiple ways on making the form in Adobe. I used as the field with and without the angled braces all the way down to something simple as F1. This is driving me nuts. – user770344 Jul 28 '11 at 00:47
  • Please edit your question to hyperlink the PDF file to the first line of text (highlight the words "PDF doc" and press Ctrl+L) – Moog Jul 28 '11 at 07:16
1

The solution to overcome the NullReferenceException is to open your pre-made PDF with Adobe Acrobat and give your form fields a default value, by changing their property-type to be something other than null.

Scott
  • 21,211
  • 8
  • 65
  • 72
Dave
  • 11
  • 1
0

Have you tried putting the current directory in when you try to open it?

Change

PdfDocument document = PdfReader.Open(fileN4, PdfDocumentOpenMode.Modify);

to

PdfDocument document = PdfReader.Open(Path.Combine(Directory.GetCurrentDirectory(), fileN4), PdfDocumentOpenMode.Modify);

I'm pretty sure that PdfReader will need a full file path, although I only use ASPOSE for pdf creation.

Gats
  • 3,452
  • 19
  • 20
  • The textBox4.text is the main path (textBox4.Text + "\\", fileN4). I have also tried just pasting the path for test purposes. Same thing. – user770344 Jun 05 '11 at 02:16
  • Point still stands though. You're copying the file from one path to another and neither of those paths match the one you're trying to open. Have you stepped into it in debug mode and checked that it's actually looking for the file in the right place? As I understand it a null reference will happen when it can't find the file. – Gats Jun 05 '11 at 02:22
  • I tried your code as well and checked debug. Still the same thing and its looking at the proper directory and filename. Also tried altering your code to the following: PdfDocument document = PdfReader.Open(Path.Combine("C:\\Temp\\", fileN4), PdfDocumentOpenMode.Modify); – user770344 Jun 05 '11 at 03:01
  • Not sure what it is then. Could be having trouble with the file or a permissions issue. Is the form file locked with a username/password and does the folder allow .net to read/write to that folder? – Gats Jun 05 '11 at 04:06
  • It shouldn't be locked. The file was created earlier in code by combining two docs into one and saving. That worked. But then reopening or editing from point of saving has an issue with the Null Reference. – user770344 Jun 05 '11 at 04:11
  • Sorry I can't help more then. Not sure what it could be. – Gats Jun 05 '11 at 04:30