C# Presentation 文本替换
我们可以通过插入占位符的方式,使用新的字词替换已有幻灯片里的文字。 本文将详细描述如何使用Spire.Presentation 来替换Prsentation 里面的文本。
首先请看示例文档,我们接下来会使用 Spire.PPT 替换示例文档里面的“Spire.Presentation for .NET”.
public ReplaceText() { { //创建一个Dictionary 实例并添加一个item Dictionary TagValues = new Dictionary(); TagValues.Add("Spire.Presentation for .NET", "Spire.PPT"); //加载PowerPoint示例文档 Presentation presentation = new Presentation(); presentation.LoadFromFile("Sample.pptx", FileFormat.Pptx2010); //调用ReplaceTags事件来替换第一个幻灯片里的文本 ReplaceTags(presentation.Slides[0], TagValues); //保存文档 presentation.SaveToFile("Result.pptx", FileFormat.Pptx2010); System.Diagnostics.Process.Start("Result.pptx"); } } public void ReplaceTags(Spire.Presentation.ISlide pSlide, Dictionary TagValues) { foreach (IShape curShape in pSlide.Shapes) { if (curShape is IAutoShape) { foreach (TextParagraph tp in (curShape as IAutoShape).TextFrame.Paragraphs) { foreach (var curKey in TagValues.Keys) { if (tp.Text.Contains(curKey)) { tp.Text = tp.Text.Replace(curKey, TagValues[curKey]); } } } } } }
替换文本后的效果图:
下载免费版的spire.presentation, 在项目中添加spire.presentation.dll为引用
using
Spire.Presentation;
using
System.Drawing;
namespace
FontColorInPpt
{
class
Program
{
static
void
Main(
string
[] args)
{
//创建Presentation对象
Presentation presentation =
new
Presentation();
//添加图形
IAutoShape shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Rectangle,
new
RectangleF(50, 50, 200, 50));
//设置图形边框色
shape.ShapeStyle.LineColor.Color = Color.Black;
//设置图形填充为不填充
shape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.None;
//添加文字
shape.TextFrame.Text =
"这是红色的字"
;
//设置文字颜色
TextRange textRange = shape.TextFrame.TextRange;
textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
textRange.Fill.SolidColor.Color = Color.Red;
//设置字体及大小
textRange.FontHeight = 21;
textRange.LatinFont =
new
TextFont(
"黑体"
);
//保存文档
presentation.SaveToFile(
"output.pptx"
, FileFormat.Pptx2007);
}
}
}
|