65.9K
CodeProject is changing. Read more.
Home

Create PowerPoint presentation using PowerPoint template

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Apr 15, 2012

CPOL
viewsIcon

32570

Convert *.potx file to *.pptx file.

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 

  1. Create a simple .potx file.
  2. 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.

  3. Copy this template into a MemoryStream.
  4. 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]; // this array length is sufficient for simple files 
                int length = buffer.Length, size; 
                while ((size = source.Read(buffer, 0, length)) != 0) 
                    target.Write(buffer, 0, size); 
            } 
        } 
    }
  5. Create presentation file using the stream.
  6. 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(); 
    }
  7. Save the memory stream into a file:
  8. File.WriteAllBytes(“PresentationFile1.pptx”, presentationStream.ToArray());

That’s it.. The presentation file PresentationFile1.pptx got created without altering the template file.