aduffy
November 30, 2022, 2:37am
1
Hi,
I have working code below using aspose.word… it merges the incoming values nicely into the document and saves correctly.
However… the end user can still hit Alt + F9 and see the merge fields on the outputted document… how can I remove them from the outputted document?
I’ve been playing around with unlink for a few hours… but no luck yet. Not even sure that’s what I should use.
using (var ms = new MemoryStream())
{
streamOfFileFromWherever.CopyTo(ms);
Document doc = new Document(ms);
doc.MailMerge.Execute(mergeFieldNames, mergeFieldValues);
doc.MailMerge.MergeWholeDocument = true;
doc.MailMerge.CleanupOptions = (MailMergeCleanupOptions.RemoveUnusedRegions | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveEmptyParagraphs | MailMergeCleanupOptions.RemoveEmptyTableRows);
MemoryStream ms2 = new MemoryStream();
doc.Save(ms2, SaveFormat.Docx);
ms2.Position = 0;
// save stream to cloud......
}
@aduffy You should specify mail merge options before exacting mail merge. Please try changing you code like this:
// 1. Set pame merge options
doc.MailMerge.MergeWholeDocument = true;
doc.MailMerge.CleanupOptions = (MailMergeCleanupOptions.RemoveUnusedRegions | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveEmptyParagraphs | MailMergeCleanupOptions.RemoveEmptyTableRows);
// 2. Execute mail merge.
doc.MailMerge.Execute(mergeFieldNames, mergeFieldValues);
If the problem still persist, please attach your sample template and the output document here for testing.
aduffy
December 1, 2022, 3:41am
3
Yes good point… but I’m still wondering the answer to my actual question… the mail merge options was incorrect and I’ve fixed… but my actual question was around unlinking merge fields in the resultant document
@aduffy If you would like to unlink unmerged merge fields in your document, you can use code like this:
// Unlink all mergefields in the document.
doc.Range.Fields.Where(f => f.Type == FieldType.FieldMergeField).ToList().ForEach(f => f.Unlink());
If you need to remove unmerged fields, you can either use CleanupOptions
as you already do, or by calling the following code:
doc.MailMerge.DeleteFields();
aduffy
December 1, 2022, 5:55am
5
Ok cool… I’ll do that… can I also unlink merged merge fields?
@aduffy After execution mail merge the merge fields are replaced with their values, so there is no need to unlink the merged merge fields, since they are already unlinked.
1 Like