Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / Office

Create PowerPoint presentation using PowerPoint template

5.00/5 (1 vote)
15 Apr 2012CPOL 32.5K  
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. C#
    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. 

    C#
    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. C#
    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. C#
    File.WriteAllBytes("PresentationFile1.pptx", presentationStream.ToArray());

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)