简体   繁体   中英

C# Add images and text to PowerPoint slides

I'm trying to add images from a folder and their names below each image. In master slide[0] there should be Title. My problem is that my code is generating single PowerPoint file for each image instead of adding all images to one PowerPoint file. Can someone help me with my come or simar code that can work out

I've attached an image of what I'm trying to achieve. Here's the code I'm working with using C# and GemBoxPresentation API:

    //Create new powerpoint presentation
        var presentation = new PresentationDocument();
        //change the path format
        string dir = txtPath.Text.Replace("/", "\\");
        fontRootFolder = dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, "");
        string workingPath = Application.StartupPath + @"\Zip Extracts\" + fontRootFolder + "\\png";

        if (Directory.Exists(workingPath))
        {
            // Get the directory
            DirectoryInfo ImagePath = new DirectoryInfo(workingPath);
            // Using GetFiles() method to get list of all png files present in the png folder
            FileInfo[] Files = ImagePath.GetFiles();
            foreach (FileInfo fi in Files)
            {
                for (int i = 0; i < fi.Length; i++)
                {
                    Cursor = Cursors.WaitCursor;
                    // Get slide size.
                    var size = presentation.SlideSize;

                    // Set slide size.
                    size.SizedFor = SlideSizeType.OnscreenShow16X10;
                    size.Orientation = GemBox.Presentation.Orientation.Landscape;
                    size.NumberSlidesFrom = 1;

                    // Create new presentation slide.
                    var slide = presentation.Slides.AddNew(SlideLayoutType.Custom);

                    // Create first picture from path.
                    Picture picture = null;
                    using (var stream = File.OpenRead(fi.FullName))
                        picture = slide.Content.AddPicture(PictureContentType.Png, stream, 1.45, 1.35, 1.45, 1.35, LengthUnit.Centimeter);

                    var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 1.03, 1.03, 6, 6, LengthUnit.Centimeter);

                    var paragraph = textBox.AddParagraph();
                    paragraph.Format.Alignment = GemBox.Presentation.HorizontalAlignment.Center;

                    paragraph.AddRun(fi.Name);

                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    sfd.Title = "Save PowerPoint Icons";
                    sfd.CheckFileExists = false;
                    sfd.CheckPathExists = true;
                    sfd.DefaultExt = "pptx";
                    sfd.Filter = "Powerpoint Files (*.pptx) | *.pptx";
                    sfd.FilterIndex = 1;
                    sfd.RestoreDirectory = true;
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        //string file = sfd.FileName;
                        presentation.Save(sfd.FileName);
                        Cursor = Cursors.Default;
                    }
                    Cursor = Cursors.Default;
                }
            }
        }

Expected PowerPoint output

I developed a similar tool.

The base class:

using System;
using System.Collections.Generic;

namespace akGraphics2Pptx
{
    class GraphicsConverter
    {
        static string[] usageText =
        {
            "akGraphics2Pptx - Graphics to Powerpoint/PDF Converter",
            "------------------------------------------------------",
            "",
            "Usage:",
            "",
            "akGraphics2Pptx graphics_file [graphics_file ...] output_file",
            "",
            "Enter more than one graphics file name to get more than one slide.",
            "Type of output file can be .pptx or .pdf",
            ""
        };

        protected IEnumerable<string> getFileNames(string[] args, string[] extensions)
        {
            List<string> names = new List<string>();

            foreach (string arg in args)
            {
                foreach (string ext in extensions)
                {
                    if (arg.ToLower().EndsWith("." + ext))
                    {
                        names.Add(arg);
                        break;
                    }
                }
            }

            return names;
        }

        /// <summary>
        /// Create a Powerpoint file with one slide per graphics file argument.
        /// The arguments can have any order. The files are distinguished by their extensions.
        /// </summary>
        /// <param name="args">The arguments</param>
        public virtual void convert(string[] args)
        {
        }

        protected void usage()
        {
            foreach (string s in usageText)
            {
                Console.WriteLine(s);
            }
        }
    }
}

The specific converter for PowerPoint output (I also have a PDF output):

using System;
using System.Collections.Generic;
using System.Linq;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using static Microsoft.Office.Core.MsoTriState;
using System.IO;

namespace akGraphics2Pptx
{
    class Graphics2PptxConverter : GraphicsConverter
    {
        private static string[] knownGraphicsFileExtensions = { "gif", "jpg", "png", "tif", "bmp", "wmf", "emf" };
        private static string[] powerpointFileExtensions = { "ppt", "pptx" };

        private IEnumerable<string> getGraphicsFileNames(string[] args)
        {
            return getFileNames(args, knownGraphicsFileExtensions);
        }

        private IEnumerable<string> getPowerpointFileNames(string[] args)
        {
            return getFileNames(args, powerpointFileExtensions);
        }

        /// <summary>
        /// Create a Powerpoint file with one slide per graphics file argument.
        /// The arguments can have any order. The files are distinguished by their extensions.
        /// </summary>
        /// <param name="args">The arguments</param>
        public void convert(string[] args)
        {
            var graphicsFileNames = getGraphicsFileNames(args);
            var powerpointFileNames = getPowerpointFileNames(args);

            if (!graphicsFileNames.Any() || (powerpointFileNames.Count() != 1))
            {
                usage();
            }
            else
            {
                //  inspired by http://stackoverflow.com/a/26372266/1911064

                Ppt.Application pptApplication = new Ppt.Application();

                // Create the Presentation File
                Ppt.Presentation pptPresentation = 
                    pptApplication.Presentations.Add(WithWindow: msoFalse);

                Ppt.CustomLayout customLayout = 
                    pptPresentation.SlideMaster.CustomLayouts[Ppt.PpSlideLayout.ppLayoutText];

                foreach (string graphicsFileName in graphicsFileNames)
                {
                    if (!File.Exists(graphicsFileName))
                    {
                        Console.WriteLine($"Graphics file {graphicsFileName} not found!");
                    }
                    else
                    {
                        // Create new Slide
                        Ppt.Slides slides = pptPresentation.Slides;
                        Ppt._Slide slide =
                            slides.AddSlide(Index: slides.Count + 1, pCustomLayout: customLayout);

                        // Add title
                        Ppt.TextRange objText = slide.Shapes[1].TextFrame.TextRange;
                        objText.Text = Path.GetFileName(graphicsFileName);
                        objText.Font.Name = "Arial";
                        objText.Font.Size = 32;

                        Ppt.Shape shape = slide.Shapes[2];
                        objText = shape.TextFrame.TextRange;
                        objText.Text = "Content goes here\nYou can add text";

                        string fullName = Path.GetFullPath(graphicsFileName);
                        slide.Shapes.AddPicture(fullName, msoFalse, msoTrue, shape.Left, shape.Top, shape.Width, shape.Height);

                        slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = graphicsFileName;
                    }
                }

                string pptFullName = Path.GetFullPath(powerpointFileNames.First());
                Console.WriteLine("Powerpoint file created: " + pptFullName);
                Console.WriteLine("Graphics slides:         " + pptPresentation.Slides.Count);
                Console.WriteLine("");

                pptPresentation.SaveAs(pptFullName, Ppt.PpSaveAsFileType.ppSaveAsDefault, msoTrue);
                pptPresentation.Close();
                pptApplication.Quit();
            }
        }
    }
}

Aspose.Slides for .NET is a Presentation Processing API for PowerPoint and OpenOffice formats. Aspose.Slides enable applications to read, write, protect, modify and convert presentations in .NET C#. Manage presentation text, shapes, charts, tables & animations, add audio & video to slides and preview slides.

More Link: https://products.aspose.com/slides/net/

internal class Program
{
    static void Main(string[] args)
    {
            string[] filesindirectory = Directory.GetFiles(@"C:\\IMG");// file folder

            string NameOfPPT = "_PPT_" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
        
            ////////////  var workbook = new Workbook(img);
           //////////// workbook.Save(img);
           
            using (Presentation pres = new Presentation())
            {
                     int SlideIndex = 0;
                    foreach (string img in filesindirectory)
                    {
                        int alpha = 200, red = 200, green = 200, blue = 200;
                        pres.Slides.AddEmptySlide(pres.LayoutSlides[SlideIndex]);
                        // Get the first slide
                        ISlide slide = pres.Slides[SlideIndex];
                        //Add an AutoShape of Rectangle type
                        IAutoShape ashp = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 5, 5, 700, 30);
                        //Add ITextFrame to the Rectangle
                        string Header = "Store: Name of Store |"+ SlideIndex.ToString() + " Visite Date: 2022-Sep-20  |" + "Category: ABC" + SlideIndex.ToString();
                        ashp.AddTextFrame(Header);
                        //Change the text color to Black (which is White by default)
                        ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.FillType = FillType.Solid;
                        ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
                        //Change the line color of the rectangle to White
                        ashp.ShapeStyle.LineColor.Color = System.Drawing.Color.DarkGoldenrod;
                        pres.HeaderFooterManager.SetAllHeadersText("Adding Header");
                        pres.HeaderFooterManager.SetAllHeadersVisibility(true);
                        pres.HeaderFooterManager.SetAllFootersText("System Auto generated");
                        pres.HeaderFooterManager.SetAllFootersVisibility(true);
                       // pres.HeaderFooterManager.SetAllDateTimesText(DateTime.Now.ToString("dd/MM/yyyy"));
                       // pres.HeaderFooterManager.SetAllDateTimesVisibility(true);
                        SlideIndex++;
                        // Instantiate the ImageEx class
                        System.Drawing.Image imgs = (System.Drawing.Image)new Bitmap(img);
                        IPPImage imgx = pres.Images.AddImage(imgs);
                        // Add Picture Frame with height and width equivalent of Picture
                        //IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 5, 5, 707, 525, imgx);// full placed image
                        IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 60,100, 600, 400, imgx);
                        // Apply some formatting to PictureFrameEx
                        pf.LineFormat.FillFormat.FillType = FillType.Gradient;
                        pf.LineFormat.FillFormat.SolidFillColor.Color = Color.Black;
                        pf.LineFormat.Width = 5;
                        pf.Rotation = 0;
                        // Get the center of the slide and calculate watermark's position
                        PointF center = new PointF(pres.SlideSize.Size.Width / 2, pres.SlideSize.Size.Height / 2);
                        float width = 100;
                        float height = 50;
                        float x = center.X - width / 2;
                        float y = center.Y - height / 2;
                        // Add watermark shape
                        IAutoShape watermarkShape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, x, y, width, height);
                        // Set fill type
                        watermarkShape.FillFormat.FillType = FillType.NoFill;
                        watermarkShape.LineFormat.FillFormat.FillType = FillType.NoFill;
                        // Set rotation angle
                        watermarkShape.Rotation = -45;
                        // Set text
                        ITextFrame watermarkTextFrame = watermarkShape.AddTextFrame("OOOOOOPPPPP");
                        IPortion watermarkPortion = watermarkTextFrame.Paragraphs[0].Portions[0];
                        // Set font size and fill type of the watermark
                        watermarkPortion.PortionFormat.FontHeight = 20;
                        watermarkPortion.PortionFormat.FillFormat.FillType = FillType.Solid;
                        watermarkPortion.PortionFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.FromArgb(alpha, red, green, blue);
                        // Lock Shapes from modifying
                        watermarkShape.ShapeLock.SelectLocked = false;
                        watermarkShape.ShapeLock.SizeLocked = false;
                        watermarkShape.ShapeLock.TextLocked = false;
                        watermarkShape.ShapeLock.PositionLocked = false;
                        watermarkShape.ShapeLock.GroupingLocked = false;
                    }
                   pres.Save(@"C:\\IMG\\PPT\\" + NameOfPPT + ".pptx", Aspose.Slides.Export.SaveFormat.Pptx);
            }
    }

   
}

Using free plugin

 public bool createPPT()
    {
       var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Where(c => c.PPTSlideInserted == false && c.Downloaded == true).ToList();
       // var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Take(10).ToList();

        if (data.Count > 0)
        {
            Application pptApplication = new Application();

            Microsoft.Office.Interop.PowerPoint.Slides slides;
            Microsoft.Office.Interop.PowerPoint._Slide slide;
            Microsoft.Office.Interop.PowerPoint.TextRange objText;
           // Microsoft.Office.Interop.PowerPoint.TextRange objText2;
            // Create the Presentation File
            Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);

            Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
            int SlideIndex = 1;
            foreach (AMR_IMG_TO_PPT_POC POCdata in data)
            {
                var pictureFileName = ImageToPptApp.Util.Constant.ImageStorePath + POCdata.Id + ".jpg";
                var StoreName = POCdata.StoreName;
                var Url = POCdata.FileCloudUrl;
                var Filename = POCdata.Id;
                var Titile = POCdata.Title;
                var PictureTime = POCdata.PictureTimeStamp;
                string Header = "Store: " + StoreName.ToString() + " |  Date Time:" + PictureTime.ToString() + " | Titile: " + Titile.ToString();

                // Create new Slide
                slides = pptPresentation.Slides;
                slide = slides.AddSlide(SlideIndex, customLayout);

                // Add title
                objText = slide.Shapes[1].TextFrame.TextRange;
                
                objText.Text = Header;
                objText.Font.Name = "Arial";
                objText.Font.Size = 20;

                //objText2 = slide.Shapes[2].TextFrame.TextRange;
                //objText2.Text = "test";
                //objText2.Font.Name = "Arial";
                //objText2.Font.Size = 10;

                //objText = slide.Shapes[2].TextFrame.TextRange;
                //objText.Text = "pp";

                Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2];
                slide.Shapes.AddPicture(pictureFileName, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 100, 100, 600, 400);

                slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = "MintPlus";
                SlideIndex++;
            }

            pptPresentation.SaveAs(ImageToPptApp.Util.Constant.PptStorePath + "ppp"+ ".pptx", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
            pptPresentation.Close();
            pptApplication.Quit();
        }

        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM