First of all, my license is for DynamicPDF, but I'm upgrading soon to PDF Merger for .Net. My application is actually an ASP.NET MVC 2 application using C# & ASP.Net 3.5.
I'm programmatically setting form field values on the pdf and then calling the Draw() method to get a byte array so I can stream that to the user for download. I've noticed that if you set a form field value for a field that doesn't exist, no error is thrown until you call the Draw() method on the MergeDocument. The error is: Object reference not set to an instance of an object.
I created a helper method to try to protect myself from this, but it still happens on occasion and I can't figure out what field I'm giving a value for that the method doesn't like. See my code below.
/**
* Helper function to set field values on pdf's. The call to .draw() will fail if you
* set a value for a field that does not exist. This method recovers gracefully by logging
* the fact that a field value was not set, but allows the process to proceed without error.
*/
private void setField( ref MergeDocument document, string fieldName, string fieldValue)
{
bool valueWasSet = false;
foreach (ceTe.DynamicPDF.Forms.TextField t in document.Form.GetTextFields())
{
if (t.Name.Equals(fieldName) &&
!document.Form.Fields[t.Name].IsReadOnly )
{
t.Value = fieldValue;
valueWasSet = true;
}
}
//foreach (ceTe.DynamicPDF.Forms.FormField f in document.Form.Fields)
//{
// if (f.Name.Equals(fieldName) && !document.Form.Fields[f.Name].IsReadOnly )
// {
// document.Form.Fields[f.Name].Value = fieldValue;
// valueWasSet = true;
// }
//}
if (!valueWasSet)
{
LogUtil.Write("setField", string.Format("Value was not set for field: {0} and value: {1} because the field name could not be found on the pdf document.", fieldName, fieldValue));
}
}
The full error stacktrace reads:
Message: Object reference not set to an instance of an object. StackTrace: at zz93.gu.a(DocumentWriter A_0)
at ceTe.DynamicPDF.Forms.FormField.Draw(DocumentWriter writer)
at ceTe.DynamicPDF.IO.DocumentResourceList.a(DocumentWriter A_0)
at zz93.ab.v()
at ceTe.DynamicPDF.Document.Draw(Stream stream)
at ceTe.DynamicPDF.Document.Draw()
I'm grasping at straws. I need a safe way to supply form field values for a given field name, but only when the field exists and it's valid to do so.
Thanks!