Beispiel #1
0
        static void ExportShapes()
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var    application = GetApplication();
            string strFolder   = folderBrowserDialog.SelectedPath;
            var    files       = Directory.GetFiles(strFolder).Where(d => d.Contains(".ppt")).ToArray();

            int i = 0;

            foreach (string file in files)
            {
                Presentation presSource = application.Presentations.Open(file);
                string       strPath    = Path.GetDirectoryName(file);
                foreach (Slide slide in presSource.Slides)
                {
                    foreach (NetOffice.PowerPointApi.Shape shape in slide.Shapes)
                    {
                        string       strSaveName = GetSaveName(strPath, shape.Name);
                        Presentation presNew     = application.Presentations.Add();
                        Slide        slideNew    = presNew.Slides.Add(1, NetOffice.PowerPointApi.Enums.PpSlideLayout.ppLayoutBlank);
                        shape.Copy();
                        NetOffice.PowerPointApi.ShapeRange shapeRange = slideNew.Shapes.Paste();
                        //shapeRange.Align(NetOffice.OfficeApi.Enums.MsoAlignCmd.msoAlignCenters | NetOffice.OfficeApi.Enums.MsoAlignCmd.msoAlignMiddles, NetOffice.OfficeApi.Enums.MsoTriState.msoTrue);
                        shapeRange.Select();
                        application.CommandBars.ExecuteMso("ObjectsAlignMiddleVerticalSmart");
                        application.CommandBars.ExecuteMso("ObjectsAlignCenterHorizontalSmart");
                        presNew.SaveAs(strSaveName);
                        Thread.Sleep(200);
                        presNew.Close();
                    }
                }
                presSource.Close();
                Console.WriteLine($"{++i}/{files.Length}");
            }
        }
        private void doWork()
        {
            PowerPoint.Presentation presentation          = null;
            PowerPoint.Application  applicationPowerPoint = null;
            Excel.Workbook          book             = null;
            Excel.Application       applicationExcel = null;

            try
            {
                Dictionary <String, Excel.Shape> excelShapesDictionary = new Dictionary <string, Excel.Shape>();


                Log.Information("Opening Excel Applicaiton");
                applicationExcel = new Excel.Application();
                applicationExcel.DisplayAlerts = false;

                Log.Information("Opening Excel File {0}", xlsx);
                book = applicationExcel.Workbooks.Open(xlsx, true, true);

                Boolean flagDouble = false;
                Log.Information("Iterating all shapes in all sheets and filtering shapes with name staring with \"#\"");
                foreach (Excel.Worksheet sheet in book.Worksheets)
                {
                    foreach (Excel.Shape shape in sheet.Shapes)
                    {
                        if (shape.Name.Length > 1 && shape.Name.Substring(0, 1) == "#")
                        {
                            if (excelShapesDictionary.ContainsKey(shape.Name.ToLower().Trim()))
                            {
                                Log.Error("\t\tSheet: {0} Shape Name : {1} Error!!! Shape with the same name exists", sheet.Name, shape.Name, shape.Width, shape.Height, shape.Left, shape.Top);
                                flagDouble = true;
                            }
                            else
                            {
                                Log.Information("\tSheet: {0} Shape Name : {1} ", sheet.Name, shape.Name, shape.Width, shape.Height, shape.Left, shape.Top);

                                excelShapesDictionary.Add(shape.Name.ToLower().Trim(), shape);
                            }
                        }
                    }
                }
                if (flagDouble)
                {
                    Log.Error("ERROR -Found shapes with the same name : Duplicated shapes need to be manually renamed in the Excel file before proceeding. Terminating run.");
                    thisForm.BeginInvoke((MethodInvoker)(() =>
                    {
                        MessageBox.Show(thisForm, "Duplicated shapes need to be manually renamed in the Excel file before proceeding.\nSee logs for more information", "ERROR - Found shapes with the same name", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }));
                    goto closeWorkbook;
                }

                Log.Information("Opening PowerPoint Applicaiton");
                applicationPowerPoint = new PowerPoint.Application();
                applicationPowerPoint.DisplayAlerts = PowerPoint.Enums.PpAlertLevel.ppAlertsNone;


                foreach (string pptxSingle in pptx)
                {
                    Dictionary <int, List <PowerPoint.Shape> > powerpointShapesSheetDictionary = new Dictionary <int, List <PowerPoint.Shape> >();

                    Log.Information("Opening Presentation {0}", pptxSingle);
                    presentation = applicationPowerPoint.Presentations.Open(pptxSingle, true, true, false);


                    Log.Information("Iterating all shapes in all slides and filtering shapes with name staring with \"#\"");
                    Boolean datamissing = false;
                    foreach (PowerPoint.Slide slide in presentation.Slides)
                    {
                        foreach (PowerPoint.Shape shape in slide.Shapes)
                        {
                            if (shape.Name.Length > 1 && shape.Name.Substring(0, 1) == "#")
                            {
                                if (!excelShapesDictionary.ContainsKey(shape.Name.ToLower().Trim()))
                                {
                                    Log.Information("\t\tData Missing for Slide No : {0} Shape Name : {1} ", slide.SlideNumber, shape.Name, shape.Width, shape.Height, shape.Left, shape.Top);
                                    datamissing = true;
                                }
                                else
                                {
                                    Log.Information("\tFound data for Slide No : {0} Shape Name : {1} ", slide.SlideNumber, shape.Name, shape.Width, shape.Height, shape.Left, shape.Top);
                                }
                                if (!powerpointShapesSheetDictionary.ContainsKey(slide.SlideNumber))
                                {
                                    powerpointShapesSheetDictionary.Add(slide.SlideNumber, new List <PowerPoint.Shape>());
                                }
                                powerpointShapesSheetDictionary[slide.SlideNumber].Add(shape);
                            }
                            else
                            {
                                /*
                                 * Log.Information("\tFound data for Slide No : {0} Shape Name : {1} Size(w x h) : {2} x {3} Position(left x top) : {4} , {5}", slide.SlideNumber, shape.Name, shape.Width, shape.Height, shape.Left, shape.Top);
                                 * if (shape.HasTextFrame == Office.Enums.MsoTriState.msoTrue && shape.TextFrame.HasText == Office.Enums.MsoTriState.msoTrue)
                                 *  shape.TextFrame.TextRange.Replace("|*test*|", "123");
                                 */
                            }
                        }
                    }
                    if (datamissing)
                    {
                        Log.Error("ERROR - Match not found for shape/s in presentation : All shapes starting with \"#\"in the presentation should have matching shape in the excel.");
                        thisForm.BeginInvoke((MethodInvoker)(() =>
                        {
                            MessageBox.Show(thisForm, "All shapes starting with \"#\"in the presentation should have matching shape in the excel.\nSee logs for more information", "ERROR - Match not found for shape/s in presentation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }));
                        goto closePresentation;
                    }


                    Log.Information("Start of Update");
                    foreach (int slideNo in powerpointShapesSheetDictionary.Keys)
                    {
                        foreach (var shape in powerpointShapesSheetDictionary[slideNo])
                        {
                            excelShapesDictionary[shape.Name.ToLower()].Copy();
                            Thread.Sleep(100);
                            PowerPoint.ShapeRange shapes = presentation.Slides[slideNo].Shapes.PasteSpecial(PowerPointEnums.PpPasteDataType.ppPasteJPG);
                            string shape_name            = shape.Name;
                            float  shape_top             = shape.Top;
                            float  shape_left            = shape.Left;

                            float shape_width  = shape.Width;
                            float shape_height = shape.Height;

                            shapes[1].Name = shape_name;
                            shapes[1].Top  = shape_top;
                            shapes[1].Left = shape_left;

                            shapes[1].ScaleWidth(shape.Width / shapes[1].Width, Office.Enums.MsoTriState.msoFalse);
                            //shapes[1].Height = shape_height;

                            shape.Delete();

                            Log.Information(" Updated {0} on slide {1}", shape_name, slideNo);
                        }
                    }
                    Log.Information("End of Update");

                    String outputfile = Path.Combine(output_folder, new FileInfo(pptxSingle).Name);
                    Log.Information("Saving a copy of updated Presentation to {0}", outputfile);
                    presentation.SaveCopyAs(outputfile);

closePresentation:
                    Log.Information("Closing Presentation");

                    presentation.Close();
                }


                Log.Information("Closing PowerPoint Applicaiton");
                applicationPowerPoint.Quit();
                applicationPowerPoint.Dispose();

closeWorkbook:
                Log.Information("Closing Excel File");
                book.Close();

                Log.Information("Closing Excel Applicaiton");
                applicationExcel.Quit();
                applicationExcel.Dispose();


                Log.Information("Done");
                thisForm.BeginInvoke((MethodInvoker)(() =>
                {
                    button1.Enabled = true;
                    button2.Enabled = true;
                    buttonFolder.Enabled = true;
                    button3.Enabled = true;

                    listView1.Enabled = true;
                    listView2.Enabled = true;
                    listView3.Enabled = true;
                    MessageBox.Show(thisForm, "Task Completed. Check logs for more info", "Completed", MessageBoxButtons.OK, MessageBoxIcon.None);
                }));
            }
            catch (Exception e)
            {
                Log.Error("Fatal Error - " + e.ToString());
                thisForm.BeginInvoke((MethodInvoker)(() =>
                {
                    MessageBox.Show(thisForm, e.ToString(), "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    button1.Enabled = true;
                    button2.Enabled = true;
                    buttonFolder.Enabled = true;
                    button3.Enabled = true;

                    listView1.Enabled = true;
                    listView2.Enabled = true;
                    listView3.Enabled = true;
                }));
                try
                {
                    presentation.Close();
                }
                catch (Exception ee) { }
                try
                {
                    applicationPowerPoint.Quit();
                    applicationPowerPoint.Dispose();
                }
                catch (Exception ee) { }
                try
                {
                    book.Close();
                }
                catch (Exception ee) { }
                try
                {
                    applicationExcel.Quit();
                    applicationExcel.Dispose();
                }
                catch (Exception ee) { }
            }
        }