我们可以通过插入占位符的方式,使用新的字词替换已有幻灯片里的文字。 本文将详细描述如何使用Spire.Presentation 来替换Prsentation 里面的文本。
首先请看示例文档,我们接下来会使用 Spire.PPT 替换示例文档里面的“Spire.Presentation for .NET”.
C#
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]);
}
}
}
}
}
}
VB.NET
Public Sub New()
If True Then
'创建一个Dictionary 实例并添加一个item
Dim TagValues As New Dictionary()
TagValues.Add("Spire.Presentation for .NET", "Spire.PPT")
'加载PowerPoint示例文档
Dim presentation As 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")
End If
End Sub
Public Sub ReplaceTags(pSlide As Spire.Presentation.ISlide, TagValues As Dictionary)
For Each curShape As IShape In pSlide.Shapes
If TypeOf curShape Is IAutoShape Then
For Each tp As TextParagraph In TryCast(curShape, IAutoShape).TextFrame.Paragraphs
For Each curKey As var In TagValues.Keys
If tp.Text.Contains(curKey) Then
tp.Text = tp.Text.Replace(curKey, TagValues(curKey))
End If
Next
Next
End If
Next
End Sub
替换文本后的效果图: