Replace text in Word document (multiple times)

Hi,

We are developing a solution to a customer where we want to achieve the following:

Adding text to a document body from a custom application.
The word template has bookmarks as placeholder where we like text to be inserted from the custom application.
The finalized Word-file will be edited by a end-users.
The finalized Word-file needs to be updated again from a custom application without losing the edits the end-users have done (assuming that the end-users doesn´t change the bookmarks or texts in the bookmarks).

Are there any examples how to achieve this with Aspose.Word?

Regards // Henrik

@henrikcompagoab

Yes, you can modify the Word documents according to your requirement using Aspose.Words. Could you please ZIP and attach your input and expected output documents here for our reference? We will then provide you more information about your query along with code.

aspose sample document source.zip (242.1 KB)

I have attached an example. What we are looking for is code samples how to insert content into placeholders (field or bookmarks) with the possibility to load the file again and replace with updated content, thus without desttoying the placeholders when adding content the first time.

Regards // Henrik

@henrikcompagoab

We suggest you please read the following articles.
Use DocumentBuilder to Insert Document Elements
Using DocumentBuilder to Modify a Document Easily
Find and Replace

In your case, we suggest you please implement IReplacingCallback interface, find the placeholder, and insert the desired content. Please check the following code example and write your code to insert text, image, table at the place of “Write your code here…”.

Document doc = new Document(MyDir + "in.docx");

FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new FindAndInsertContent();

doc.Range.Replace(@"<SALESPRICECONTENT>", "", options); 
doc.Save(MyDir + "output.docx");

public class FindAndInsertContent : IReplacingCallback
{
    DocumentBuilder builder;
    public FindAndInsertContent()
    {
    }

    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;

        if (builder == null)
            builder = new DocumentBuilder((Document)currentNode.Document);

        // The first (and may be the only) run can contain text before the match, 
        // in this case it is necessary to split the run.
        if (e.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while (
            (remainingLength > 0) &&
            (currentNode != null) &&
            (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;

            // Select the next Run node. 
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add(currentNode);
        }

        Run run = (Run)runs[0];
        builder.MoveTo(run);

        //Write your code here....
        //Write your code here....
                

        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }

    /// <summary>
    /// Splits text of the specified run into two runs.
    /// Inserts the new run just after the specified run.
    /// </summary>
    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring(0, position);
        run.ParentNode.InsertAfter(afterRun, run);
        return afterRun;
    }
}

Hi and thanks for the suggestion.

This will replace the content for the first run, but I need to open the document again later and make the same replacement again (with other content). Doesn´t the text “SALESPRICECONTENT” get replaced in the first run and wouldn´t be able to find it the second time?

Regards // Henrik

@henrikcompagoab

Please read the following article about finding the text and replace it with other content.
Find and Replace

If there are multiple instances of of SALESPRICECONTENT, they will be replaced. Moreover, you need to modify the code of FindAndInsertContent class according to your requirement.

If you still face problem, please ZIP and attach your input and expected output documents. We will then provide you more information about your query.

Hi Tahir,

Thanks for the update but I need to elaborate more to explain this.

Day 1: Our application loads the Word template with the placeholdes. Add content to the placeholders. Saves the document and make it available to the end-users.

Day 2: End-users opens the document in Word. Adds texts and images to different places in the document (not the places which we added content to in Day 1).

Day 3: Our application opens the documenet modified in Day 2. The application replace content in the placeholders (which was filled with content Day 1 for the first time) but does not modify any content the end-user added on Day 2. Our application saves the document again and the End-user can open the modified document.

How can we maintain placeholders during this cycle, so an application can add content for Day 1 and Day 3?
The question is not to have a multiple “PLACEHOLDER” but how to use field/bookmarks for replacing content on multiple occassions.

Regards // Henrik

@henrikcompagoab

In this case, we suggest you please insert the bookmark at the place of placeholder while replacing the content. When you load the document second time, you can find the replaced content using bookmark.