While replacing a specified syntax with a document I want the main documents Style font everything to be applied

Hello Team,
Currently I have a main document which in turn has some syntaxes those syntax will be replaced with a document that I have done with the help of your Shows how to insert an entire document’s contents as a replacement of a match in a find-and-replace operation. from IReplacingCallback.Replacing | Aspose.Words for .NET
Now I am done with that but now I need the main document’s Style and Font properties to be applied for the replaced content. Could you please help me in achieving that.

Thanks & Regards
Raghul

@Keerthana_K_R When you use DocumentBuildet.InsertDocument method you can specify ImportFormatMode. ImportFormatMode specifies how styles are handled upon importing nodes from one document to another. If formatting in your source document is not specified via styles, then ImportFormatMode will not affect such nodes. You can clear formatting of nodes and reapply styles to make sure all formatting is specified via style. For example for paragraphs you can achieve this using the following code:

// Make sure there is no formatting applied to paragraphs explicitely.
doc.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>().ToList()
    .ForEach(p => { Style s = p.ParagraphFormat.Style; p.ParagraphFormat.ClearFormatting(); p.ParagraphFormat.Style = s; });

In this case if use ImportFormatMode.UseDestinationStyles, formatting will be applied via styles from the destination document.

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "Document insertion destination.docx");

    // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocument.InsertDocumentAtReplace.docx");

}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "Document.docx");

        // Insert a document after the paragraph containing the matched text.
        Paragraph para = (Paragraph)args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the matched text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

/// <summary>
/// Inserts all the nodes of another document after a paragraph or table.
/// </summary>
private static void InsertDocument(Node insertionDestination, Document docToInsert)
{
    if (insertionDestination.NodeType == NodeType.Paragraph || insertionDestination.NodeType == NodeType.Table)
    {
        CompositeNode dstStory = insertionDestination.ParentNode;

        NodeImporter importer =
            new NodeImporter(docToInsert, insertionDestination.Document, ImportFormatMode.KeepSourceFormatting);

        foreach (Section srcSection in docToInsert.Sections.OfType<Section>())
            foreach (Node srcNode in srcSection.Body)
            {
                // Skip the node if it is the last empty paragraph in a section.
                if (srcNode.NodeType == NodeType.Paragraph)
                {
                    Paragraph para = (Paragraph)srcNode;
                    if (para.IsEndOfSection && !para.HasChildNodes)
                        continue;
                }

                Node newNode = importer.ImportNode(srcNode, true);

                dstStory.InsertAfter(newNode, insertionDestination);
                insertionDestination = newNode;
            }
    }
    else
    {
        throw new ArgumentException("The destination node must be either a paragraph or table.");
    }
}

Currently I am not using docmentbuilder I am using this way…
could you please help with this

@Keerthana_K_R In your code ImportFormatMode is specified in NodeImporter's constructor:

NodeImporter importer =
            new NodeImporter(docToInsert, insertionDestination.Document, ImportFormatMode.KeepSourceFormatting);

In your case, ImportFormatMode.KeepSourceFormatting is used.

Yes I tried using KeepDestinationStyles here But didn’t work…

@Keerthana_K_R Please use ImportFormatMode.UseDestinationStyles and perform the source document preprocessing using the code I have provided above. Like this:

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "Document.docx");

        // Make sure there is no formatting applied to paragraphs explicitely.
        subDoc.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>().ToList()
            .ForEach(p => { Style s = p.ParagraphFormat.Style; p.ParagraphFormat.ClearFormatting(); p.ParagraphFormat.Style = s; });

        // Insert a document after the paragraph containing the matched text.
        Paragraph para = (Paragraph)args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the matched text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

Yes @alexey.noskov I tried the same exact way you mentioned but still the replaced document has the same style of its own but I need main documents style to be applied not the style of replaced document style…

I want main documents style to be applied to the replaced document content…Hope I am clear…

@Keerthana_K_R If the source document has an unique style names then such styles will be copied into the destination document. This is expected. Could you please attach your source and destination documents here for testing? We will check them and provide you more information.

Ok I will share

Main Document.docx (11.6 KB)
ReplacingDocument.docx (11.9 KB)

I want main documents style to be applied to the replaced content which is there in ReplacingDocument.

@Keerthana_K_R Formatting in your source document is specified explicitly, not via styles. So it is required to clear formatting. Please try using the following code:

Document doc = new Document(@"C:\Temp\Main Document.docx");
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new InsertDocumentAtReplaceHandler();
doc.Range.Replace("##Syntax for Replacing document##", "", options);
doc.Save(@"C:\Temp\out.docx");
private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(@"C:\Temp\ReplacingDocument.docx");

        // Clear explicit formatting applied to nodes in the source document.
        // Make sure there is no formatting applied to paragraphs explicitely.
        subDoc.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>().ToList()
            .ForEach(p => { Style s = p.ParagraphFormat.Style; p.ParagraphFormat.ClearFormatting(); p.ParagraphBreakFont.ClearFormatting(); p.ParagraphFormat.Style = s; });
        subDoc.GetChildNodes(NodeType.Run, true).Cast<Run>().ToList()
            .ForEach(r => { Style s = r.Font.Style; r.Font.ClearFormatting(); r.Font.Style = s; });

        // Insert a document after the paragraph containing the matched text.
        Paragraph para = (Paragraph)args.MatchNode.ParentNode;
        DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
        builder.MoveTo(para);
        builder.Writeln();
        builder.InsertDocument(subDoc, ImportFormatMode.UseDestinationStyles);

        // Remove the paragraph with the matched text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

Hello @alexey.noskov Its working perfectly fine So could you please explain what we are doing as I find It difficult to understand…

And Thank you soo much for your time😊

@Keerthana_K_R The code clears formatting applied explicitly to paragraphs and runs. In this case nodes uses formatting applied via styles.

Ok so by default Its taking Main documents styles as we cleared the replacing documents style Is my understanding correct…?

@Keerthana_K_R Yes, since ImportFormatMode.UseDestinationStyles mode is used, the styles from the main document are used.

Ok then Thank you so much for your Time😊

1 Like

@alexey.noskov I can see Everytime Calibri (Body) is applied to the Replaced content…Shall I know why but in my main document I used Different Family like Times New Roman…

Paragraph para = (Paragraph)args.MatchNode.ParentNode;
This is the matching element to be replaced like regex exprssion to be replaced with document so shall we get the style of this particular para and apply to the replaced content…?
After clearing the style and font we can do this…
Could you please help on this

@Keerthana_K_R Times New Roman fonts is not applied via style in your document. Since you are inserting content using InsertDocument method content is not inserted as simple text and have it’s own styles applied not the nodes. In the code example above direct formatting applied to the nodes has been cleared, so formatting applied through the styles is used. If you take a look at your destination document, you will see that Normal style uses Calibri font.