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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public Paragraph CreateStyledParagraph(string text, System.Drawing.Color color, bool isBold, bool isItalic, int fontSize = 2000)
{
var runProperties = new RunProperties(); //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 hex
var solidFill = new SolidFill();
var rgbColorModelHex = new RgbColorModelHex() { Val = hexColor };
solidFill.Append(rgbColorModelHex);
runProperties.Append(solidFill);
var textBody = new Drawing.Text();
textBody.Text = text; //assign text
var run = new Drawing.Run();
var newParagraph = new Paragraph();
run.Append(runProperties);//append styles
run.Append(textBody);//append text
newParagraph.Append(run);//append run to paragraph
return 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public Paragraph CreateStyledLinkParagraph(SlidePart slidePart, string url, string text, bool isBold, bool isItalic, int fontSize = 2000)
{
//note: HyperlinkOnClick does not support link color
var relationshipId = "rIdlink" + Guid.NewGuid().ToString();//create unique id
slidePart.AddHyperlinkRelationship(new System.Uri(url, System.UriKind.Absolute), true, relationshipId);//assign hyperlink to the current slide we process
var runProperties = new RunProperties(new HyperlinkOnClick() { 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 text
var run = new Drawing.Run();
var newParagraph = new Paragraph();
run.Append(runProperties);//append styles
run.Append(textBody);//append text
newParagraph.Append(run);//append run to paragraph
return newParagraph;
}
|
Project files can be downloaded here:
http://www.dotnet-geek.co.uk/index.php/programmatically-adding-links-and-styled-text-to-power-point-presentation/
http://c.statcounter.com/9052428/0/942dbb33/1/