Search code examples
c#asposemailmergeaspose.words

Aspose Calling UpdateFields() on document loses mail merge field data


I am trying to export a Word document (link to a sample file which is not working as expected is given below) to PDF using Aspose. https://1drv.ms/w/s!AheHNqR6oXmSmd5H80L0vzCTfVVrTg

The code for the same is as below.

var doc=new Document(<streamFromTheFile>); // Aspose.Words.Document
doc.UpdateFields();// This is required for any possible formula
var outStream=new MemoryStream();
doc.Save(outStream, SaveFormat.Pdf); // Aspose.Words.SaveFormat
File.WriteAllBytes(<exportPdfFilePath>, outStream.ToArray());

Every other files work fine except the ones which has a merge field as in the sample document where even the current value is lost and is replaced by the merge field name like «AtpIssueDate». Taking away the UpdateFields() method call fixes the issue but it cannot be done because it breaks the very logic. Please help how to keep the values of merged fields without removing the UpdateFields() call on export.


Solution

  • You can workaround this problem by using the following code:

    Document doc = new Document("D:\\temp\\so.docx");
    
    // LOCK merge fields before Updatefields method call
    foreach(Field field in doc.Range.Fields)
    {
        if (field.Type == FieldType.FieldMergeField)
        {
            field.IsLocked = true;
        }
    }
    
    doc.UpdateFields();
    
    // UN-LOCK merge fields after Updatefields method call
    foreach (Field field in doc.Range.Fields)
    {
        if (field.Type == FieldType.FieldMergeField)
        {
            field.IsLocked = false;
        }
    }
    
    doc.Save("D:\\temp\\18.10.pdf");
    

    Hope, this helps. I work with Aspose as Developer Evangelist.