Copy style from one word document and apply in other word document in C#

Hi Team,

Could you please help me with C# code on hiw to extract style from one document and apply in other document

@Amisha43 You can use Document.CopyStylesFromTemplate to copy all styles from one document to another. Please see our documentation for more information:
https://docs.aspose.com/words/net/working-with-styles-and-themes/#copy-all-styles-from-template

Also, you can use StyleCollection.AddCopy to copy a particular style from the document. For example see the following code:

Document src = new Document(@"C:\Temp\in.docx");

Document dst = new Document();
dst.Styles.AddCopy(src.Styles["MyStyle"]);

DocumentBuilder dstBuilder = new DocumentBuilder(dst);
dstBuilder.ParagraphFormat.StyleName = "MyStyle";
dstBuilder.Write("This text should be bold itelic underlined");

dst.Save(@"C:\Temp\out.docx");

I tried using both options but none worked for me. could you please help me on this. Both sourec and target word file is kept on C drive. Below is the code.

First Tried Code

Document source = new Document(@"C:\File\SourceDocument.docx");
Document target = new Document(@"C:\File\TargetDocument.docx");
target.CopyStylesFromTemplate(source);
target.Save(@"C:\File\TargetDocument.docx");

Second Tried Code

Document srcDoc = new Document();
Style srcStyle = srcDoc.Styles.Add(StyleType.Paragraph, "MyStyle");
srcStyle.Font.Color = Color.Red;
target.Styles.AddCopy(srcStyle);
target.Save(@"C:\File\TargetDocument.docx");

“dstBuilder.Write(“This text should be bold itelic underlined”);” this applies style to new text I want to apply style to already existing text in word file

@Amisha43 dstBuilder.Write("This text should be bold itelic underlined"); was used just for demonstration purposes. You can apply the style to any paragraph in your target document.

Could you please attach your source and target documents along with the expected output document? We will check them and provide oyu more information.

SourceDocument.docx (11.3 KB)
TargetDocument.docx (9.2 KB)

Target File Font should be Arial and size 14 with bold character

@Amisha43 The formatting you have mentioned (Bold Arial 14) is not defined via style in your source document. It is applied explicitly to the Run:

<w:r w:rsidRPr="000B1139">
	<w:rPr>
		<w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/>
		<w:b/>
		<w:sz w:val="28"/>
		<w:szCs w:val="28"/>
	</w:rPr>
	<w:t>Source Document</w:t>
</w:r>

CopyStylesFromTemplate and Styles.AddCopy deals only with styles, they does not work with formatting explicitly set to nodes.

Can you please share me the code on how to apply style through run

@Amisha43 Sure, you can access direct formatting of the Run using Run.Font property. Please see our documentation for more information:
https://docs.aspose.com/words/net/working-with-fonts/