Ejemplo n.º 1
0
        /// <summary>
        /// 文字替换
        /// </summary>
        public void ReplaceText(KeyValuePair <string, string> kv)
        {
            string OldText = string.Empty;
            string NewText = string.Empty;

            OldText = kv.Key;
            NewText = kv.Value;

            int num = PageNum();

            for (int j = 1; j <= num; j++)
            {
                POWERPOINT.Slide slide = objPresSet.Slides[j];
                for (int i = 1; i <= slide.Shapes.Count; i++)
                {
                    try
                    {
                        POWERPOINT.Shape shape = slide.Shapes[i];
                        if (shape.TextFrame != null)
                        {
                            POWERPOINT.TextFrame textFrame = shape.TextFrame;
                            string oldText = textFrame.TextRange.Text;
                            string newText = textFrame.TextRange.Text.Replace(OldText, NewText);
                            if (textFrame.TextRange != null && !string.IsNullOrEmpty(oldText))
                            {
                                textFrame.TextRange.Replace(oldText, newText);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private static void SelectAndAction(int start, RangeCommand command, Action <PowerPoint.TextRange> action)
        {
            PowerPoint.TextFrame parent = Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange.Parent;
            var range = parent.TextRange.Characters(start + command.Start, command.Length);

            action(range);
        }
Ejemplo n.º 3
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Add a blank slide
            PowerPoint.Slide sld = Application.ActivePresentation.Slides[0];

            //Add a 15 x 15 table
            PowerPoint.Shape shp = sld.Shapes.AddTable(15, 15, 10, 10, 200, 300);
            PowerPoint.Table tbl = shp.Table;
            int i = -1;
            int j = -1;

            //Loop through all the rows
            foreach (PowerPoint.Row row in tbl.Rows)
            {
                i = i + 1;
                j = -1;

                //Loop through all the cells in the row
                foreach (PowerPoint.Cell cell in row.Cells)
                {
                    j = j + 1;
                    //Get text frame of each cell
                    PowerPoint.TextFrame tf = cell.Shape.TextFrame;
                    //Add some text
                    tf.TextRange.Text = "T" + i.ToString() + j.ToString();
                    //Set font size of the text as 10
                    tf.TextRange.Paragraphs(0, tf.TextRange.Text.Length).Font.Size = 10;
                }
            }
        }
Ejemplo n.º 4
0
        public string FindInPPT(string oldText, string filePath)
        {
            int    num  = PageNum();
            string text = "";

            for (int j = 1; j <= num; j++)
            {
                POWERPOINT.Slide slide = objPresSet.Slides[j];
                for (int i = 1; i <= slide.Shapes.Count; i++)
                {
                    POWERPOINT.Shape shape = slide.Shapes[i];
                    if (shape.TextFrame != null)
                    {
                        POWERPOINT.TextFrame textFrame = shape.TextFrame;
                        try
                        {
                            if (textFrame.TextRange != null)
                            {
                                text += textFrame.TextRange.Text;
                            }
                        }
                        catch
                        { }
                    }
                }
            }
            Regex  regex    = new Regex(oldText);
            var    matches  = regex.Matches(text);
            string fileName = Path.GetFileName(filePath);
            String result   = string.Format("在文件:{0}中-----找到{1}个\"{2}\"", fileName, matches.Count, oldText);

            return(result);
        }
Ejemplo n.º 5
0
 private void WriteToTextbox(string text, PowerPoint.Shape textBox, int fontSize)
 {
     PowerPoint.TextFrame pptTextFrame = textBox.TextFrame;
     PowerPoint.TextRange pptTextRange = pptTextFrame.TextRange;
     pptTextRange.Text      = text;
     pptTextRange.Font.Size = fontSize;
 }
Ejemplo n.º 6
0
        private static string GetNotesFirstLine(SlideShowWindow slideShowWindow)
        {
            var slide  = slideShowWindow.View.Slide;
            var result = slideShowWindow.View.Slide.HasNotesPage;

            if (result == MsoTriState.msoTrue)
            {
                var notes  = slide.NotesPage;
                var shapes = notes.Shapes;
                foreach (Shape shape in shapes)
                {
                    if (shape.Type == MsoShapeType.msoPlaceholder && shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderBody)
                    {
                        if (shape.HasTextFrame == MsoTriState.msoTrue)
                        {
                            TextFrame textFrame = shape.TextFrame;
                            if (textFrame.HasText == MsoTriState.msoTrue)
                            {
                                TextRange textRange      = textFrame.TextRange;
                                string    allText        = textRange.Text;
                                string[]  lines          = allText.Split('\r');
                                string    notesFirstLine = lines.FirstOrDefault();
                                return(notesFirstLine);
                            }
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 7
0
 private void WriteToLyricsTextbox(string text, PowerPoint.Shape textBox, int fontSize)
 {
     PowerPoint.TextFrame pptTextFrame = textBox.TextFrame;
     PowerPoint.TextRange pptTextRange = pptTextFrame.TextRange;
     pptTextRange.Text      = text;
     pptTextRange.Font.Size = fontSize;
     pptTextRange.ParagraphFormat.Alignment = PowerPoint.PpParagraphAlignment.ppAlignCenter;
 }
Ejemplo n.º 8
0
 private void ColorShapeWithColor(PowerPoint.TextRange text, int rgb, MODE mode)
 {
     PowerPoint.TextFrame frame         = text.Parent as PowerPoint.TextFrame;
     PowerPoint.Shape     selectedShape = frame.Parent as PowerPoint.Shape;
     if (mode != MODE.NONE)
     {
         ColorShapeWithColor(selectedShape, rgb, mode);
     }
 }
Ejemplo n.º 9
0
        public Generate_PPT(string Title, string text, string FullOutputPath, string[] imageLinks)
        {
            //Initialize variables
            Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Slides      slides;
            Microsoft.Office.Interop.PowerPoint._Slide      slide;
            Microsoft.Office.Interop.PowerPoint.TextRange   objText;

            // Create the Presentation File - msoFalse to hide presentation
            Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoFalse);

            Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];

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

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

            // Add text
            Clipboard.SetData(DataFormats.Rtf, text);
            Microsoft.Office.Interop.PowerPoint.TextFrame tf = slide.Shapes[2].TextFrame;
            Microsoft.Office.Interop.PowerPoint.TextRange tr = tf.TextRange;
            tr.PasteSpecial(PpPasteDataType.ppPasteRTF);

            //Add images
            Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2];
            int i = 1;

            foreach (string image in imageLinks)
            {
                if (i == 1)
                {
                    slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left + (shape.Width / 2), shape.Top, shape.Width / 2, shape.Height / 2);
                }
                else if (i == 2)
                {
                    slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top + (shape.Height / 2), shape.Width / 2, shape.Height / 2);
                }
                else if (i == 3)
                {
                    slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left + (shape.Width / 2), shape.Top + (shape.Height / 2), shape.Width / 2, shape.Height / 2);
                }
                i++;
            }

            //save PPT and close
            pptPresentation.SaveAs(FullOutputPath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
            pptPresentation.Close();
            pptApplication.Quit();
        }
Ejemplo n.º 10
0
 public void InsertText(string textToBeInserted, int textPos)
 {
     if (textToBeInserted != "")
     {
         if (oShapes[textPos] != null)
         {
             PowerPoint.Shape     oShape    = oShapes[textPos];
             PowerPoint.TextFrame oTxtFrame = oShape.TextFrame;
             PowerPoint.TextRange oTxtRange = oTxtFrame.TextRange;
             oTxtRange.Text = textToBeInserted;
         }
         else
         {
             RobotMessageBox.Show("There is no element to add your text to. Have you selected appropriate slide layout?");
         }
     }
 }
Ejemplo n.º 11
0
 private void ReplaceTextInSlide(PowerPoint.Slide slide, string from, string to)
 {
     foreach (PowerPoint.Shape shape in slide.Shapes)
     {
         PowerPoint.TextFrame frame = shape.TextFrame;
         if (frame == null || frame.HasText == Office.MsoTriState.msoFalse)
         {
             continue;
         }
         string text = frame.TextRange.Text;
         if (text.Length == 0)
         {
             continue;
         }
         text = text.Replace(from, to);
         frame.TextRange.Text      = text;
         frame.TextRange.Font.Name = "微软雅黑";
     }
 }
        /// <summary>
        /// Retrieves color of the selected shape(s).
        /// </summary>
        /// <param name="mode"></param>
        /// <returns></returns>
        private Color GetSelectedShapeColor(MODE mode)
        {
            SelectShapes();
            if (_selectedShapes == null && _selectedText == null)
            {
                return(dataSource.SelectedColor);
            }

            if (this.GetCurrentSelection().Type == PowerPoint.PpSelectionType.ppSelectionShapes)
            {
                return(GetSelectedShapeColor(_selectedShapes, mode));
            }
            if (this.GetCurrentSelection().Type == PowerPoint.PpSelectionType.ppSelectionText)
            {
                PowerPoint.TextFrame frame         = _selectedText.Parent as PowerPoint.TextFrame;
                PowerPoint.Shape     selectedShape = frame.Parent as PowerPoint.Shape;
                return(GetSelectedShapeColor(selectedShape, mode));
            }

            return(dataSource.SelectedColor);
        }
Ejemplo n.º 13
0
        private Color GetSelectedShapeColor()
        {
            SelectShapes();
            if (_selectedShapes == null && _selectedText == null)
            {
                return(dataSource.SelectedColor);
            }

            if (PowerPointCurrentPresentationInfo.CurrentSelection.Type == PpSelectionType.ppSelectionShapes)
            {
                return(GetSelectedShapeColor(_selectedShapes));
            }
            if (PowerPointCurrentPresentationInfo.CurrentSelection.Type == PpSelectionType.ppSelectionText)
            {
                PowerPoint.TextFrame frame         = _selectedText.Parent as PowerPoint.TextFrame;
                PowerPoint.Shape     selectedShape = frame.Parent as PowerPoint.Shape;
                return(GetSelectedShapeColor(selectedShape));
            }

            return(dataSource.SelectedColor);
        }
Ejemplo n.º 14
0
        public string ReplaceAll(string OldText, string NewText, string filePath)
        {
            int num   = PageNum();
            int total = 0;

            for (int j = 1; j <= num; j++)
            {
                POWERPOINT.Slide slide = objPresSet.Slides[j];
                for (int i = 1; i <= slide.Shapes.Count; i++)
                {
                    POWERPOINT.Shape shape = slide.Shapes[i];
                    if (shape.TextFrame != null)
                    {
                        POWERPOINT.TextFrame textFrame = shape.TextFrame;
                        try
                        {
                            if (textFrame.TextRange != null)
                            {
                                string text    = textFrame.TextRange.Text;
                                Regex  regex   = new Regex(OldText);
                                var    matches = regex.Matches(text);
                                //需求替换的次数
                                foreach (var macth in matches)
                                {
                                    textFrame.TextRange.Replace(OldText, NewText);
                                    total++;
                                }
                            }
                        }
                        catch
                        { }
                    }
                }
            }
            string fileName = Path.GetFileName(filePath);
            string reslut   = string.Format("在文件{0}-----替换了{1}个{2}", fileName, total, OldText);

            return(reslut);
        }
Ejemplo n.º 15
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Create a presentation
            PowerPoint.Presentation pres = Globals.ThisAddIn.Application
                                           .Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            //Add a blank slide
            PowerPoint.Slide sld = pres.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutBlank);

            //Add a 15 x 15 table
            PowerPoint.Shape shp = sld.Shapes.AddTable(15, 15, 10, 10, pres.PageSetup.SlideWidth - 20, 300);
            PowerPoint.Table tbl = shp.Table;
            int i = -1;
            int j = -1;

            //Loop through all the rows
            foreach (PowerPoint.Row row in tbl.Rows)
            {
                i = i + 1;
                j = -1;

                //Loop through all the cells in the row
                foreach (PowerPoint.Cell cell in row.Cells)
                {
                    j = j + 1;
                    //Get text frame of each cell
                    PowerPoint.TextFrame tf = cell.Shape.TextFrame;
                    //Add some text
                    tf.TextRange.Text = "T" + i.ToString() + j.ToString();
                    //Set font size of the text as 10
                    tf.TextRange.Paragraphs(0, tf.TextRange.Text.Length).Font.Size = 10;
                }
            }

            //Save the presentation to disk
            pres.SaveAs("tblVSTO.ppt",
                        PowerPoint.PpSaveAsFileType.ppSaveAsPresentation,
                        Microsoft.Office.Core.MsoTriState.msoFalse);
        }
Ejemplo n.º 16
0
        private string[] ParseText(Ppt.TextFrame text_frame)
        {
            const StringSplitOptions nOMTs = StringSplitOptions.RemoveEmptyEntries;

            Ppt.TextRange run;

            for (int i = 1; i < image_count - 1; ++i)
            {
                run = text_frame.TextRange.Runs(i);
                if (run == null)
                {
                    break;
                }
                run.RemovePeriods();
                if (run.Font.Bold == MsoTriState.msoTrue)
                {
                    var punctless = RemovePunct(run.Text.Trim(), '\"', '\'', '?', '*', '\r');
                    terms.AddRange(punctless.Split(new char[] { '\t', '\n' }, nOMTs));
                }
            }

            return(terms.ToArray());
        }
Ejemplo n.º 17
0
        public static void createNewSlide(Slides oSlides, int slideNumber, string slideText, float advanceSec)
        {
            /*Slide oSlide=null;
             * if (slideText == "")
             * {
             *  oSlide = oSlides.Add(slideNumber, PpSlideLayout.ppLayoutBlank);
             *  oSlide.FollowMasterBackground = MsoTriState.msoFalse;
             *  oSlide.Background.Fill.ForeColor.RGB = colorizing(System.Windows.Media.Colors.Black);
             * }
             * else
             * {*/
            // Slide oSlide = oSlides.Add(slideNumber, PpSlideLayout.ppLayoutText);
            Slide oSlide = oSlides.Add(slideNumber, PpSlideLayout.ppLayoutTitleOnly);

            oSlide.FollowMasterBackground        = MsoTriState.msoFalse;
            oSlide.Background.Fill.ForeColor.RGB = colorizing(System.Windows.Media.Colors.Black);

            Microsoft.Office.Interop.PowerPoint.Shapes    oShapes   = oSlide.Shapes;
            Microsoft.Office.Interop.PowerPoint.Shape     oShape    = oShapes[1];
            Microsoft.Office.Interop.PowerPoint.TextFrame oTxtFrame = oShape.TextFrame;

            TextRange oTxtRange = oTxtFrame.TextRange;

            oTxtRange.Text = slideText;
            // oTxtRange = setItalic(oTxtRange);

            oTxtRange.Font.Size = 44;
            oTxtRange.Font.Name = "Arial";
            oTxtRange.ParagraphFormat.Alignment = PpParagraphAlignment.ppAlignCenter;
            oTxtRange.Font.Color.RGB            = colorizing(System.Windows.Media.Colors.White);

            //repositing text in the shape does not work
            //oTxtFrame.MarginTop = 10;
            //oShape.Top = 2;
            // }
            addTimecodeToSlide(oSlide, advanceSec);
        }
Ejemplo n.º 18
0
        public void InsertSlide(int slidePosition, string titleText, string slideText, string layout)
        {
            PowerPoint.PpSlideLayout slideLayout = PowerPoint.PpSlideLayout.ppLayoutTitle;
            switch (layout)
            {
            case "ContentWithCaption":
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutTitle;
                break;

            case "TitleOnly":
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutTitleOnly;
                break;

            case "Title":
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutTitle;
                break;

            case "ObjectAndText":
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutObjectAndText;
                break;

            case "Object":
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutObject;
                break;

            default:
                slideLayout = PowerPoint.PpSlideLayout.ppLayoutObject;
                break;
            }
            if (slidePosition <= oSlides.Count + 1)
            {
                oSlide = oSlides.Add(slidePosition, slideLayout);
            }
            else
            {
                RobotMessageBox.Show("Your slide insert position is incorrect. Please check your number.");
                return;
            }
            oShapes = oSlide.Shapes;
            if (titleText != "")
            {
                PowerPoint.Shape     oShape    = oShapes[1];
                PowerPoint.TextFrame oTxtFrame = oShape.TextFrame;
                PowerPoint.TextRange oTxtRange = oTxtFrame.TextRange;
                oTxtRange.Text = titleText;
            }
            if (slideText != "")
            {
                if (oShapes[2] != null)
                {
                    PowerPoint.Shape     oShape    = oShapes[2];
                    PowerPoint.TextFrame oTxtFrame = oShape.TextFrame;
                    PowerPoint.TextRange oTxtRange = oTxtFrame.TextRange;
                    oTxtRange.Text = slideText;
                }
                else
                {
                    RobotMessageBox.Show("There is no element to add your text to. Have you selected appropriate slide layout?");
                }
            }
        }
Ejemplo n.º 19
0
 public static void RestoreSelection(Range selection)
 {
     PowerPoint.TextFrame parent = Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange.Parent;
     parent.TextRange.Characters(selection.Start, selection.Length).Select();
 }
        public static void AutomatePowerPoint()
        {
            PowerPoint.Application   oPowerPoint = null;
            PowerPoint.Presentations oPres       = null;
            PowerPoint.Presentation  oPre        = null;
            PowerPoint.Slides        oSlides     = null;
            PowerPoint.Slide         oSlide      = null;
            PowerPoint.Shapes        oShapes     = null;
            PowerPoint.Shape         oShape      = null;
            PowerPoint.TextFrame     oTxtFrame   = null;
            PowerPoint.TextRange     oTxtRange   = null;

            try
            {
                // Create an instance of Microsoft PowerPoint and make it
                // invisible.
                oPowerPoint = new PowerPoint.Application();

                // By default PowerPoint is invisible, till you make it visible.
                // oPowerPoint.Visible = Office.MsoTriState.msoFalse;



                // Create a new Presentation.

                oPres = oPowerPoint.Presentations;
                oPre  = oPres.Add(Office.MsoTriState.msoTrue);
                Console.WriteLine("A new presentation is created");

                // Insert a new Slide and add some text to it.

                Console.WriteLine("Insert a slide");
                oSlides = oPre.Slides;
                oSlide  = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutText);

                Console.WriteLine("Add some texts");
                oShapes        = oSlide.Shapes;
                oShape         = oShapes[1];
                oTxtFrame      = oShape.TextFrame;
                oTxtRange      = oTxtFrame.TextRange;
                oTxtRange.Text = "All-In-One Code Framework";

                // Save the presentation as a pptx file and close it.

                Console.WriteLine("Save and close the presentation");

                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.pptx";
                oPre.SaveAs(fileName,
                            PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                            Office.MsoTriState.msoTriStateMixed);
                oPre.Close();

                // Quit the PowerPoint application.

                Console.WriteLine("Quit the PowerPoint application");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomatePowerPoint throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged PowerPoint COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oTxtRange != null)
                {
                    Marshal.FinalReleaseComObject(oTxtRange);
                    oTxtRange = null;
                }
                if (oTxtFrame != null)
                {
                    Marshal.FinalReleaseComObject(oTxtFrame);
                    oTxtFrame = null;
                }
                if (oShape != null)
                {
                    Marshal.FinalReleaseComObject(oShape);
                    oShape = null;
                }
                if (oShapes != null)
                {
                    Marshal.FinalReleaseComObject(oShapes);
                    oShapes = null;
                }
                if (oSlide != null)
                {
                    Marshal.FinalReleaseComObject(oSlide);
                    oSlide = null;
                }
                if (oSlides != null)
                {
                    Marshal.FinalReleaseComObject(oSlides);
                    oSlides = null;
                }
                if (oPre != null)
                {
                    Marshal.FinalReleaseComObject(oPre);
                    oPre = null;
                }
                if (oPres != null)
                {
                    Marshal.FinalReleaseComObject(oPres);
                    oPres = null;
                }
                if (oPowerPoint != null)
                {
                    Marshal.FinalReleaseComObject(oPowerPoint);
                    oPowerPoint = null;
                }
            }
        }
Ejemplo n.º 21
0
        public static void generate(GenInfo genInfo)
        {
            Powerpoint.Application powerApp = new Powerpoint.Application();

            Powerpoint.Presentation awardsPresentation = powerApp.Presentations.Open(genInfo.awardPowerpointTemplateFile, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);

            int startingNumberOfSlides = awardsPresentation.Slides.Count;

            Excel.Application excelApp        = new Excel.Application();
            Excel.Workbook    awardsWorkbook  = excelApp.Workbooks.Open(genInfo.awardExcelFile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "/t", false, false, 0, true, 1, 0);
            Excel.Worksheet   awardsWorksheet = awardsWorkbook.Worksheets[1];

            int lastUsedRow = awardsWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;

            for (int rowIndex = genInfo.startingRow; rowIndex <= lastUsedRow; rowIndex++)
            {
                if (getValueOfCell(ref awardsWorksheet, genInfo.studentCodeColumn, rowIndex) == "")
                {
                    continue;
                }

                Powerpoint.Slide currentSlide = awardsPresentation.Slides.AddSlide(awardsPresentation.Slides.Count + 1, awardsPresentation.SlideMaster.CustomLayouts[genInfo.awardLayoutIndex]);

                Powerpoint.Shapes slideShapes = currentSlide.Shapes;

                Powerpoint.Placeholders placeholders = slideShapes.Placeholders;

                int placeholderIndex = 1;
                foreach (Powerpoint.Shape shape in placeholders)
                {
                    // Set Student Name
                    if (placeholderIndex == genInfo.awardStudentNamePlaceholderIndex)
                    {
                        shape.TextFrame.TextRange.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentNameColumn, rowIndex);
                    }

                    // Set Student Form
                    if (placeholderIndex == genInfo.awardStudentFormPlaceholderIndex)
                    {
                        Powerpoint.TextFrame frame = shape.TextFrame;

                        Powerpoint.TextRange range = frame.TextRange;
                        range.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentFormColumn, rowIndex);
                    }

                    // Set award
                    if (placeholderIndex == genInfo.awardAwardTitlePlaceholderIndex)
                    {
                        shape.TextFrame.TextRange.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentAwardColumn, rowIndex);
                    }

                    // Set picture
                    if (placeholderIndex == genInfo.awardStudentPicturePlaceholderIndex)
                    {
                        string studentCode = getValueOfCell(ref awardsWorksheet, genInfo.studentCodeColumn, rowIndex);
                        string pictureFile = findFileInFolder(genInfo.picturesFolder, studentCode + genInfo.pictureFileExtension);
                        if (pictureFile != "")
                        {
                            shape.Fill.UserPicture(pictureFile);
                        }
                        else
                        {
                            Console.Out.WriteLine("Picture for " + studentCode + " not found");
                        }
                    }
                    placeholderIndex++;
                }
            }

            for (int i = 0; i < startingNumberOfSlides; i++)
            {
                awardsPresentation.Slides[1].Delete();
            }



            awardsPresentation.SaveAs(Path.GetDirectoryName(genInfo.awardPowerpointTemplateFile) + "/Output.pptx");
        }
Ejemplo n.º 22
0
        public static void AutomatePowerPoint()
        {
            PowerPoint.Application   oPowerPoint = null;
            PowerPoint.Presentations oPres       = null;
            PowerPoint.Presentation  oPre        = null;
            PowerPoint.Slides        oSlides     = null;
            PowerPoint.Slide         oSlide      = null;
            PowerPoint.Shapes        oShapes     = null;
            PowerPoint.Shape         oShape      = null;
            PowerPoint.TextFrame     oTxtFrame   = null;
            PowerPoint.TextRange     oTxtRange   = null;

            try
            {
                // 创建一个Microsoft PowerPoint实例并使其不可见。

                oPowerPoint = new PowerPoint.Application();

                // 默认情况下PowerPoint不可见,直道你使它可见。
                //oPowerPoint.Visible = Office.MsoTriState.msoFalse;

                // 创建一个新的演示文稿。

                oPres = oPowerPoint.Presentations;
                oPre  = oPres.Add(Office.MsoTriState.msoTrue);
                Console.WriteLine("一个新的演示文稿被建立");

                // 插入一个幻灯片,并为幻灯片加入一些文本。

                Console.WriteLine("插入一个幻灯片");
                oSlides = oPre.Slides;
                oSlide  = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutText);

                Console.WriteLine("添加一些文本");
                oShapes        = oSlide.Shapes;
                oShape         = oShapes[1];
                oTxtFrame      = oShape.TextFrame;
                oTxtRange      = oTxtFrame.TextRange;
                oTxtRange.Text = "一站式代码框架";

                // 保存此演示文稿为pptx文件并将其关闭。

                Console.WriteLine("保存并退出演示文稿");

                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.pptx";
                oPre.SaveAs(fileName,
                            PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                            Office.MsoTriState.msoTriStateMixed);
                oPre.Close();

                // 退出PowerPoint应用程序

                Console.WriteLine("退出PowerPoint应用程序");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("解决方案1.AutomatePowerPoint抛出的错误: {0}",
                                  ex.Message);
            }
            finally
            {
                // 显式地调用Marshal.FinalReleaseComObject访问所有的存取器对象清除
                // 非托管的COM资源。
                // 参见http://support.microsoft.com/kb/317109

                if (oTxtRange != null)
                {
                    Marshal.FinalReleaseComObject(oTxtRange);
                    oTxtRange = null;
                }
                if (oTxtFrame != null)
                {
                    Marshal.FinalReleaseComObject(oTxtFrame);
                    oTxtFrame = null;
                }
                if (oShape != null)
                {
                    Marshal.FinalReleaseComObject(oShape);
                    oShape = null;
                }
                if (oShapes != null)
                {
                    Marshal.FinalReleaseComObject(oShapes);
                    oShapes = null;
                }
                if (oSlide != null)
                {
                    Marshal.FinalReleaseComObject(oSlide);
                    oSlide = null;
                }
                if (oSlides != null)
                {
                    Marshal.FinalReleaseComObject(oSlides);
                    oSlides = null;
                }
                if (oPre != null)
                {
                    Marshal.FinalReleaseComObject(oPre);
                    oPre = null;
                }
                if (oPres != null)
                {
                    Marshal.FinalReleaseComObject(oPres);
                    oPres = null;
                }
                if (oPowerPoint != null)
                {
                    Marshal.FinalReleaseComObject(oPowerPoint);
                    oPowerPoint = null;
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Scans pptx file starting slide with specified index
        /// <para>Can throw exceptions from inner calls.</para>
        /// </summary>
        /// <param name="pptPresentation"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public List <IFileItem> UpdateIndex(PPT.Presentation pptPresentation, int startIndex)
        {
            PPT.Slide     slide             = null;
            dynamic       addin             = null;
            string        tempIndexFile     = null;
            List <string> tempFilesToDelete = new List <string>();

            try
            {
                List <IFileItem> newItems = new List <IFileItem>();

                string tempImgFile = null;

                addin = GetAddin();

                tempIndexFile = Path.GetTempFileName();

                using (FileStream zipFile = new FileStream(indexFileFullName, FileMode.Open))
                {
                    using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Update))
                    {
                        ZipArchiveEntry indexFileEntry = zip.GetEntry(ZIPEntry_IndexFileName);
                        indexFileEntry.ExtractToFile(tempIndexFile, true);

                        PPT.Slides gSlides = pptPresentation.Slides;
                        for (int idx = startIndex; idx <= gSlides.Count; idx++)
                        {
                            slide = gSlides[idx];
                            bool isShapeItem = slide.Tags[ShapeTag.Tag] != "";
                            #region Collect Item Data

                            string title = "";

                            StringBuilder sbKeyWords  = new StringBuilder();
                            StringBuilder sbChartType = new StringBuilder();
                            StringBuilder sbDescr     = new StringBuilder();

                            int chartsCount = 0;

                            if (isShapeItem)
                            {
                                try
                                {
                                    PPT.Shape shape = slide.Shapes[1]; //If it is the Shape we expect it to be the only shape on this slide
                                    if (addin?.IsExcelChart(shape) ?? false)
                                    {
                                        chartsCount++;
                                        #region Get Chart Description
                                        string[] str = addin.GetChartDescription(shape);
                                    }
                                    #endregion Get MG Chart Description
                                    else
                                    {
                                        //TODO: Get something from non chart shape
                                        title = shape.Title.Replace("\n", " ").Replace("  ", " ");
                                        sbKeyWords.Append(shape.Name);
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                            else
                            { //Slide
                                foreach (PPT.Shape shape in slide.Shapes)
                                {
                                    try
                                    {
                                        if (shape.Name == "Title 1" && title == "")
                                        {
                                            PPT.TextFrame frame = shape.TextFrame;
                                            PPT.TextRange txt   = frame.TextRange;
                                            title = txt.Text.Replace("\n", " ").Replace("  ", " ");
                                            txt   = null;
                                            frame = null;
                                        }
                                        if (addin?.IsExceloChart(shape) ?? false)
                                        {
                                            chartsCount++;
                                        }
                                    }
                                    catch { }
                                }
                            }
                            sbKeyWords.Append(title);
                            sbKeyWords.Append(" ");

                            tempImgFile = Path.GetTempFileName();
                            float ratio = pptPresentation.PageSetup.SlideHeight / pptPresentation.PageSetup.SlideWidth;
                            slide.Export(tempImgFile, "png", ThumbnailWidth, (int)(ThumbnailWidth * ratio));
                            zip.CreateEntryFromFile(tempImgFile, ZIPEntry_ImagesFolder + idx + ".png");
                            Bitmap img = null;

                            using (var fs = new System.IO.FileStream(tempImgFile, System.IO.FileMode.Open))
                            {
                                img = new Bitmap(fs);
                            }

                            sbChartType.Replace("\n", " ");

                            #endregion

                            IFileItem item = LibraryFile.CreateItem(idx);
                            {
                                item.Image = img;
                                item.Type  = (
                                    (Func <ItemType>)(() => {
                                    if (isShapeItem)
                                    {
                                        return(chartsCount == 0 ? ItemType.Shape : ItemType.Chart);
                                    }
                                    else
                                    {
                                        //                                            if (mgChartsCount == 0)
                                        {
                                            return(ItemType.Slide);
                                        }
                                        //    else
                                        //    {
                                        //        return mgChartsCount > 1 ? ItemType.SlideWithMultipleCharts : ItemType.SlideWithChart;
                                        //    }
                                    }
                                })
                                    )();
                                item.ShapesCount = chartsCount;
                                item.Title       = title;
                                item.Description = sbDescr.ToString();
                                item.Keywords    = sbKeyWords.ToString();
//TODO:                                item.ChartType = sbChartType.ToString();
                            }
                            newItems.Add(item);

                            slide = null;
                        }
                        items.AddRange(newItems);

                        Save(newItems, tempIndexFile);

                        indexFileEntry.Delete();
                        zip.CreateEntryFromFile(tempIndexFile, ZIPEntry_IndexFileName);
                    } //using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Update))
                }     //using (FileStream zipFile = new FileStream(indexFilePath, FileMode.Open))

                return(newItems);
            }
            finally
            {
                addin = null;

                slide.ReleaseCOM();
                slide = null;

                pptPresentation = null;

                try
                {
                    if (tempIndexFile != null)
                    {
                        File.Delete(tempIndexFile);
                    }

                    foreach (string path in tempFilesToDelete)
                    {
                        File.Delete(path);
                    }
                }
                catch
                {
                }
            }
        }