我们可以通过插入占位符的方式,使用新的字词替换已有幻灯片里的文字。 本文将详细描述如何使用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
替换文本后的效果图: