コード例 #1
0
        public override void Convert(string inputFilePath, FormatInfo format, string outputFilePath, string password)
        {
            base.Convert(inputFilePath, format, outputFilePath, password);

            MsoAutomationSecurity originalAutomationSecurity = this._application.AutomationSecurity;

            this._application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;

            string tempFilePath = Converter.GetTempFileName(".pptx");

            if (this.Options.UseAddin && Path.GetExtension(inputFilePath) == ".odp")
            {
                // convert odp to pptx
                this.ConvertWithOdfConverter(inputFilePath, tempFilePath);
                inputFilePath = tempFilePath;
            }

            string      sourceFileName = inputFilePath;
            MsoTriState openReadonly   = MsoTriState.msoTrue;
            MsoTriState untitled       = MsoTriState.msoFalse;
            MsoTriState withWindow     = MsoTriState.msoFalse;

            PowerPoint.Presentation presentation = this._application.Presentations.Open(sourceFileName, openReadonly, untitled, withWindow);

            string targetFileName = outputFilePath;

            PowerPoint.PpSaveAsFileType saveFormat = (PowerPoint.PpSaveAsFileType)format.SaveFormat;
            MsoTriState embedTrueTypeFonts         = MsoTriState.msoTriStateMixed;

            string tempFilePath2 = Converter.GetTempFileName(".pptx");

            if (this.Options.UseAddin && format.SaveFormat == (int)PowerPoint.PpSaveAsFileType.ppSaveAsOpenDocumentPresentation)
            {
                // export to odt using addin
                saveFormat = PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation;
                string tempOpenXmlDocument = tempFilePath2;
                presentation.SaveAs(tempOpenXmlDocument, saveFormat, embedTrueTypeFonts);
                presentation.Close();

                this.ConvertWithOdfConverter(tempFilePath2, outputFilePath);
            }
            else
            {
                presentation.SaveAs(targetFileName, saveFormat, embedTrueTypeFonts);
                presentation.Close();
            }

            if (File.Exists(tempFilePath))
            {
                File.Delete(tempFilePath);
            }
            if (File.Exists(tempFilePath2))
            {
                File.Delete(tempFilePath2);
            }
            this._application.AutomationSecurity = originalAutomationSecurity;
        }
コード例 #2
0
        public FileInfo SaveAsHtmlAll(FileInfo htmlFile)
        {
            FileInfo docX = new FileInfo(presentation.FullName);

            htmlFile.Directory.Create();
            if (htmlFile.Exists)
            {
                htmlFile.Delete();
            }
            presentation.SaveAs(htmlFile.FullName, PowerPoint.PpSaveAsFileType.ppSaveAsHTMLDual, Office.MsoTriState.msoFalse);
            presentation.Close();
            presentation = (PowerPoint.Presentation)application.Presentations.Open(docX.FullName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue);
            return(htmlFile);
        }
コード例 #3
0
        /// <summary>
        /// Save a PowerPoint presentation
        /// </summary>
        /// <param name="presentationToSave">Handle to PPT.Presentation object to save</param>
        /// <param name="pathAndFileName">Path (including filename) of where to save the presentation</param>
        /// <param name="fileType">PPT.PpSaveAsFileType object</param>
        /// <param name="embedTrueTypeFonts">Whether to embed TrueType fonts</param>
        public void SavePresentationAs(
            PPT.Presentation presentationToSave,
            string pathAndFileName,
            PPT.PpSaveAsFileType fileType,
            bool embedTrueTypeFonts)
        {
            if (embedTrueTypeFonts)
            {
                presentationToSave.SaveAs(pathAndFileName, fileType, OFFICE.MsoTriState.msoTrue);
                return;
            }

            presentationToSave.SaveAs(pathAndFileName, fileType, OFFICE.MsoTriState.msoFalse);
        }
コード例 #4
0
 public static void SaveFile(PowerPoint.Presentation pre, string fileName = "")
 {
     if (string.IsNullOrEmpty(fileName))
     {
         try
         {
             pre.Save();
         }
         catch (Exception e)
         {
             throw new Exception("Can't save file", e);
         }
     }
     else
     {
         try
         {
             pre.SaveAs(fileName);
         }
         catch (Exception e)
         {
             throw new Exception("Can't save file in " + fileName, e);
         }
     }
 }
コード例 #5
0
        public static void ConvertFromPowerPoint(string sourcePath, string targetPath)
        {
            PowerPoint.Application  application  = new PowerPoint.Application();
            PowerPoint.Presentation presentation = null;
            try
            {
                application  = new PowerPoint.Application();
                presentation = application.Presentations.Open(sourcePath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                presentation.SaveAs(targetPath, PowerPoint.PpSaveAsFileType.ppSaveAsXPS);
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
            }
        }
コード例 #6
0
        public static Microsoft.Office.Interop.PowerPoint.Application ConvertToPPTX(List <string> sourcePpts, string tempDir)
        {
            //Close(powerpointApp);
            Microsoft.Office.Interop.PowerPoint.Application newPowerpointApp = Start();

            string targetPptx = "";

            //List<SlideInfo> slideInfos = new List<SlideInfo>();
            foreach (var sourcePpt in sourcePpts)
            {
                string pptFile = Path.GetFileName(sourcePpt);
                targetPptx = Path.Combine(tempDir, pptFile);

                if (!sourcePpt.Contains(".pptx"))
                {
                    targetPptx += "x";
                }

                if (!File.Exists(targetPptx))
                {
                    //Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(preso, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                    //Microsoft.Office.Interop.PowerPoint.Presentation ppt = newPowerpointApp.Presentations.Open(sourcePpt, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
                    Microsoft.Office.Interop.PowerPoint.Presentation prez = newPowerpointApp.Presentations.Open(sourcePpt, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                    prez.SaveAs(targetPptx, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault);
                    prez.Close();
                }
            }
            Close(newPowerpointApp);
            Microsoft.Office.Interop.PowerPoint.Application returnPowerpointApp = Start();
            // Microsoft.Office.Interop.PowerPoint.Presentation pptx = returnPowerpointApp.Presentations.Open(targetPptx, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
            return(returnPowerpointApp);
        }
コード例 #7
0
        private void button_unlock_Click(object sender, EventArgs e)
        {
            this.savePptNum  = 0;
            this.savepageNum = ppt[0].ActiveWindow.Selection.SlideRange.SlideNumber;

            //save와lock다른경우
            if ((this.savepageNum != this.lockPageNum) || (this.savePptNum != this.lockPptNum))
            {
                MessageBox.Show(lockPageNum + "의 slide를 수정완료먼저해주세요");
            }
            else
            {
                string _Path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                presentation[this.savePptNum].Save();
                PowerPoint.Application  tempPpt          = new PowerPoint.Application();
                PowerPoint.Presentation tempPresentation = tempPpt.Presentations.Add(MsoTriState.msoFalse);
                PowerPoint.Slides       tempSlides       = tempPresentation.Slides;
                tempSlides.InsertFromFile(ButtonPPT[this.savePptNum].Tag.ToString(), 0, this.savepageNum, this.savepageNum);

                saveFileName = _Path + @"\" + "slide.pptx";
                FileInfo fileInfo = new FileInfo(saveFileName);
                if (fileInfo.Exists == true)
                {
                    File.Delete(this.saveFileName);
                }
                tempPresentation.SaveAs(_Path + @"\" + "slide");


                this.askSave = true;
            }
        }
コード例 #8
0
        private void cmdCreateDictionary_Click(object sender, EventArgs e)
        {
            dictionaryName = txtDictionary.Text;

            if (!api.dictionary_exists(dictionaryName))
            {
                if (dictionaryName != "")
                {
                   // PowerPoint.Presentation pres = Globals.ThisAddIn.Application.ActivePresentation;
                    pres = Globals.ThisAddIn.Application.ActivePresentation;
                    string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    location = filePath + "\\Dictionaries\\" + dictionaryName;

                    pres.SaveAs(location, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Microsoft.Office.Core.MsoTriState.msoTrue);
                    pres.Save();

                    api.addDictionary(dictionaryName, location + ".pptx");

                    MessageBox.Show("Dictionary added");
                    pnlAssociations.Enabled = true;
                    pnlDictionary.Enabled = false;

                }
            }
            else
            {
                MessageBox.Show("Already exists");
            }
        }
コード例 #9
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);

            //Get the blank slide layout
            PowerPoint.CustomLayout layout = pres.SlideMaster.
                                             CustomLayouts[7];

            //Add a blank slide
            PowerPoint.Slide sld = pres.Slides.AddSlide(1, layout);

            //Add a text
            PowerPoint.Shape shp = sld.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, 150, 100, 400, 100);

            //Set a text
            PowerPoint.TextRange txtRange = shp.TextFrame.TextRange;
            txtRange.Text      = "Text added dynamically";
            txtRange.Font.Name = "Arial";
            txtRange.Font.Bold = Microsoft.Office.Core.MsoTriState.msoTrue;
            txtRange.Font.Size = 32;

            //Write the output to disk
            pres.SaveAs("outVSTOAddingText.ppt",
                        PowerPoint.PpSaveAsFileType.ppSaveAsPresentation,
                        Microsoft.Office.Core.MsoTriState.msoFalse);
        }
コード例 #10
0
        private void findReplaceText(string strToFind, string strToReplaceWith)
        {
            //Open the presentation
            PowerPoint.Presentation pres = null;
            pres = Globals.ThisAddIn.Application.Presentations.Open("mytextone.ppt",
                                                                    Microsoft.Office.Core.MsoTriState.msoFalse,
                                                                    Microsoft.Office.Core.MsoTriState.msoFalse,
                                                                    Microsoft.Office.Core.MsoTriState.msoFalse);

            //Loop through slides
            foreach (PowerPoint.Slide sld in pres.Slides)
            {
                //Loop through all shapes in slide
                foreach (PowerPoint.Shape shp in sld.Shapes)
                {
                    //Access text in the shape
                    string str = shp.TextFrame.TextRange.Text;
                    //Find text to replace
                    if (str.Contains(strToFind))
                    //Replace exisitng text with the new text
                    {
                        int    idx          = str.IndexOf(strToFind);
                        string strStartText = str.Substring(0, idx);
                        string strEndText   = str.Substring(idx + strToFind.Length, str.Length - 1 - (idx + strToFind.Length - 1));
                        shp.TextFrame.TextRange.Text = strStartText + strToReplaceWith + strEndText;
                    }
                    pres.SaveAs("MyTextOne___.ppt",
                                PowerPoint.PpSaveAsFileType.ppSaveAsPresentation,
                                Microsoft.Office.Core.MsoTriState.msoFalse);
                }
            }
        }
コード例 #11
0
        public void CreatePowerPoint(CreateFileBindingModel createPPBindingModel)
        {
            //Uses CreateFileBindingModel to get specific information from it.

            //Creates a excel application that runs in the background.
            //In the background the application adds the things it needs to be opened after being created.
            PowerPoint.Application  objPowerPoint   = new PowerPoint.Application();
            PowerPoint.Presentation objPresentation = objPowerPoint.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            Microsoft.Office.Interop.PowerPoint.Slides       slides;
            Microsoft.Office.Interop.PowerPoint._Slide       slide;
            Microsoft.Office.Interop.PowerPoint.TextRange    objText;
            Microsoft.Office.Interop.PowerPoint.CustomLayout custLayout =
                objPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
            slides            = objPresentation.Slides;
            slide             = slides.AddSlide(1, custLayout);
            objText           = slide.Shapes[1].TextFrame.TextRange;
            objText.Text      = "Title of page";
            objText.Font.Name = "Arial";
            objText.Font.Size = 32;
            Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2];

            //After the user has given a directory and a name for the file, it is saved there with that name.
            objPresentation.SaveAs(createPPBindingModel.DestPath + @"\" + $"{createPPBindingModel.FileName}", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault,
                                   Microsoft.Office.Core.MsoTriState.msoTrue);

            //This closes the created in the background application and quits it.
            objPresentation.Close();
            objPowerPoint.Quit();
        }
コード例 #12
0
        public override void Convert(string inputFilePath, FormatInfo format, string outputFilePath, string password)
        {
            base.Convert(inputFilePath, format, outputFilePath, password);

            MsoAutomationSecurity originalAutomationSecurity = this._application.AutomationSecurity;

            this._application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;

            string      sourceFileName = inputFilePath;
            MsoTriState openReadonly   = MsoTriState.msoTrue;
            MsoTriState untitled       = MsoTriState.msoFalse;
            MsoTriState withWindow     = MsoTriState.msoFalse;

            PowerPoint.Presentation presentation = this._application.Presentations.Open(sourceFileName, openReadonly, untitled, withWindow);

            string targetFileName = outputFilePath;

            PowerPoint.PpSaveAsFileType saveFormat = (PowerPoint.PpSaveAsFileType)format.SaveFormat;
            MsoTriState embedTrueTypeFonts         = MsoTriState.msoTriStateMixed;

            presentation.SaveAs(targetFileName, saveFormat, embedTrueTypeFonts);

            presentation.Close();

            this._application.AutomationSecurity = originalAutomationSecurity;
        }
コード例 #13
0
        }        //			^As I said ealier I'll stick to the company style guide once I have it.

        //			things got a little out of hand with this project.

        private void Save(object sender, EventArgs e)
        {
            try
            { if (NoPowerPoint())
              {
                  SaveFileDialog sfd = new SaveFileDialog {
                      Filter = powerpointformat
                  };
                  try
                  { if (sfd.ShowDialog() == DialogResult.OK)
                          {
                              filePath = sfd.FileName;
                          }
                          else
                          {
                              return;
                          } } catch (SystemException exc)
                  { MessageBox.Show(save_err_msg + sfd.FileName + ":\n\n" + exc);
                          return; } finally { sfd.Dispose(); }

                  CreateNewPresentation();
              }

              Active_slide.Shapes[1].TextFrame.TextRange.Text = TitleBox.Text;
              Active_slide.Shapes[2].TextFrame.TextRange.Text = BodyTextBox.Text;

              try { presentation.SaveAs(filePath); }
              catch (Exception) {  } } catch (ArgumentException exc)
            { MessageBox.Show(save_err_msg + filePath + ":\n\n" + exc); }
        }
コード例 #14
0
    public async Task <dynamic> GetPowerPoint(dynamic opts)
    {
        string file    = Path.GetFullPath(opts.input as string);
        string pdfFile = Path.GetFullPath(opts.output as string);

        return(await this.scheduler.StartNew(() =>
        {
            Thread.Sleep(100);
            CreatePowerPoint();

            PowerPoint.Presentation presso = this.mspowerpoint.Presentations.Open(file, MsoTriState.msoTrue, WithWindow: MsoTriState.msoFalse);
            Delay(0);
            try
            {
                Delay(1);
                //presso.ExportAsFixedFormat(pdfFile, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint);
                presso.SaveAs(pdfFile, PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
                Delay(2);
            }
            finally
            {
                presso.Close();
                Marshal.ReleaseComObject(presso);
            }

            //closeInternal();
            return pdfFile;
        }));
    }
コード例 #15
0
        ///<summary>
        /// 将PPT文件转换为HTML文件
        ///</summary>
        ///<param name="source_path">PPT文件路径(绝对)</param>
        ///<param name="target_path">生成的Html文件路径(绝对),路径的目录结构必须存在,否则保存失败</param>
        ///<returns>是否执行成功</returns>
        public static bool PowerPointToHtml(string source_path, string target_path)
        {
            PowerPoint.Application ppt = new PowerPoint.Application();
            MsoTriState            m1  = new MsoTriState();
            MsoTriState            m2  = new MsoTriState();
            MsoTriState            m3  = new MsoTriState();

            PowerPoint.Presentation pp = null;
            try
            {
                if (File.Exists(target_path))
                {
                    File.Delete(target_path);
                }
                pp = ppt.Presentations.Open(source_path, m1, m2, m3);
                pp.SaveAs(target_path, PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTriStateMixed);
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                try
                {
                    pp.Close();
                }
                catch { }
                //Thread.Sleep(3000);
            }
        }
コード例 #16
0
        public void PPTSave(string filePath)
        {
            try
            {
                filePath = filePath.Replace('/', '\\');
                if (filePath.Equals(m_PptPresSet.FullName))
                {
                    m_PptPresSet.Save();
                }
                else
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    POWERPOINT.PpSaveAsFileType format = POWERPOINT.PpSaveAsFileType.ppSaveAsDefault;
                    m_PptPresSet.SaveAs(filePath, format, Microsoft.Office.Core.MsoTriState.msoFalse);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #17
0
 public void Save(string presName, string path)
 {
     if (string.IsNullOrEmpty(path))
     {
         pres.SaveAs(presName);
     }
     else
     {
         if (string.IsNullOrEmpty(Path.GetDirectoryName(path)))
         {
             path = application.ActivePresentation.Path + "\\" + path;
         }
         else
         {
             this.path = path;
         }
         pres.SaveAs(path + presName);
     }
 }
コード例 #18
0
        static void Main(string[] args)
        {
            PowerPoint.Application app = new PowerPoint.Application();
            string sourcePptx          = @"c:\test.pptx";
            string targetPpt           = @"c:\test.ppt";
            object missing             = Type.Missing;

            PowerPoint.Presentation pptx = app.Presentations.Open(sourcePptx, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
            pptx.SaveAs(targetPpt, PowerPoint.PpSaveAsFileType.ppSaveAsPowerPoint4);
            app.Quit();
        }
コード例 #19
0
        /// <summary>
        /// 置き換え処理を実施
        /// </summary>
        /// <param name="pptFilePath">テンプレートPPTファイルパス</param>
        /// <param name="pptGenerateFilePath">生成PPT保存ファイルパス</param>
        private void doReplace(string pptFilePath, string pptGenerateFilePath)
        {
            List <string> notes = new List <string>();

            Microsoft.Office.Interop.PowerPoint.Application  app = null;
            Microsoft.Office.Interop.PowerPoint.Presentation ppt = null;

            try
            {
                // PPTのインスタンス作成
                app = new Microsoft.Office.Interop.PowerPoint.Application();

                // PPTファイルオープン
                ppt = app.Presentations.Open(
                    pptFilePath,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoFalse
                    );

                // スライドのインデックスは1から 順にループする
                for (int i = 1; i <= ppt.Slides.Count; i++)
                {
                    //sb.AppendLine(" -------------------- Sheet " + ppt.Slides[i].SlideIndex.ToString());

                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in ppt.Slides[i].Shapes)
                    {
                        getShapeText(shape);
                    }
                }

                //生成PPTファイルの保存を実行
                ppt.SaveAs(pptGenerateFilePath,
                           PpSaveAsFileType.ppSaveAsDefault,
                           Microsoft.Office.Core.MsoTriState.msoFalse);
            }
            finally
            {
                // PPTファイルを閉じる
                if (ppt != null)
                {
                    ppt.Close();
                    ppt = null;
                }

                // PPTインスタンスを閉じる
                if (app != null)
                {
                    app.Quit();
                    app = null;
                }
            }
        }
コード例 #20
0
        private void cmdNewFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (FocusedRow.Data is IGroup group)
            {
                var baseName = "New file";
                var name     = baseName + ".pptx";
                int cnt      = 2;
                while (group.ContainsFile(name)) //TODO: AST: Limit number of iterations
                {
                    name = Path.Combine(baseName + $" ({cnt++})") + ".pptx";
                }
                var fullPath = Path.Combine(group.FullPath, name);


                PPT.Application   app  = null;
                PPT.Presentations pres = null;
                PPT.Presentation  ppt  = null;

                try
                {
                    app  = new PPT.Application();
                    pres = app.Presentations;

                    ppt = pres.Add(MsoTriState.msoFalse);
                    ppt.SaveAs(fullPath);
                }
                finally
                {
                    ppt?.Close();
                    ppt.ReleaseCOM();
                    ppt = null;

                    pres.ReleaseCOM();
                    pres = null;

                    app = null;
                    //TODO: AST: app is not released
                }


                var file = group.AddFile(name);
                var row  = FocusedRow;

                var newRow = dtTree.AddTreeRow(row.ID, 4, Path.GetFileNameWithoutExtension(file.Name), file, false); //TODO: AST: Move it to builder

                var node = uxTree.FindNodeByKeyID(newRow.ID);
                if (node != null)
                {
                    node.Selected = true;
                    uxTree.ShowEditor();
                }
            }
        }
コード例 #21
0
        private static void AutomatePowerPointImpl()
        {
            try
            {
                // Create an instance of Microsoft PowerPoint and make it
                // invisible.

                PowerPoint.Application oPowerPoint = new PowerPoint.Application();


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


                // Create a new Presentation.

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

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

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

                Console.WriteLine("Add some texts");
                oSlide.Shapes[1].TextFrame.TextRange.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) + "\\Sample2.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("Solution2.AutomatePowerPoint throws the error: {0}",
                                  ex.Message);
            }
        }
コード例 #22
0
        private void Save(object sender, EventArgs e)
        {
            try
            { if (NoPowerPoint())
              {
                  SaveFileDialog sfd = new SaveFileDialog {
                      Filter = powerpointformat
                  };
                  try
                  { if (sfd.ShowDialog() == DialogResult.OK)
                                {
                                    file_path = sfd.FileName;
                                }
                                else
                                {
                                    return;
                                } } catch (SystemException exc)
                  { MessageBox.Show(save_err_msg + sfd.FileName + ":\n\n" + exc);
                                return; } finally { sfd.Dispose(); }

                  CreateNewPresentation();
              }
              else
              {
                  foreach (var item in presentation.Slides[1].Shapes)
                  {
                      var shape = (Ppt.Shape)item;
                      if (shape.HasTextFrame != MsoTriState.msoTrue)
                      {
                          continue;
                      }

                      if (shape.Name == box_list[0])
                      {
                          shape.TextFrame.TextRange.Text = TitleBox.Text;
                      }

                      else if (box_list.Contains(shape.Name))
                      {
                          IDataObject clipped = Clipboard.GetDataObject();
                          BodyTextBox.SelectAll();
                          BodyTextBox.Copy();
                          shape.TextFrame.TextRange.Paste();
                          Clipboard.SetDataObject(clipped, true);
                      }
                  }
              }

              presentation.SaveAs(file_path); } catch (ArgumentException exc)
            { MessageBox.Show(save_err_msg + file_path + ":\n\n" + exc); }
        }
コード例 #23
0
        public void SavePowerPoint(string fileName)
        {
            m_pptPres.SaveAs(fileName, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                             Office.MsoTriState.msoTriStateMixed);
            m_pptPres.Close();
            m_pptApplication.Quit();

            // TODO: Need to figure out how to close ppt application programmatically
            Marshal.FinalReleaseComObject(m_pptApplication);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
コード例 #24
0
        protected override System.IO.FileInfo SaveAsHtml(System.IO.DirectoryInfo dir)
        {
            FileInfo docX = new FileInfo(presentation.FullName);

            if (!(docX.Extension.Equals(DocumentDefaultExtension, StringComparison.CurrentCultureIgnoreCase) || docX.Extension.Equals(".pptx", StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new WBAlertException("El documento debe estar en formato Word 2000/XP/2003/2007 con extensión .doc ó .docx");
            }
            if (!dir.Exists)
            {
                dir.Create();
            }
            FileInfo HTMLFile = new FileInfo(dir.FullName + Separator + this.FilePath.Name.Replace(docX.Extension, HtmlExtension));

            if (HTMLFile.Exists)
            {
                HTMLFile.Delete();
            }
            presentation.SaveAs(HTMLFile.FullName, PowerPoint.PpSaveAsFileType.ppSaveAsHTML, Office.MsoTriState.msoFalse);
            presentation.Close();
            presentation = (PowerPoint.Presentation)application.Presentations.Open(docX.FullName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue);
            return(HTMLFile);
        }
コード例 #25
0
        /// <summary>
        /// Saves the document out with the appropriate new filename and format.
        /// Also does any special handling such as accepting/rejecting changes
        /// before saving.
        /// </summary>
        private void SaveDocument()
        {
            m_presentation.SaveAs(m_newFileName, m_newFormatType, MS_FALSE);

            try
            {
                m_presentation.Close();
            }
            catch (Exception e)
            {
                Logger.LogError(m_log, "Failed to close PowerPoint presentation", e);
            }

            m_presentation = null;
        }
コード例 #26
0
        /// <summary>
        /// Converts ppts to PDF documents asynchronously
        /// </summary>
        /// <param name="ppApp">The PowerPoint application</param>
        /// <param name="info">A PptInfo object of the file to be converted to pdf</param>
        /// <param name="newPath">Full path of the converted file</param>
        private Task ppConvertAsync(PP.Application ppApp, PptInfo info, string destDir)
        {
            return(Task.Run(() => {
                // open presentation in PP in the bg
                PP.Presentation pres = ppApp.Presentations.Open(info.Path, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse);

                // build path for converted file
                string newPath = Path.Combine(new[] { destDir, Path.ChangeExtension(Path.GetFileName(info.Path), "pdf") });

                // convert to pdf
                pres.SaveAs(newPath, PP.PpSaveAsFileType.ppSaveAsPDF);
                pres.Close();
                Util.ReleaseComObject(pres);
            }));
        }
コード例 #27
0
ファイル: Solution2.cs プロジェクト: tablesmit/OneCode
        private static void AutomatePowerPointImpl()
        {
            try
            {
                // 创建一个Microsoft PowerPoint实例并使其不可见。

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

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

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

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

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

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

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

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

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

                // 退出PowerPoint应用程序

                Console.WriteLine("退出PowerPoint应用程序");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("解决方案2.AutomatePowerPoint抛出的错误: {0}",
                                  ex.Message);
            }
        }
コード例 #28
0
        public void ConvertToPPTX(string vfileName)
        {
            try
            {
                PowerPoint.Application powerpoint = new PowerPoint.Application();
                // Excel.Workbook wbook = new Excel.Workbook();

                //DirSearch( lstFiles,vPath);
                //foreach (string filetoProcess in lstFiles.Items)
                //{
                // Workbook workbook = new Workbook();
                try
                {
                    //if (!IsProtected(vfileName))
                    //{
                    //powerpoint.Visible = MsoTriState.msoFalse;
                    //powerpoint.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone;
                    PowerPoint.Presentation pptx = powerpoint.Presentations.Open(vfileName, MsoTriState.msoTrue
                                                                                 , MsoTriState.msoTrue, MsoTriState.msoFalse);
                    pptx.SaveAs(vfileName.Substring(0, vfileName.Length - 3) + "pptx"
                                , PowerPoint.PpSaveAsFileType.ppSaveAsDefault);
                    powerpoint.Quit();
                    File.Delete(vfileName);
                    LogManager.GetLogger(typeof(BusinessClass).FullName).Info("Presentation Converted Successfully: " + vfileName);
                    //}
                    //else
                    //{
                    //    LogManager.GetLogger(typeof(BusinessClass).FullName).Info("This ppt file is protected: " + vfileName);


                    //}
                }
                catch (Exception exception)
                {
                    powerpoint.Quit();
                    LogManager.GetLogger(typeof(BusinessClass).FullName).Error("Error while converting the presentation " + vfileName + " Error " + exception.Message);
                }


                //
                //excel.Quit();
            }
            catch (Exception exception)
            {
                LogManager.GetLogger(typeof(BusinessClass).FullName).Error("Error is directory search, Error: " + exception.Message);
            }
        }
コード例 #29
0
        public static string PPTToPPTX(string filepath)
        {
            string   outputfilepath = string.Empty;
            FileInfo fi             = new FileInfo(filepath);

            if (fi.Exists)
            {
                MSPowerPoint.Application app = new MSPowerPoint.Application();
                object missing = Type.Missing;
                MSPowerPoint.Presentation pptx = app.Presentations.Open(fi.FullName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
                outputfilepath = fi.FullName.Replace(fi.Extension, ".pptx");
                pptx.SaveAs(outputfilepath, MSPowerPoint.PpSaveAsFileType.ppSaveAsDefault);
                pptx.Close();
                app.Quit();
            }
            return(outputfilepath);
        }
コード例 #30
0
ファイル: Form1.cs プロジェクト: CastonYoung/SEHAmerica_test
        private void Write(object sender, EventArgs e)
        {
            bool new_presentation = NoPowerPoint();

            try
            { if (new_presentation)
              {
                  if (!CreateNewPresentation())
                  {
                      return;                                                                //If there is no presentation open create one, but return if the user cancels.
                  }
              }
              foreach (var item in presentation.Slides[1].Shapes)
              {
                  var shape = (Ppt.Shape)item;
                  if (shape.HasTextFrame != msoTrue)
                  {
                      continue;
                  }

                  if (shape.Name.Contains("Title"))
                  {
                      shape.TextFrame.TextRange.Text = TitleBox.Text;
                  }

                  else
                  {
                      IDataObject clipped = Clipboard.GetDataObject();
                      BodyTextBox.SelectAll();
                      BodyTextBox.Copy();
                      shape.TextFrame.TextRange.Paste();
                      Clipboard.SetDataObject(clipped, true);
                  }
              }

              if (new_presentation)
              {
                  try { presentation.SaveAs(file_path); }
                  catch (FileNotFoundException)
                  { MessageBox.Show(save_err_msg + file_path + " (invalid name)."); }
              }
              catch (System.Runtime.InteropServices.COMException exc)
              { MessageBox.Show(save_err_msg + file_path + ":\n\n" + exc); } } catch (System.Runtime.InteropServices.COMException exc)
コード例 #31
0
ファイル: PPTDeal.cs プロジェクト: hansanjie/HallControl
        /// <summary>
        /// 切取PPT为图片
        /// </summary>
        private int GetPptPic(string pptPath, string imagePath, int imageWidth, int imageHeight)
        {
            int count = 0;

            try
            {
                POWERPOINT.ApplicationClass ac = new POWERPOINT.ApplicationClass();
                POWERPOINT.Presentation     p  = ac.Presentations.Open(pptPath, MsoTriState.msoCTrue, MsoTriState.msoCTrue, MsoTriState.msoFalse);
                count = p.Slides.Count;;
                DeleteInDir(imagePath);
                p.SaveAs(imagePath, POWERPOINT.PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue);
                RenameImage(imagePath, imageWidth, imageHeight);
                p.Close();
            }
            catch
            {
            }
            return(count);
        }
コード例 #32
0
        /// <summary>
        /// Build presentation from document tree.
        /// </summary>
        /// <param name="filename">Filename of input file (used for output file)</param>
        /// <param name="outputPath">Output directory</param>
        /// <param name="document">Document tree</param>
        /// <param name="slideCount">Number of slides in document tree</param>
        /// <param name="sectionTable">Table of document sections</param>
        /// <param name="frametitleTable">Table of frame titles</param>
        public void Build(string filename, string outputPath, Node document, int slideCount, List<SectionRecord> sectionTable, Dictionary<int, FrametitleRecord> frametitleTable)
        {
            #region Initialize internal variables
            if (outputPath.Length == 0)
            {
                _filename = Path.Combine(Directory.GetCurrentDirectory(), "output", Path.GetFileNameWithoutExtension(filename));

                try
                {
                    // if output directory doesn't exist then create it
                    if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "output")))
                        Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "output"));
                }
                catch (Exception)
                {
                    throw new PowerPointApplicationException("Couldn't create default output directory.");
                }
            }
            else
            {
                _filename = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(filename));

                try
                {
                    // if output directory doesn't exist then create it
                    if (!Directory.Exists(outputPath))
                        Directory.CreateDirectory(outputPath);
                }
                catch (Exception)
                {
                    throw new PowerPointApplicationException("Couldn't create output directory.");
                }
            }

            _document = document;
            _slideCount = slideCount;

            _sectionTable = sectionTable ?? new List<SectionRecord>();
            _frametitleTable = frametitleTable ?? new Dictionary<int, FrametitleRecord>();

            _preambuleSettings = new PreambuleSettings(Path.GetDirectoryName(filename));

            _currentSlide = 0;
            _slideIndex = 0;

            _currentProgress = BasicProgress;

            #endregion // Initialize internal variables

            Node preambule = _document.FindFirstNode("preambule");
            if (preambule == null)
                throw new DocumentBuilderException("Couldn't build document, something went wrong. Please try again.");

            ProcessPreambule(preambule, _document.OptionalParams);

            // create new presentation without window
            _pptPresentation = _pptApplication.Presentations.Add(MsoTriState.msoFalse);

            Node body = _document.FindFirstNode("body");
            if (body == null)
                throw new DocumentBuilderException("Couldn't build document, something went wrong. Please try again.");

            ProcessBody(body);

            try
            {
                _pptPresentation.SaveAs(_filename, Settings.Instance.SaveAs);
            }
            catch (Exception)
            {
                throw new DocumentBuilderException("Couldn't save output file.");
            }
            finally
            {
                // final progress change after saving
                RaiseProgress();
            }

            // print save message
            switch (Settings.Instance.SaveAs)
            {
                case Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault:
                case Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation:
                case Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation:
                    Messenger.Instance.SendMessage(System.IO.Path.GetFileName(filename) + " - Output saved to: \"" + _pptPresentation.FullName + "\"");
                    break;
                case Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF:
                    Messenger.Instance.SendMessage(System.IO.Path.GetFileName(filename) + " - Output saved to: \"" + _filename + ".pdf\"");
                    break;
                default:
                    Messenger.Instance.SendMessage(System.IO.Path.GetFileName(filename) + " - Output saved to output directory.");
                    break;
            }

            try
            {
                _pptPresentation.Close();
                _pptPresentation = null;
            }
            catch { }
        }
コード例 #33
0
        /// <summary>
        /// Handles button for creating dictionaries
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdCreateDictionary_Click(object sender, EventArgs e)
        {
            dictionaryName = txtDictionary.Text;
            //dictionaryName = txtDictionary.Text.ToLower(); ?

            if (!api.dictionary_exists(dictionaryName))
            {
                if (dictionaryName != "")
                {

                    presentation = Globals.ThisAddIn.Application.ActivePresentation;

                    location = filePath + "\\" + dictionaryName;

                    presentation.SaveAs(location, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Microsoft.Office.Core.MsoTriState.msoTrue);
                    presentation.Save();

                    api.addDictionary(dictionaryName, location + ".pptx");

                    MessageBox.Show("Dictionary added. You may now add keywords to the dictionary");

                    pnlAssociations.Enabled = true;
                    pnlDictionary.Enabled = false;

                }
                else
                {
                    MessageBox.Show("Dictionary name cannot be blank - Please enter a dictionary name");
                }
            }
            else
            {
                MessageBox.Show("\""+ dictionaryName + "\"" + " dictionary already exists");
            }
        }