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.

Mon Apr 10, 2023 11:17 am

Good morning,
can you help me? I need to replace some text strings in doc documents by FieldMergeField ,
i have client templates that has plain text, and I need to replace some words with the correct template parameters.

I've got to create parameters,

Spire.Doc.Document document = new Spire.Doc.Document();
Spire.Doc.Section section = document.AddSection();
Spire.Doc.Documents.Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("<<nombreClienteExpediente>>");
paragraph.AppendField("nombreClienteExpediente", Spire.Doc.FieldType.FieldMergeField);
document.SaveToFile("c:\\plantilla .docx", Spire.Doc.FileFormat.Docx);
document.Close();


but I can't replace plain text with FieldMergeField.



thank you

fernandojimenez
 
Posts: 2
Joined: Mon Apr 10, 2023 11:04 am

Tue Apr 11, 2023 3:34 am

Hi,

Thanks for your inquiry.
Please see the following code for reference.
Code: Select all
            Document doc = new Document();
            doc.LoadFromFile("test.docx");

            TextSelection[] textSelections = doc.FindAllString("<<nombreClienteExpediente>>",true,true);

            foreach (TextSelection text in textSelections)
            {
                TextRange textRange = text.GetAsOneRange();
                Paragraph ownerParagraph = textRange.OwnerParagraph;
                int index = ownerParagraph.ChildObjects.IndexOf(textRange);
                MergeField mergeField = new MergeField(doc);
                mergeField.FieldName = "nombreClienteExpediente";

                ownerParagraph.ChildObjects.Insert(index, mergeField);
                ownerParagraph.ChildObjects.Remove(textRange);
            }

            doc.SaveToFile("result.docx");

If the code does not meet your requirement, please provide us with your test document and describe your requirement more clearly to help us work out an accurate 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 12, 2023 10:27 am

Hi,
Many Many Thanks,
is perfect for me.

its just what i need.

Thanks for your response.

fernandojimenez
 
Posts: 2
Joined: Mon Apr 10, 2023 11:04 am

Thu Apr 13, 2023 1:24 am

Hi,

Thanks for your feedback.
Glad to hear that my code works for your issue. If you have any other questions related to our products, just feel free to contact us.

Have a nice day! :D

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