Adding links and styled text paragraphs to Power-Point presentation in C#
Article
When processing Power-Point presentations, the very common scenario is to replace or insert new paragraphs into presentation. Inserting styled paragraphs can be quite confusing as we need to structure run tags properly in order to avoid breaking the document structure.
In typical scenario we want to create multiple paragraphs containing different texts and colors. We can do it as follows:
public Paragraph CreateStyledParagraph(string text,System.Drawing.Color color, bool isBold, bool isItalic,int fontSize =2000){var runProperties =newRunProperties();//set basic styles for paragraph runProperties.Bold= isBold; runProperties.Italic= isItalic; runProperties.FontSize= fontSize; runProperties.Dirty=false;var hexColor = color.R.ToString("X2")+ color.G.ToString("X2")+ color.B.ToString("X2");//convert color to hexvar solidFill =newSolidFill();var rgbColorModelHex =newRgbColorModelHex(){ Val = hexColor }; solidFill.Append(rgbColorModelHex); runProperties.Append(solidFill);var textBody =new Drawing.Text(); textBody.Text= text;//assign textvar run =new Drawing.Run();var newParagraph =newParagraph(); run.Append(runProperties);//append styles run.Append(textBody);//append text newParagraph.Append(run);//append run to paragraphreturn newParagraph;}
Creating links is a little bit different. In order to do it we first need to create HyperlinkRelationship in the slide, the HyperlinkOnClick class contained within the run will then map to it on user click event. Please note that link color is not supported.
public Paragraph CreateStyledLinkParagraph(SlidePart slidePart, string url, string text, bool isBold, bool isItalic,int fontSize =2000){//note: HyperlinkOnClick does not support link colorvar relationshipId ="rIdlink"+ Guid.NewGuid().ToString();//create unique id slidePart.AddHyperlinkRelationship(newSystem.Uri(url,System.UriKind.Absolute),true, relationshipId);//assign hyperlink to the current slide we processvar runProperties =newRunProperties(newHyperlinkOnClick(){ Id = relationshipId });//set basic styles and assign relationshipId runProperties.Bold= isBold; runProperties.Italic= isItalic; runProperties.FontSize= fontSize; runProperties.Dirty=false;var textBody =new Drawing.Text(); textBody.Text= text;//assign textvar run =new Drawing.Run();var newParagraph =newParagraph(); run.Append(runProperties);//append styles run.Append(textBody);//append text newParagraph.Append(run);//append run to paragraphreturn newParagraph;}