I want to search and replace text in PPT document using .NET Aspose, In this PPT document, the same TextFrame has multiple styles.
If I use the following code for find and replace, It will cause the style to be lost.
void Main()
{
string inputFile = @"C:\Users\Downloads\test.pptx";
string outPutfile = @"C:\Users\Downloads\output.pptx";
findReplaceText1("BBB","FFF", inputFile, outPutfile);
}
private static void findReplaceText1(string strToFind, string strToReplaceWith, string inputFile, string outPutfile)
{
Presentation pres = new Presentation(inputFile);
ITextFrame[] tb = SlideUtil.GetAllTextBoxes(pres.Slides[0]);
for (int i = 0; i < tb.Length; i++)
{
tb[i].Text = tb[i].Text.Replace(strToFind, strToReplaceWith);
}
pres.Save(outPutfile, SaveFormat.Pptx);
}
If I use the following code for find and replace, The result is ok.
void Main()
{
string inputFile = @"C:\Users\Downloads\test.pptx";
string outPutfile = @"C:\Users\Downloads\output.pptx";
findReplaceText2("BBB","FFF", inputFile, outPutfile);
}
private static void findReplaceText2(string strToFind, string strToReplaceWith, string inputFile, string outPutfile)
{
Presentation pres = new Presentation(inputFile);
ITextFrame[] tb = SlideUtil.GetAllTextBoxes(pres.Slides[0]);
for (int i = 0; i < tb.Length; i++)
{
foreach (Paragraph para in tb[i].Paragraphs)
{
foreach (Portion port in para.Portions)
{
port.Text = port.Text.Replace(strToFind, strToReplaceWith);
}
}
}
pres.Save(outPutfile, SaveFormat.Pptx);
}
But, If the content to be replaced is in two different Portions like the following code , How can I replace it correctly and keep the style?
void Main()
{
string inputFile = @"C:\Users\Downloads\test.pptx";
string outPutfile = @"C:\Users\Downloads\output.pptx";
// 'A' and 'B' in different Portion
findReplaceText2("ABB","FFF", inputFile, outPutfile);
}
The test PPT document:
test.zip (380.3 KB)
Thank you!