Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different styling in a line in wordprocessing with opxnxml in c#

I have used codes below to apply two different character style to the two runs of one paragraph:

            Paragraph heading = new Paragraph();
            ParagraphProperties heading_pPr = new ParagraphProperties();
            heading.Append(heading_pPr);

            Run Run1 = new Run() { RsidRunProperties = "009531B2" };
            Text Text_Run1 = new Text("THIS IS TEST RUN 1");
            Run1.Append(Text_Run1);
            RunProperties rpr_Run1 = new RunProperties();
            rpr_Run1.RunStyle = new RunStyle() { Val = "CharacterStyle1" };

            Run Run2 = new Run();
            RunProperties rpr_Run2 = new RunProperties();
            rpr_Run2.RunStyle = new RunStyle() { Val = "CharacterStyle2" };
            Text text_Run2 = new Text("THIS IS TEST RUN 2");
            Run2.Append(text_Run2);

            heading.Append(Run1);
            heading.Append(Run2);
            body.Append(heading);

But after running the code, In the word file these runs gets the Normal style. I can apply paragraph style to the paragraph but i can't apply character style to run,Where is wrong in my code?

In Conclusion:

How can i apply character style to a run and how to have a paragraph with different styling Run?

like image 319
Reza M.A Avatar asked Nov 27 '25 16:11

Reza M.A


1 Answers

You need to specify the formatting for the paragraph in its properties section otherwise it's going to fallback to the document's default which in this case is Normal. This might also happen if your custom styles are not saved to the styles part of the document.

Change your code to:

Paragraph heading = new Paragraph();
ParagraphProperties heading_pPr = new ParagraphProperties();
heading.Append(heading_pPr);
ParagraphMarkRunProperties headingParagraphMarkRunProperties = new ParagraphMarkRunProperties();
RunStyle runStyle1 = new RunStyle(){ Val = "CharacterStyle1" };

headingParagraphMarkRunProperties.Append(runStyle1);
heading_pPr.Append(headingParagraphMarkRunProperties);

This will enable your paragraph to adopt your custom formatting. You still need to apply individual styles to the run elements to change it's formatting as you correctly did in your rest of the code.

like image 158
Flowerking Avatar answered Nov 30 '25 04:11

Flowerking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!