开发者

PDFSharp filling in form fields

开发者 https://www.devze.com 2023-03-10 17:14 出处:网络
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.

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 re开发者_开发百科cognizing 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!


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


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.


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();


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"]


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消