none
insert paragraph of texts in the powerpoint slide dynamically using openxml RRS feed

  • Question

  • Hi ,

    i am new to open xml. i have some requirement for my project.

    i need to insert text or paragraphs  in the powerpoint slide dynamically that is coming from excel sheet .

    Excel is the source document which contains texts and paragraphs.

    For example : sheet 1 contains the following information. i need to retrieve these informations and write it into the powerpoint presentation. if the text limit reaches the end of the slide it should automatically create a new slide.

    Currently am able to read all the contents from excel sheet and i could load in the dataset. after loading the content in the dataset i dont know how to write the loaded contents in the presentation slide.

    i created an empty presentation using openxml with PresentationParts,SlidePart,SlideLayoutPart,SlideMasterPart,Theme.

    My Code:

    public void generate_click(object sender, EventArgs e)
            {
                string scode = "C:\\Users\\302480\\Documents\\Visual Studio 2010\\Projects\\ppt\\ppt\\Source\\Excel_Source_ppt\\test.pptx";
                CreatePresentation(scode);
                sExcelPath = Server.MapPath("~/Source/Excel_Source_ppt/") + ConfigurationManager.AppSettings["TEMS_ppt"].ToString();
                sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sExcelPath + ".xlsx;Extended Properties=Excel 12.0";
                Get_WorkSheet_Names();
                Get_Excel_Data();
                foreach (DataTable table in dsSOW.Tables)
                {
                    foreach (DataRow dr in table.Rows)
                    {
                        no = dr.ItemArray[0].ToString();
                        desc = dr.ItemArray[1].ToString();
                        data = no+ " " + desc;
                    }
                }
    private void Get_WorkSheet_Names()
            {
                string sWorkSheetsColl = String.Empty;
              
                    {
                        int iIndex = 0;
                        oConn = new OleDbConnection(sConnString);
                        oConn.Open();
                        dtList = oConn.GetSchema("Tables");
                        if (dtList != null)
                        {
                            dsSOW = new DataSet();                       
                            foreach (DataRow dr in dtList.Rows)
                            {
                                if (dr["TABLE_NAME"].ToString().ToLower() != "_xlnm#_filterdatabase")
                                {
                                    dsSOW.Tables.Add(dr["TABLE_NAME"].ToString());                               
                                    sWorkSheetsColl += dr["TABLE_NAME"].ToString() + ",";
                                    iIndex++;
                                }
                            }
                            sWorkSheetsColl = sWorkSheetsColl.TrimEnd(',');
                            sWorkSheets = sWorkSheetsColl.Split(',');
                            dsSOW.AcceptChanges();
                        }
                    }
                }
            private void Get_Excel_Data()
            {
                    for (int i = 0; i < sWorkSheets.Length; i++)
                    {
                        oCmd = new OleDbCommand("SELECT * FROM [" + sWorkSheets[i].TrimEnd() + "]", oConn);
                        oDa = new OleDbDataAdapter();
                        oDa.SelectCommand = oCmd;
                        oDa.Fill(dsSOW.Tables[sWorkSheets[i].ToString()]);
                    }
                    oConn.Close();
                    dsSOW.AcceptChanges();
             }     

     

     

    public static void CreatePresentation(string filepath) { // Create a presentation at a specified file path. The presentation document type is pptx, by default. PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationParts(presentationPart); // Close the presentation handle presentationDoc.Close(); } private static void CreatePresentationParts(PresentationPart presentationPart) { SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" }); SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" }); SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 }; NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 }; DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle(); presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1); SlidePart slidePart1; SlideLayoutPart slideLayoutPart1; SlideMasterPart slideMasterPart1; ThemePart themePart1; slidePart1 = CreateSlidePart(presentationPart); slideLayoutPart1 = CreateSlideLayoutPart(slidePart1); slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1); themePart1 = CreateTheme(slideMasterPart1); slideMasterPart1.AddPart(slideLayoutPart1, "rId1"); presentationPart.AddPart(slideMasterPart1, "rId1"); presentationPart.AddPart(themePart1, "rId5"); } private static SlidePart CreateSlidePart(PresentationPart presentationPart) { SlidePart slidePart1 = presentationPart.AddNewPart<SlidePart>("rId2"); ImagePart imagePart = slidePart1.AddNewPart<ImagePart>("image/jpg", "rId2"); string filepath = @"C:\Users\302480\Documents\Visual Studio 2010\Projects\ppt\ppt\Source\Images\DDT.jpg"; FileStream stream = new FileStream(filepath, FileMode.Open); imagePart.FeedData(stream); stream.Close(); slidePart1.Slide = new Slide( new CommonSlideData( new ShapeTree( new P.NonVisualGroupShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, new P.NonVisualGroupShapeDrawingProperties(), new ApplicationNonVisualDrawingProperties()), new GroupShapeProperties(new TransformGroup()), new P.Shape( new P.NonVisualShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" }, new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), new P.ShapeProperties(), new P.TextBody( new BodyProperties(), new ListStyle(), new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))))), new ColorMapOverride(new MasterColorMapping())); P.Picture picture = new P.Picture(); P.BlipFill blipFill = new P.BlipFill(); D.Blip blip = new D.Blip() { Embed = "rId2" }; Stretch stretch = new Stretch(); FillRectangle fillRectangle = new FillRectangle(); stretch.Append(fillRectangle); blipFill.Append(blip); blipFill.Append(stretch); BlipExtensionList blipExtensionList1 = new BlipExtensionList(); BlipExtension blipExtension1 = new BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }; UseLocalDpi useLocalDpi1 = new UseLocalDpi() { Val = false }; useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main"); blipExtension1.Append(useLocalDpi1); blipExtensionList1.Append(blipExtension1); blip.Append(blipExtensionList1); picture.Append(blipFill); P.ShapeProperties shapeProperties1 = new P.ShapeProperties(); D.Transform2D transform2D1 = new D.Transform2D(); D.Offset offset1 = new D.Offset() { X = 667544L, Y = 648680L }; D.Extents extents1 = new D.Extents() { Cx = 5743848L, Cy = 4886743L }; transform2D1.Append(offset1); transform2D1.Append(extents1); D.PresetGeometry presetGeometry1 = new D.PresetGeometry() { Preset = D.ShapeTypeValues.Rectangle }; D.AdjustValueList adjustValueList1 = new D.AdjustValueList(); presetGeometry1.Append(adjustValueList1); shapeProperties1.Append(transform2D1); shapeProperties1.Append(presetGeometry1); picture.Append(shapeProperties1); slidePart1.Slide.CommonSlideData.ShapeTree.Append(picture); return slidePart1; } private static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1) { SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart<SlideLayoutPart>("rId1"); SlideLayout slideLayout = new SlideLayout( new CommonSlideData(new ShapeTree( new P.NonVisualGroupShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, new P.NonVisualGroupShapeDrawingProperties(), new ApplicationNonVisualDrawingProperties()), new GroupShapeProperties(new TransformGroup()), new P.Shape( new P.NonVisualShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" }, new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), new P.ShapeProperties(), new P.TextBody( new BodyProperties(), new ListStyle(), new Paragraph(new EndParagraphRunProperties()))))), new ColorMapOverride(new MasterColorMapping())); slideLayoutPart1.SlideLayout = slideLayout; return slideLayoutPart1; } private static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1) { SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart<SlideMasterPart>("rId1"); SlideMaster slideMaster = new SlideMaster( new CommonSlideData(new ShapeTree( new P.NonVisualGroupShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, new P.NonVisualGroupShapeDrawingProperties(), new ApplicationNonVisualDrawingProperties()), new GroupShapeProperties(new TransformGroup()), new P.Shape( new P.NonVisualShapeProperties( new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" }, new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })), new P.ShapeProperties(), new P.TextBody( new BodyProperties(), new ListStyle(), new Paragraph())))), new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink }, new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }), new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle())); slideMasterPart1.SlideMaster = slideMaster; return slideMasterPart1; } private static ThemePart CreateTheme(SlideMasterPart slideMasterPart1) { ThemePart themePart1 = slideMasterPart1.AddNewPart<ThemePart>("rId5"); D.Theme theme1 = new D.Theme() { Name = "Office Theme" }; D.ThemeElements themeElements1 = new D.ThemeElements( new D.ColorScheme( new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }), new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }), new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }), new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }), new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }), new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }), new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }), new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }), new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }), new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }), new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }), new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) { Name = "Office" }, new D.FontScheme( new D.MajorFont( new D.LatinFont() { Typeface = "Calibri" }, new D.EastAsianFont() { Typeface = "" }, new D.ComplexScriptFont() { Typeface = "" }), new D.MinorFont( new D.LatinFont() { Typeface = "Calibri" }, new D.EastAsianFont() { Typeface = "" }, new D.ComplexScriptFont() { Typeface = "" })) { Name = "Office" }, new D.FormatScheme( new D.FillStyleList( new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), new D.GradientFill( new D.GradientStopList( new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }, new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 35000 }, new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 }, new D.SaturationModulation() { Val = 350000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 100000 } ), new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), new D.NoFill(), new D.PatternFill(), new D.GroupFill()), new D.LineStyleList( new D.Outline( new D.SolidFill( new D.SchemeColor( new D.Shade() { Val = 95000 }, new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }), new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) { Width = 9525, CapType = D.LineCapValues.Flat, CompoundLineType = D.CompoundLineValues.Single, Alignment = D.PenAlignmentValues.Center }, new D.Outline( new D.SolidFill( new D.SchemeColor( new D.Shade() { Val = 95000 }, new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }), new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) { Width = 9525, CapType = D.LineCapValues.Flat, CompoundLineType = D.CompoundLineValues.Single, Alignment = D.PenAlignmentValues.Center }, new D.Outline( new D.SolidFill( new D.SchemeColor( new D.Shade() { Val = 95000 }, new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }), new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) { Width = 9525, CapType = D.LineCapValues.Flat, CompoundLineType = D.CompoundLineValues.Single, Alignment = D.PenAlignmentValues.Center }), new D.EffectStyleList( new D.EffectStyle( new D.EffectList( new D.OuterShadow( new D.RgbColorModelHex( new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), new D.EffectStyle( new D.EffectList( new D.OuterShadow( new D.RgbColorModelHex( new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), new D.EffectStyle( new D.EffectList( new D.OuterShadow( new D.RgbColorModelHex( new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))), new D.BackgroundFillStyleList( new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), new D.GradientFill( new D.GradientStopList( new D.GradientStop( new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }, new D.GradientStop( new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }, new D.GradientStop( new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }), new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), new D.GradientFill( new D.GradientStopList( new D.GradientStop( new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }, new D.GradientStop( new D.SchemeColor(new D.Tint() { Val = 50000 }, new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }), new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) { Name = "Office" }); theme1.Append(themeElements1); theme1.Append(new D.ObjectDefaults()); theme1.Append(new D.ExtraColorSchemeList()); themePart1.Theme = theme1; return themePart1; }


    Thanks !

    banu


    banupriya


    Wednesday, August 14, 2013 10:38 AM

Answers

  • Hi banu,

    According to your description, you wanted to insert dataset to presentation and if text limit reaches the end of the

    slide it should automatically create a new slide. I wrote a sample add text to the slide from dataset.

    After ran the code:

    Code:

      public void button1_Click(object sender, EventArgs e)
            {
                string SlideText="";
                int slideLineNum = 6;
                int drIndex=0;
                int slideIndex=1;
                string slideTitle = "My new slide title"; 
                slideTitle = "";
                string pptPath = @"D:\Documents\study\Code\MyProject\InsertText\Hello.pptx";
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (drIndex++ % slideLineNum == 0)
                    {
                        //InsertNewSlide(pptPath, slideIndex++, slideTitle, SlideText);
                        InsertNewSlide(pptPath, slideIndex++,SlideText , "");
                        SlideText = "";
                    }
                    SlideText+=dr[0].ToString()+" "+dr[1].ToString()+"\r\n";
                }
                if (!String.IsNullOrEmpty(SlideText))
                   // InsertNewSlide(pptPath, slideIndex++, slideTitle, SlideText);
                    InsertNewSlide(pptPath, slideIndex++, SlideText, "");
                MessageBox.Show("OK");
              
            }
       // Insert a slide into the specified presentation.
            public static void InsertNewSlide(string presentationFile, int position, string slideTitle, string slideContent)
            {
                // Open the source document as read/write. 
                using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
                {
                    // Pass the source document and the position and title of the slide to be inserted to the next method.
                    InsertNewSlide(presentationDocument, position, slideTitle, slideContent);
                }
            }
    
            // Insert the specified slide into the presentation at the specified position.
            public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle,string slideContent)
            {
                if (presentationDocument == null)
                {
                    throw new ArgumentNullException("presentationDocument");
                }
    
                if (slideTitle == null)
                {
                    throw new ArgumentNullException("slideTitle");
                }
    
                PresentationPart presentationPart = presentationDocument.PresentationPart;
    
                // Verify that the presentation is not empty.
                if (presentationPart == null)
                {
                    throw new InvalidOperationException("The presentation document is empty.");
                }
    
                // Declare and instantiate a new slide.
                Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
                uint drawingObjectId = 1;
    
                // Construct the slide content.            
                // Specify the non-visual properties of the new slide.
                NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
                nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
                nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
                nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
    
                // Specify the group shape properties of the new slide.
                GroupShapeProperties transformGroup1 = new GroupShapeProperties();
                DocumentFormat.OpenXml.Drawing.Offset offset1 = new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L };
                transformGroup1.Append(offset1);
                slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
    
                if (!String.IsNullOrEmpty(slideTitle))
                {
                   
                    // Declare and instantiate the title shape of the new slide.
                    Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
    
                    drawingObjectId++;
    
                    // Specify the required shape properties for the title shape. 
                    titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
                        (new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" },
                        new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
                    titleShape.ShapeProperties = new ShapeProperties();
                    
    
                    // Specify the text of the title shape.
                    titleShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                            new Drawing.ListStyle(),
                            new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle })));
                    
                }
               
    
                // Declare and instantiate the body shape of the new slide.
                Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
                drawingObjectId++;
    
                // Specify the required shape properties for the body shape.
                bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(
                        new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" },
                        new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 }));
                bodyShape.ShapeProperties = new ShapeProperties();
    
                // Specify the text of the body shape.
                bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                        new Drawing.ListStyle(),
                        new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideContent })));
               
    
                // Create the slide part for the new slide.
                SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
    
                // Save the new slide part.
                slide.Save(slidePart);
    
                // Modify the slide ID list in the presentation part.
                // The slide ID list should not be null.
                SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
    
                // Find the highest slide ID in the current list.
                uint maxSlideId = 1;
                SlideId prevSlideId = null;
    
                foreach (SlideId slideId in slideIdList.ChildElements)
                {
                    if (slideId.Id > maxSlideId)
                    {
                        maxSlideId = slideId.Id;
                    }
    
                    position--;
                    if (position == 0)
                    {
                        prevSlideId = slideId;
                    }
    
                }
    
                maxSlideId++;
    
                // Get the ID of the previous slide.
                SlidePart lastSlidePart;
    
                if (prevSlideId != null)
                {
                    lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
                }
                else
                {
                    lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
                }
    
                // Use the same slide layout as that of the previous slide.
                if (null != lastSlidePart.SlideLayoutPart)
                {
                    slidePart.AddPart(lastSlidePart.SlideLayoutPart);
                }
    
                // Insert the new slide into the slide list after the previous slide.
                SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
                newSlideId.Id = maxSlideId;
                newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
    
                // Save the modified presentation.
                presentationPart.Presentation.Save();
            }

    You can get the sample project from click here to download.

    • Marked as answer by Banupriya V K Monday, August 19, 2013 7:56 AM
    Friday, August 16, 2013 2:23 PM

All replies

  • Hi banu,

    According to your description, you wanted to insert dataset to presentation and if text limit reaches the end of the

    slide it should automatically create a new slide. I wrote a sample add text to the slide from dataset.

    After ran the code:

    Code:

      public void button1_Click(object sender, EventArgs e)
            {
                string SlideText="";
                int slideLineNum = 6;
                int drIndex=0;
                int slideIndex=1;
                string slideTitle = "My new slide title"; 
                slideTitle = "";
                string pptPath = @"D:\Documents\study\Code\MyProject\InsertText\Hello.pptx";
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (drIndex++ % slideLineNum == 0)
                    {
                        //InsertNewSlide(pptPath, slideIndex++, slideTitle, SlideText);
                        InsertNewSlide(pptPath, slideIndex++,SlideText , "");
                        SlideText = "";
                    }
                    SlideText+=dr[0].ToString()+" "+dr[1].ToString()+"\r\n";
                }
                if (!String.IsNullOrEmpty(SlideText))
                   // InsertNewSlide(pptPath, slideIndex++, slideTitle, SlideText);
                    InsertNewSlide(pptPath, slideIndex++, SlideText, "");
                MessageBox.Show("OK");
              
            }
       // Insert a slide into the specified presentation.
            public static void InsertNewSlide(string presentationFile, int position, string slideTitle, string slideContent)
            {
                // Open the source document as read/write. 
                using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
                {
                    // Pass the source document and the position and title of the slide to be inserted to the next method.
                    InsertNewSlide(presentationDocument, position, slideTitle, slideContent);
                }
            }
    
            // Insert the specified slide into the presentation at the specified position.
            public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle,string slideContent)
            {
                if (presentationDocument == null)
                {
                    throw new ArgumentNullException("presentationDocument");
                }
    
                if (slideTitle == null)
                {
                    throw new ArgumentNullException("slideTitle");
                }
    
                PresentationPart presentationPart = presentationDocument.PresentationPart;
    
                // Verify that the presentation is not empty.
                if (presentationPart == null)
                {
                    throw new InvalidOperationException("The presentation document is empty.");
                }
    
                // Declare and instantiate a new slide.
                Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
                uint drawingObjectId = 1;
    
                // Construct the slide content.            
                // Specify the non-visual properties of the new slide.
                NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
                nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
                nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
                nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
    
                // Specify the group shape properties of the new slide.
                GroupShapeProperties transformGroup1 = new GroupShapeProperties();
                DocumentFormat.OpenXml.Drawing.Offset offset1 = new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L };
                transformGroup1.Append(offset1);
                slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
    
                if (!String.IsNullOrEmpty(slideTitle))
                {
                   
                    // Declare and instantiate the title shape of the new slide.
                    Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
    
                    drawingObjectId++;
    
                    // Specify the required shape properties for the title shape. 
                    titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
                        (new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" },
                        new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
                    titleShape.ShapeProperties = new ShapeProperties();
                    
    
                    // Specify the text of the title shape.
                    titleShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                            new Drawing.ListStyle(),
                            new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle })));
                    
                }
               
    
                // Declare and instantiate the body shape of the new slide.
                Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
                drawingObjectId++;
    
                // Specify the required shape properties for the body shape.
                bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(
                        new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" },
                        new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 }));
                bodyShape.ShapeProperties = new ShapeProperties();
    
                // Specify the text of the body shape.
                bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                        new Drawing.ListStyle(),
                        new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideContent })));
               
    
                // Create the slide part for the new slide.
                SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
    
                // Save the new slide part.
                slide.Save(slidePart);
    
                // Modify the slide ID list in the presentation part.
                // The slide ID list should not be null.
                SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
    
                // Find the highest slide ID in the current list.
                uint maxSlideId = 1;
                SlideId prevSlideId = null;
    
                foreach (SlideId slideId in slideIdList.ChildElements)
                {
                    if (slideId.Id > maxSlideId)
                    {
                        maxSlideId = slideId.Id;
                    }
    
                    position--;
                    if (position == 0)
                    {
                        prevSlideId = slideId;
                    }
    
                }
    
                maxSlideId++;
    
                // Get the ID of the previous slide.
                SlidePart lastSlidePart;
    
                if (prevSlideId != null)
                {
                    lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
                }
                else
                {
                    lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
                }
    
                // Use the same slide layout as that of the previous slide.
                if (null != lastSlidePart.SlideLayoutPart)
                {
                    slidePart.AddPart(lastSlidePart.SlideLayoutPart);
                }
    
                // Insert the new slide into the slide list after the previous slide.
                SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
                newSlideId.Id = maxSlideId;
                newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
    
                // Save the modified presentation.
                presentationPart.Presentation.Save();
            }

    You can get the sample project from click here to download.

    • Marked as answer by Banupriya V K Monday, August 19, 2013 7:56 AM
    Friday, August 16, 2013 2:23 PM
  • Thanks alot for your reply !!

    This is working fine . now i could insert text in my powerpoint slide. But am getting this error when i try to open the presentation.

    After clicking repair,

    after repairing it i can see the contents . But without getting this error can i open the file ?? could you pls give me the solution.

    Thanks !!

    Banu


    banupriya

    Monday, August 19, 2013 7:55 AM
  • Hi,

    i have created a powerpoint presentation with number of slides and inserted some sample text . Now the problem is , while taking Multiline text or paragraphs from Excel sheet it is counting the whole paragraph as 1 line.  so if we give SlidelineNumber as 6 or any default value , then the text or paragraph does not fit in the placeholder. it is floating after the slide's end. so how can i find the EndofSlide automatically without giving slidelineNumber..

     


    banupriya

    Tuesday, September 3, 2013 11:53 AM
  • Did you find any resolution for this?
    Thursday, July 16, 2015 2:58 PM