Add slides in ppt at runtime using c#

Add slides in ppt at runtime using c#

This is the continuation part of the C# with PowerPoint Series..!

Before proceeding please go through the very important previous session:

Previous Session : 1.How to create PPT using ASP NET C# | Power Point Presentation

Next Session: 3.Compare Two PPT Presentation using C#


Now, Create web application
1. Start Visual Studio:
2. Select File => New Project
3. Select the Programming language you want to use from Installed Templates section, in the New Project dialog box. Out of the box, you can either use C# or Visual Basic to develop ASP.NET web applications.
4. Select ASP.NET Web Application from the middle section of the New Project dialog box.
5. Provide a meaningful name to your project and solution.
6. Select the location, where you want the solution to be created.
7. Finally click OK.

Add the Assembly reference
Microsoft.Office.Interop.PowerPoint;

or the assembly mentioned in the image.
Microsoft PowerPoint 12.0 Object Library
Microsoft PowerPoint 12.0 Object Library

ExportInPPT.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportInPPT.aspx.cs" Inherits="DotNetConcept.ExportInPPT" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="3" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2">
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export In PPT" BackColor="#996600" Font-Bold="True" Font-Size="Medium" ForeColor="White" Height="37px" Width="205px" />
        <asp:Label ID="lblErrorMessage" runat="server"></asp:Label> 
    </div>
    </form>
</body>
</html>

ExportInPPT.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using Office = Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace DotNetConcept
{
    public partial class ExportInPPT : System.Web.UI.Page
    {
        PowerPoint.Application pptApplication = null;
        PowerPoint.Presentations pptPresentations = null;
        PowerPoint.Presentation pptPresentation = null;
        PowerPoint.Slides slides = null;
        PowerPoint.Slide slide = null;
        PowerPoint.Shapes shapes = null;
        PowerPoint.Shape shape = null;
        PowerPoint.TextFrame textFrame = null;
        PowerPoint.TextRange textRange = null;

        System.Data.DataTable table = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            table = new System.Data.DataTable();
            table.Columns.Add("Dosage", typeof(int));
            table.Columns.Add("Drug", typeof(string));
            table.Columns.Add("Patient", typeof(string));
            table.Columns.Add("Date", typeof(DateTime));

            table.Rows.Add(25, "Indocin", "Sam", DateTime.Now);
            table.Rows.Add(27, "Indocin", "David", DateTime.Now);
            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
            table.Rows.Add(23, "Combivent", "steav", DateTime.Now);
            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
            GridView1.DataSource = table;
            GridView1.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CreatePowerPointPresentation("ppt");
        }

        private void CreatePowerPointPresentation(string type)
        {
            StringBuilder sb = new StringBuilder();
            string PPTExportedFileInfo = "MyPPT_" + DateTime.Now.ToUniversalTime() + ".pptx";
            try
            {
                pptApplication = new PowerPoint.Application();
                // Create the Presentation File
                pptPresentations = pptApplication.Presentations;
                pptPresentation = pptPresentations.Add(Office.MsoTriState.msoTrue);                
                PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[PowerPoint.PpSlideLayout.ppLayoutText];
                slides = pptPresentation.Slides;
                slide = slides.AddSlide(1, customLayout);
                slide.Shapes[1].TextFrame.TextRange.Text = "My First Autogenerated PPT";
                
                PowerPoint.Shape _shape = slide.Shapes.AddTable(8, 4);
                PowerPoint.Table objTable1 = null;
                objTable1 = _shape.Table;
                objTable1.Rows.Add();
                for (int k = 0; k < table.Columns.Count; k++)
                {
                    objTable1.Cell(1, k + 1).Shape.TextFrame.TextRange.Text = table.Columns[k].ToString();
                }
                // Run through the created new table and paste all the previous table values
                for (int k = 0; k < table.Rows.Count; k++)
                {
                    for (int l = 0; l < table.Columns.Count; l++)
                    {
                        objTable1.Cell(k + 2, l + 1).Shape.TextFrame.TextRange.Text = table.Rows[k][l].ToString();
                    }
                }

                //Add new Slide in ppt at runtime
                int _slideIndex = slide.SlideIndex;
                PowerPoint.Slide _slide = null;
                _slideIndex = _slideIndex + 1;
                _slide = pptPresentation.Slides.Add(_slideIndex, PowerPoint.PpSlideLayout.ppLayoutText);
                _slide.Shapes[1].TextFrame.TextRange.Text = "This slide added dynamically at runtime!";

                
                WebClient user = null;
                Byte[] fileBuffer = null;
                if (type == "ppt")
                {
                    string tempPPT1 = "MyPPT_" + DateTime.Now.ToUniversalTime() + ".ppt";
                    tempPPT1 = tempPPT1.Replace(":", "_").Replace("/", "_").Replace(" ", "_");
                    string tempPPT = Server.MapPath("~/App_Data/PD1.ppt");
                    pptPresentation.SaveAs(tempPPT, PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Office.MsoTriState.msoCTrue);
                    pptPresentation.Close();
                    pptApplication.Quit();

                    //ClientScript.RegisterStartupScript(this.GetType(), "Planning Document Alert Box.", preScriptMessage + tempPPT + postScriptMessage, true);

                    user = new WebClient();
                    fileBuffer = user.DownloadData(tempPPT);
                    if (fileBuffer != null)
                    {
                        Response.Clear();
                        Response.Buffer = true;
                        Response.ContentType = "application/ppt";
                        Response.AddHeader("content-length", fileBuffer.Length.ToString());
                        Response.AddHeader("content-disposition", "attachment;filename=" + tempPPT1);
                        //response.binarywrite(filebuffer);
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.BinaryWrite(fileBuffer);
                        Response.Flush();
                        if (File.Exists(tempPPT))
                        {
                            File.Delete(tempPPT);
                        }
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "Hide Progress after task completion.", "$('.loading').hide();$('.modal').hide();", true);
                        Response.Close();
                    }
                }
                
            }
            catch (Exception ex)
            {
                lblErrorMessage.Text = ex.Message;
            }
            finally
            {
                if (textRange != null)
                {
                    Marshal.FinalReleaseComObject(textRange);
                    textRange = null;
                }
                if (textFrame != null)
                {
                    Marshal.FinalReleaseComObject(textFrame);
                    textFrame = null;
                }
                if (shape != null)
                {
                    Marshal.FinalReleaseComObject(shape);
                    shape = null;
                }
                if (shapes != null)
                {
                    Marshal.FinalReleaseComObject(shapes);
                    shapes = null;
                }
                if (slide != null)
                {
                    Marshal.FinalReleaseComObject(slide);
                    slide = null;
                }
                if (slides != null)
                {
                    Marshal.FinalReleaseComObject(slides);
                    slides = null;
                }
                if (pptPresentation != null)
                {
                    Marshal.FinalReleaseComObject(pptPresentation);
                    pptPresentation = null;
                }
                if (pptPresentations != null)
                {
                    Marshal.FinalReleaseComObject(pptPresentations);
                    pptPresentations = null;
                }
                if (pptApplication != null)
                {
                    Marshal.FinalReleaseComObject(pptApplication);
                    pptApplication = null;
                }
            }
        }   
    }
}

If you have any doubt please leave a comment.
Watch the video:

No comments:

Post a Comment

Your feedback is important.
Visit www.techwebdots.in