Remove Merge Fields from PDF Document

Hi Team,

We have a Merge Type field in our template, and when generating the PDF document, the merge field is not being removed as expected.

We now need to remove merge fields from the generated PDF. Below is the code I’m currently using — could you please confirm if this is the correct approach, or let me know if there’s a better way to handle it?

foreach (Field field in actualDocument.Range.Fields)
{
    if (field.Type == FieldType.FieldMergeField)
    {
        field.Remove();
    }
}

@rahulprajapati

To remove merge fields from a PDF document generated from a template, your current approach is correct. The code snippet you provided iterates through all fields in the document and removes those that are of the type FieldMergeField. Here’s a refined version of your code that ensures clarity and correctness:

foreach (Field field in actualDocument.Range.Fields)
{
    if (field.Type == FieldType.FieldMergeField)
    {
        field.Remove();
    }
}

This code effectively checks each field in the document’s range and removes it if it is identified as a merge field.

If you are still encountering issues with merge fields not being removed as expected, consider the following:

  1. Ensure Document is Updated: After removing the fields, make sure to update the document if necessary. Sometimes, fields may need to be refreshed or the document saved again to reflect changes.

  2. Check for Nested Fields: If your merge fields are nested within other fields or structures, ensure that your logic accounts for those cases.

  3. Document Type: Verify that the document type you are working with supports the operations you are performing.

  4. Debugging: You can add logging or debugging statements to check how many fields are being processed and how many are being removed.

If you continue to face issues, please provide additional details about the specific behavior you are observing, and I can assist you further.

Sources:
[1]: Working with Fields in Aspose.Words
[2]: Working with Fields in Aspose.Words for Java

@rahulprajapati In PDF documents there is no concept of merge field. So you should remove them before converting document to PDF. You can use the following simple code to achieve this:

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.DeleteFields();
doc.Save(@"C:\Temp\out.docx");