在使用C#创建PowerPoint文档的过程中,我们首先需要添加一个shape图形到幻灯片文档,然后在图形中添加多个段落并设置段落格式。该示例将详细描述如何使用Spire.Presentation 添加或删除PowerPoint段落。
添加段落到幻灯片
C#
//新建一个PowerPoint文档并获取第一个幻灯片
Presentation presentation = new Presentation();
ISlide slide = presentation.Slides[0];
//添加一个shape到第一张幻灯片并设置其大小,颜色
IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70, 600, 200));
shape.Fill.FillType = FillFormatType.None;
shape.ShapeStyle.LineColor.Color = Color.White;
//在图形上添加第一个段落及文字
shape.TextFrame.Paragraphs[0].TextRanges.Append(new TextRange("使用代码添加段落到幻灯片"));
//在图形上添加第二个段落及文字
string text = "一款专业的 PowerPoint 组件,使用该组件,开发者可以在 .NET 平台上对 PowerPoint 文档进行生成、读取、写入、修改、转换和打印等操作。";
TextParagraph p=new TextParagraph();
p.Text=text;
shape.TextFrame.Paragraphs.Append(p);
//设置段落中文字的字体与颜色
foreach (TextParagraph para in shape.TextFrame.Paragraphs)
{
foreach (TextRange range in para.TextRanges)
{
range.LatinFont = new TextFont("宋体");
range.Fill.FillType = FillFormatType.Solid;
range.Fill.SolidColor.Color = Color.Black;
}
//设置段落对齐方式、段首缩进及行距
para.Alignment = TextAlignmentType.Left;
para.Indent = 50;
para.LineSpacing = 150;
}
//保存文档
presentation.SaveToFile("Result.pptx", FileFormat.Pptx2010);
VB.NET
'新建一个PowerPoint文档并获取第一个幻灯片
Dim presentation As New Presentation()
Dim slide As ISlide = presentation.Slides(0)
'添加一个shape到第一张幻灯片并设置其大小,颜色
Dim shape As IAutoShape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(50, 70, 600, 200))
shape.Fill.FillType = FillFormatType.None
shape.ShapeStyle.LineColor.Color = Color.White
'在图形上添加第一个段落及文字
shape.TextFrame.Paragraphs(0).TextRanges.Append(New TextRange("使用代码添加段落到幻灯片"))
'在图形上添加第二个段落及文字
Dim text As String = "一款专业的 PowerPoint 组件,使用该组件,开发者可以在 .NET 平台上对 PowerPoint 文档进行生成、读取、写入、修改、转换和打印等操作。"
Dim p As New TextParagraph()
p.Text = text
shape.TextFrame.Paragraphs.Append(p)
'设置段落中文字的字体与颜色
For Each para As TextParagraph In shape.TextFrame.Paragraphs
For Each range As TextRange In para.TextRanges
range.LatinFont = New TextFont("宋体")
range.Fill.FillType = FillFormatType.Solid
range.Fill.SolidColor.Color = Color.Black
Next
'设置段落对齐方式、段首缩进及行距
para.Alignment = TextAlignmentType.Left
para.Indent = 50
para.LineSpacing = 150
Next
'保存文档
presentation.SaveToFile("Result.pptx", FileFormat.Pptx2010)
添加段落和设置段落格式效果图:
删除段落
C#
//加载文档
Presentation presentation = new Presentation();
presentation.LoadFromFile("Result.pptx",FileFormat.Pptx2010);
//获取第一张幻灯片
ISlide slide = presentation.Slides[0];
//获取第一个图形
IAutoShape shape = slide.Shapes[0] as IAutoShape;
//删除图形里的第二个段落
shape.TextFrame.Paragraphs.RemoveAt(1);
//保存文档
presentation.SaveToFile("RemovePara.pptx", FileFormat.Pptx2010);
VB.NET
'加载文档
Dim presentation As New Presentation()
presentation.LoadFromFile("Result.pptx", FileFormat.Pptx2010)
'获取第一张幻灯片
Dim slide As ISlide = presentation.Slides(0)
'获取第一个图形
Dim shape As IAutoShape = TryCast(slide.Shapes(0), IAutoShape)
'删除图形里的第二个段落
shape.TextFrame.Paragraphs.RemoveAt(1)
'保存文档
presentation.SaveToFile("RemovePara.pptx", FileFormat.Pptx2010)