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);
}
}
}
|