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 Mar 07, 2011 11:59 am

How can i get the result as expected in the attachment by replacing text.

Currently im using the code below:
Document document = new Document();
document.LoadFromFile(@"C:\Work\Input.docx");
document.Replace("#ThePlaceholder#", "1. Line\tsome Text\r\n2. Line\tother Text", true, true);
document.SaveToFile(@"C:\Work\Output.docx", FileFormat.Docx);

softecregistrierung
 
Posts: 22
Joined: Mon Mar 07, 2011 9:35 am

Tue Mar 08, 2011 6:44 am

Hi,

Thanks for your inquiry.
Please try:
Code: Select all
Document doc = new Document(@"..\..\Input.docx", FileFormat.Docx);
TextSelection[] selections = doc.FindAllString("#ThePlaceholder#", true, true);
foreach (TextSelection selection in selections)
{
    TextRange text = selection.GetAsOneRange();
    Paragraph p = text.OwnerParagraph;
    text.Text = "1. Line\tsome Text";

    //append new paragraph
    Paragraph p2 = p.OwnerTextBody.AddParagraph();
    p2.AppendText("2. Line\tother Text");

    //move p2
    int index = p.OwnerTextBody.Paragraphs.IndexOf(p);
    p.OwnerTextBody.Paragraphs.Insert(index + 1, p2);

    //apply list
    p2.ListFormat.ContinueListNumbering();
}
doc.SaveToFile("Output.docx", FileFormat.Docx);
Harry
Technical Support / Developer,
e-iceblue Support Team
User avatar

harry.support
 
Posts: 180
Joined: Mon Nov 08, 2010 3:11 pm

Wed Mar 16, 2011 8:05 am

Hi,
What do you think about my solution?
While testing i realized, that everything is working when there is a space at the end of the paragraph.
Because the placeholder can be everywhere in the document (can also be a numbering list) and should always keep the paragraph settings, it is working with the code below.

Code: Select all
Document document = new Document();
document.LoadFromFile(@"C:\Work\OpenXML\Input.docx");
TextSelection[] selections = document.FindAllString("#ThePlaceholder#", true, true);
foreach (TextSelection selection in selections)
{
   TextRange text = selection.GetAsOneRange();
   
   if (text.Text.EndsWith("#ThePlaceholder#"))
   {
       text.OwnerParagraph.AppendText(" ");
   }
}
document.Replace("#ThePlaceholder#", "1. Line\tsome Text\r\n2. Line\tother Text", true, true);
document.SaveToFile(@"C:\Work\OpenXML\Output.docx", FileFormat.Docx);

softecregistrierung
 
Posts: 22
Joined: Mon Mar 07, 2011 9:35 am

Wed Mar 16, 2011 9:38 am

Oh, Thank you my friend. You share me a great solution. You easily keep the paragraph settings.
Harry
Technical Support / Developer,
e-iceblue Support Team
User avatar

harry.support
 
Posts: 180
Joined: Mon Nov 08, 2010 3:11 pm

Return to Spire.Doc