Introduction
The article tells how to create PowerPoint
presentation using PowerPoint template and Office OpenXML SDK 2.0. I assume the users have basic knowledge about Office OpenXML.
Background
To do so, first we need an existing PowerPoint template (*.potx file).
Using the code
- Create a simple .potx file.
Open Microsoft PowerPoint Presentation. The left panel contains a default slide, delete it. On the File menu, click Save As. In the File name box, type a name for your template, and then, in the Save as type box, select PowerPoint Template(*.potx). Let’s name this template as
SimplePresentationTemplate.potx.
- Copy this template into a
MemoryStream
.
MemoryStream templateStream = null;
using (Stream stream = File.Open("SimplePresentationTemplate.potx", FileMode.Open, FileAccess.Read))
{
templateStream = new MemoryStream((int)stream.Length);
stream.Copy(templateStream);
templateStream.Position = 0L;
}
stream.Copy(templateStream)
copies the FileStream
into the
MemoryStream
. This is an extension method.
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
- Create presentation file using the stream.
using (PresentationDocument prstDoc = PresentationDocument.Open(templateStream, true))
{
prstDoc.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = prstDoc.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship(
"http://schemas.openxmlformats.org/officeDocument/2006/" +
"relationships/attachedTemplate",
new Uri(("SimplePresentationTemplate.potx", UriKind.Absolute));
presPart.Presentation.Save();
}
- Save the memory stream into a file:
File.WriteAllBytes("PresentationFile1.pptx", presentationStream.ToArray());
That’s it.. The presentation file PresentationFile1.pptx got created without altering
the template file.