Need help in copy content from 1 word document 2 word document but styles should be applied of Document 2

Need help in copy content from 1 word document 2 word document but styles should be applied of Document 2 in Aspose word .NET

@ankurkedia If you need to preserve original documents formatting, please try using ImportFormatMode.KeepSourceFormatting. Also, you can additionally specify ImportFormatOptions.ForceCopyStyles property to force Aspose.Words to copy conflicting styles in KeepSourceFormatting mode.

Hi Alexey,

I tried the same code given in example but was unable to achieve this. I need to apply destination style while copying a document to another document.

@ankurkedia Could you please provide you template, source document, current output and expected output documents here along with code that will allow us to reproduce the problem? We will check the issue and provide you more information.

Hi Alexey,

Please find the below snippets:-
I am replacing #TempDoc.docx# keyword from DestinationDocument. from another TempDoc. I want to override the style for tempDoc from DdestimationDocument while replacing.

string DestinationDocument = $@"C:\\temp\\DestDoc.docx";
string tempDocumentPath = $@"C:\\temp\\TempDoc.docx";

Document doc = new Document(templatePath);

// Set find and replace options.
FindReplaceOptions options = new FindReplaceOptions
{
    Direction = FindReplaceDirection.Backward,
    ReplacingCallback = new InsertDocumentAtReplaceHandler()
};

// Call the replace method.
var toBeReplacedTag = string.Format(@"#{0}#", "TempDoc.docx");
doc.Range.Replace(toBeReplacedTag, tempDocumentPath, options);

doc.Save(dataDir + "DestinationDocumentUpdated.docx");

@ankurkedia Could you please attach your input documents, current and expected output documents here for our reference?

Please find the documentDestinationDocument.docx (13.2 KB)
ToBeReplaced.docx (13.3 KB)
FinalOutput.docx (13.6 KB)

Hi @alexey.noskov, I tried using example given in website. But this was also not working. can u please help me

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = dataDir + "template.docx";
Document doc = new Document(fileName);

// Open the document.
Document target = new Document(dataDir + "TestFile.doc");
target.CopyStylesFromTemplate(doc);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);

@ankurkedia Formatting in your source document is explicitly applied to the nodes (paragraphs and runs):

<w:p w14:paraId="24C5051D" w14:textId="77777777" w:rsidR="005A2686" w:rsidRPr="005A2686" w:rsidRDefault="005A2686" w:rsidP="00FD1388">
	<w:pPr>
		<w:jc w:val="center"/>
		<w:rPr>
			<w:rFonts w:ascii="Algerian" w:hAnsi="Algerian" w:cs="Arial"/>
			<w:b/>
			<w:color w:val="00CC00"/>
		</w:rPr>
	</w:pPr>
	<w:r w:rsidRPr="005A2686">
		<w:rPr>
			<w:rFonts w:ascii="Algerian" w:hAnsi="Algerian" w:cs="Arial"/>
			<w:b/>
			<w:color w:val="00CC00"/>
		</w:rPr>
		<w:t>Hi.</w:t>
	</w:r>
</w:p>

if you need to discard this formatting while inserting the document, you can clear it before inserting. For example see the following code:

Document dst = new Document(@"C:\Temp\DestinationDocument.docx");

Document src = new Document(@"C:\Temp\ToBeReplaced.docx");
// Clear formatting of the source document.
src.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>().ToList()
    .ForEach(p => { p.ParagraphFormat.ClearFormatting(); p.ParagraphBreakFont.ClearFormatting(); });
src.GetChildNodes(NodeType.Any, true).Where(n => n is Inline).Cast<Inline>().ToList()
    .ForEach(i => i.Font.ClearFormatting());

ReplaceEvaluatorFindAndReplaceWithDocument evaluator = new ReplaceEvaluatorFindAndReplaceWithDocument();
evaluator.ReplacementDocument = src;

// Set find and replace options.
FindReplaceOptions options = new FindReplaceOptions
{
    Direction = FindReplaceDirection.Backward,
    ReplacingCallback = evaluator
};

dst.Range.Replace("#ToBeReplaced.docx#", "", options);

dst.Save(@"C:\Temp\out.docx");
internal class ReplaceEvaluatorFindAndReplaceWithDocument : IReplacingCallback
{
    /// <summary>
    /// This method is called by the Aspose.Words find and replace engine for each match.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document doc = (Document)e.MatchNode.Document;

        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;

        // 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);

        // This array is used to store all nodes of the match for further deleting.
        List<Run> runs = new List<Run>();

        // 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((Run)currentNode);
            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((Run)currentNode);
        }

        // Create DocumentBuilder to insert HTML.
        DocumentBuilder builder = new DocumentBuilder(doc);
        // Move builder to the first run.
        builder.MoveTo(runs[0]);
        // Insert document.
        builder.InsertDocument(ReplacementDocument, ImportFormatMode.UseDestinationStyles);

        // Delete matched runs
        foreach (Run run in runs)
            run.Remove();

        // Remove empty paragraph if any.
        if(string.IsNullOrEmpty(builder.CurrentParagraph.ToString(SaveFormat.Text).Trim()))
        {
            builder.CurrentParagraph.Remove();
        }

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

    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        run.ParentNode.InsertAfter(afterRun, run);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring((0), (0) + (position));
        return afterRun;
    }

    public Document ReplacementDocument { get; set; }
}

Here is the output: out.docx (10.5 KB)