Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Fri Apr 21, 2023 7:51 am

I have a mergefield in document A
I need to replace this mergefield with content of another word document (B)
Any help is appreciated.

hemantahire
 
Posts: 10
Joined: Tue Feb 28, 2023 9:58 am

Sun Apr 23, 2023 7:05 am

Hi,

Thanks for your inquiry.
Please see the following code for your reference.
Code: Select all
            Document doc = new Document();
            doc.LoadFromFile("test1.docx");
            MergeField mergeField = doc.Fields[0] as MergeField;
            Spire.Doc.Documents.Paragraph ownerParagraph = mergeField.OwnerParagraph;
            // get the index of the mergeField in the paragraph
            int index = ownerParagraph.ChildObjects.IndexOf(mergeField);

            Document newDoc = new Document();
            newDoc.LoadFromFile("test2.docx");
            Spire.Doc.Documents.TextSelection[] textSelections = doc.FindAllString("text1", true, true);
            Spire.Doc.Documents.TextSelection textSelection = textSelections[0];
            // get the text of the new document
            TextRange textRange = textSelection.GetAsOneRange();
            // Insert the text at specific position
            ownerParagraph.ChildObjects.Insert(index, textRange);
            // remove the mergeField
            ownerParagraph.ChildObjects.RemoveAt(index);

            doc.SaveToFile("result.docx");
            doc.Dispose();
            newDoc.Dispose();

If the code does not meet your requirement, please share us with your documents so that we can work out a solution for you.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Wed Apr 26, 2023 9:58 am

Hi ,
Thanks for your response.
I tried this code but its breaking with error "Index was outside of bound" after inserting new document
Also below line added by you is searching specific string and returning data

Spire.Doc.Documents.TextSelection[] textSelections = doc.FindAllString("text1", true, true);


In my case i want to read whole document which can contain images only

hemantahire
 
Posts: 10
Joined: Tue Feb 28, 2023 9:58 am

Thu Apr 27, 2023 2:25 am

Hi,

Thanks for your feedback.
Could you please tell me what kind of content do you want to use to replace the merge field or provide us with some screenshots for our reference? So that we can better understand your need and find a solution for you. Thanks for your assistance and understanding.

Best regards,
Triste
E-iceblue support team
User avatar

Triste.Dai
 
Posts: 1000
Joined: Tue Nov 15, 2022 3:59 am

Return to Spire.Doc

cron