We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Style lost after find/replace

Hi, I try to replace a tag field in an word document with another document. Find and replace works fine, but the style is lost. The inserted document must keep the style (font, color, …) of tag from source document. Here is the code used for insert:

public void InsertDocument(Node insertAfterNode, Aspose.Words.Document srcDoc)
    // We need to make sure that the specified node is either pargraph or table.
    if (!((insertAfterNode.NodeType == NodeType.Paragraph) ||
    (insertAfterNode.NodeType == NodeType.Table)))
        throw new ArgumentException("The destination node should be either paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.

    NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document,

    // Loop through all sections in the source document.

    foreach (Section srcSection in srcDoc.Sections)
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
            // Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = srcNode as Paragraph;
            if ((para != null) && para.IsEndOfSection && !para.HasChildNodes)
            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            //((Paragraph)newNode).ParagraphFormat.Style = ((Paragraph)insertAfterNode).ParagraphFormat.Style; 
            //((Paragraph)insertAfterNode).ParagraphFormat.Style = ((Paragraph)newNode).ParagraphFormat.Style;
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;

Seems that the problem is from NodeImporter(srcDoc, insertAfterNode.Document,ImportFormatMode.UseDestinationStyles).

Cosmy G.

Thanks for your inquiry. I think that problem is in the following line of code.

NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.UseDestinationStyles);

It seems that you should use the following line instead this.

NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

I hope that this will help you.
Also see the following link.
Best regards.