Question

Is it possible to add mergefields to an existing .docx document without using interop, only handling with open SDK from CodeBehind?

No correct solution

OTHER TIPS

Yes this is possible, I've created a little method below where you simply pass through the name you want to assign to the merge field and it creates it for you. The code below is for creating a new document but it should be easy enough to use the method to append to an existing document, hope this helps you:

using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\ManualMergeFields.docx", WordprocessingDocumentType.Document))
            {
                package.AddMainDocumentPart();

                Paragraph nameMergeField = CreateMergeField("Name");
                Paragraph surnameMergeField = CreateMergeField("Surname");

                Body body = new Body();
                body.Append(nameMergeField);
                body.Append(surnameMergeField);
                package.MainDocumentPart.Document = new Document(new Body(body));
            }
        }

        static Paragraph CreateMergeField(string name)
        {
            if (!String.IsNullOrEmpty(name))
            {
                string instructionText = String.Format(" MERGEFIELD  {0}  \\* MERGEFORMAT", name);
                SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };

                Run run1 = new Run();

                RunProperties runProperties1 = new RunProperties();
                NoProof noProof1 = new NoProof();

                runProperties1.Append(noProof1);
                Text text1 = new Text();
                text1.Text = String.Format("«{0}»", name);

                run1.Append(runProperties1);
                run1.Append(text1);

                simpleField1.Append(run1);

                Paragraph paragraph = new Paragraph();
                paragraph.Append(new OpenXmlElement[] { simpleField1 });
                return paragraph;
            }
            else return null;
        }
    }
}

You can download the Open Xml Productivity Tool from this url(if you do not already have it)http://www.microsoft.com/download/en/details.aspx?id=5124 This tool has a "Reflect Code" functionality.So you can manually create a merge field in an MS Word document and then open up the document with the Productivity Tool and see a C# code sample on how to do this in code!It's very effective an I've used this exact tool to create the sample above.Good luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top