I have a PPT template in which I need to programmatically replace some text fields with data that comes from my database then convert the ppt to pdf and send it as attachment in an email. I am not sure of how to change the content of text fields in the PowerPoint Presentation. I think OpenXML needs to be used. Please help me to feed dynamic data into my ppt template.
CodePudding user response:
I have worked previously with the DocumentFormat.OpenXml
from Microsoft but with word files. I played a bit with it to replace some Texts in a Power Point file.
Here is my simple test code snippet:
static void Main(string[] args)
{
// just gets me the current location of the assembly to get a full path
string fileName = GetFilePath("Resource\\Template.pptx");
// open the presentation in edit mode -> the bool parameter stands for 'isEditable'
using (PresentationDocument document = PresentationDocument.Open(fileName, true))
{
// going through the slides of the presentation
foreach (SlidePart slidePart in document.PresentationPart.SlideParts)
{
// searching for a text with the placeholder i want to replace
DocumentFormat.OpenXml.Drawing.Text text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[TITLE]]");
// change the text
if (text != null)
text.Text = "My new cool title";
// searching for the second text with the placeholder i want to replace
text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[SUBTITLE]]");
// change the text
if (text != null)
text.Text = "My new cool sub-title";
}
document.Save();
}
}
In my case i had a simple presentation with one slide and in the Text fields the entries "[[TITLE]]" and "[[SUBTITLE]]" which i replaced with this text.
For my test file this worked well but maybe you will need to adopt / change something for your specific file. E.g. in Word i had sometimes texts which was splitted in multiple Text parts within a Run element and had to write a logic to "collect" this data and replace them with one Text element with the new text i wanted to be there or maybe you have to search for other Descendant types.