Example #1
0
 public void QuitAndCleanup()
 {
     WorkingPPT?.Close();
     if (Output != null && File.Exists(Output))
     {
         File.Delete(Output);
     }
 }
Example #2
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();
                }
            }
        }
        private void cmbDictionary_SelectedIndexChanged(object sender, EventArgs e)
        {
            dictionaryName = cmbDictionary.SelectedItem.ToString();
            location = api.getDictionary(dictionaryName).Slide_URL;
            presentation = Globals.ThisAddIn.Application.ActivePresentation;
            presentation.Close();
            presentation = Globals.ThisAddIn.Application.Presentations.Open(location);
            presentation = Globals.ThisAddIn.Application.ActivePresentation;

            txtOldName.Text = dictionaryName;
            pnlDictionary.Enabled = false;
            pnlRenameSlide.Enabled = true;
            pnlRenameDictionary.Enabled = true;
        }
Example #4
0
        public void Parse(object src, object dest)
        {
            if (src == null || string.IsNullOrEmpty(src.ToString()))
            {
                throw new ArgumentNullException("源文件不能为空");
            }
            if (dest == null || string.IsNullOrEmpty(dest.ToString()))
            {
                throw new ArgumentNullException("目标路径不能为空");
            }
            try
            {
                presentation = pptApp.Presentations.Open(src.ToString(), Microsoft.Office.Core.MsoTriState.msoTrue
                , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                presentation.ExportAsFixedFormat(dest.ToString(), PpFixedFormatType.ppFixedFormatTypePDF, PpFixedFormatIntent.ppFixedFormatIntentScreen
                    , Microsoft.Office.Core.MsoTriState.msoFalse, PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst, PpPrintOutputType.ppPrintOutputSlides
                    , Microsoft.Office.Core.MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, string.Empty, false
                    , false, false, true, true, missing);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }

                if (pptApp != null)
                {
                    pptApp.Quit();
                    pptApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #5
0
 public static void ConvertPowerPointDocumentToPdf(string srcFile, string dstFile)
 {
     PowerPoint.Application  powerPointApp          = null;
     PowerPoint.Presentation powerPointPresentation = null;
     try
     {
         powerPointApp          = new PowerPoint.Application();
         powerPointPresentation = powerPointApp.Presentations.Open(srcFile,
                                                                   MsoTriState.msoTrue,
                                                                   MsoTriState.msoFalse,
                                                                   MsoTriState.msoFalse);
         powerPointPresentation.ExportAsFixedFormat(dstFile, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
     }
     finally
     {
         powerPointPresentation?.Close();
         powerPointApp?.Quit();
     }
 }
Example #6
0
        /// <summary>
        /// 转换为pdf文件,适合(.ppt、pptx文件类型)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="outputFileName"></param>
        /// <returns></returns>
        private static bool PowerPointExportAsPdf(string fileName, string outputFileName)
        {
            bool isSucceed = false;

            PowerPoint.PpFixedFormatType fileFormat = PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF;

            PowerPoint.Application pptxApp = null;
            if (pptxApp == null)
            {
                pptxApp = new PowerPoint.Application();
            }
            PowerPoint.Presentation presentation = null;

            try
            {
                presentation = pptxApp.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                presentation.ExportAsFixedFormat(outputFileName, fileFormat);
                isSucceed = true;
            }

            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }
                if (pptxApp != null)
                {
                    pptxApp.Quit();
                    pptxApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(isSucceed);
        }
        /// <summary>
        /// Scans pptx file and creates Index
        /// </summary>
        public void CreateIndex()
        {
            items.Clear();

            DeleteIndexFile();
            CreateIndexFile();

            PPT.Application   app          = null;
            PPT.Presentations preentations = null;
            PPT.Presentation  pptx         = null;
            try
            {
                app          = new PPT.Application();
                preentations = app.Presentations;
                pptx         = preentations.Open(LibraryFile.FullPath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
//                PPT.Slides gSlides = pptx.Slides;

                UpdateIndex(pptx, 1);
            }
            catch (Exception ex)
            {
                DeleteIndexFile();
                throw ex;
            }
            finally
            {
                pptx?.Close();
                pptx.ReleaseCOM();
                pptx = null;

                preentations.ReleaseCOM();
                preentations = null;

                app.ReleaseCOM();
                app = null;
            }
        }
Example #8
0
        public static string ReadPPT(string pptFileName)
        {
            string text = string.Empty;

            PowerPoint.ApplicationClass app = null;
            PowerPoint.Presentation     pp  = null;
            object readOnly = true;
            object missing  = System.Reflection.Missing.Value;
            object fileName = pptFileName;

            try
            {
                app = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
                pp  = app.Presentations.Open(fileName.ToString(), Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                foreach (PowerPoint.Slide slide in pp.Slides)
                {
                    foreach (PowerPoint.Shape shape in slide.Shapes)
                    {
                        text += shape.TextFrame.TextRange.Text.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty) + " ";
                    }
                }
            }
            catch
            {
            }
            finally
            {
                pp.Close();
                pp = null;
                app.Quit();
                app = null;
            }

            return(text);
        }
Example #9
0
        protected override FileInfo SaveAs(DirectoryInfo dir, SaveDocument format)
        {
            FileInfo docX     = new FileInfo(presentation.FullName);
            FileInfo HTMLFile = new FileInfo(dir.FullName + Separator + this.FilePath.Name.Replace(docX.Extension, HtmlExtension));

            switch (format)
            {
            case SaveDocument.HtmlIE:
                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);

            case SaveDocument.HtmlAll:
                dir.Create();
                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);

            default:
                throw new NotImplementedException();
            }
        }
Example #10
0
        public void ges_listen()
        {
            while (true)
            {
                if (global.gesture)
                {
                    if (global.gesture_number == 3)
                    {
                        presentation.SlideShowWindow.View.Previous();
                        Thread.Sleep(2000);
                        global.gesture_number = 0;
                    }
                    else if (global.gesture_number == 4)
                    {
                        presentation.SlideShowWindow.View.Next();
                        Thread.Sleep(2000);
                        global.gesture_number = 0;
                    }
                    else if (global.gesture_number == 9)
                    {
                        //if(oSlideShowView != null)
                        {
                            //oSlideShowView.Exit();

                            // this.Dispose();
                        }
                        presentation.Close();
                        //this.Hide();
                        global.gesture_number = 0;
                        Thread.CurrentThread.Suspend();
                        //Thread.Sleep(5000);
                    }
                }
                Thread.Sleep(1000);
            }
        }
Example #11
0
        /// <summary>
        /// 给ppt添加页眉
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool AddPageHeaderFooterForPPT(string filepath)
        {
            try
            {
                //加载PPT文档
                Microsoft.Office.Interop.PowerPoint._Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                app.Visible = MsoTriState.msoTrue;
                Microsoft.Office.Interop.PowerPoint.Presentation ppt = app.Presentations.Open(filepath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue);


                //设置水印文字和字体
                System.Drawing.Font font = new System.Drawing.Font("宋体", 10);
                String watermark         = "内部资料";

                foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in ppt.Slides)
                {
                    //slide.DisplayMasterShapes = MsoTriState.msoCTrue;
                    slide.HeadersFooters.Footer.Visible = MsoTriState.msoCTrue;
                    slide.HeadersFooters.Footer.Text    = watermark;
                }

                //ppt.SaveAs(@"C:\Users\Administrator\Desktop\Test_yemei.pptx",PpSaveAsFileType.ppSaveAsDefault);
                ppt.Save();
                ppt.Close();
                app.Quit();
                app = null;
                GC.Collect();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Example #12
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.ppSaveAsPDF);
     }
     finally
     {
         if (presentation != null)
         {
             presentation.Close();
             presentation = null;
         }
         if (application != null)
         {
             application.Quit();
             application = null;
         }
     }
 }
Example #13
0
        public static void exportImg2(string path)
        {
            Log.Info("PPT.exportImg  path=" + path);
            string name = Path.GetFileName(path);

            string dir = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (name.IndexOf("ppt") < 0 && name.IndexOf("PPT") < 0)
            {
                return;
            }

            string imgpath2 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + 2 + ".jpg";
            string imgpath3 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + 3 + ".jpg";

            if (File.Exists(imgpath2) && File.Exists(imgpath3))
            {
                return;
            }

            POWERPOINT.Application  app = null;
            POWERPOINT.Presentation pre = null;
            try
            {
                app = new POWERPOINT.Application();

                #region check ppt or pptx
                try
                {
                    pre = app.Presentations.Open(path, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse);
                }
                catch (Exception e1)
                {
                    Log.Info("Presentations.Open exception. " + e1 + ", " + path);
                }
                #endregion


                POWERPOINT.Slides slides = pre.Slides;
                int pageTotal            = pre.Slides.Count;

                IEnumerator e = slides.GetEnumerator();
                int         i = 0;

                while (e.MoveNext())
                {
                    i++;
                    PPT.Slide slide   = (PPT.Slide)e.Current;
                    string    imgpath = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + i + ".jpg";
                    slide.Export(imgpath, "jpg", 400, 300);
                }
            }
            catch (Exception e1)
            {
                Log.Info("exportImg1 exception: " + e1.Message);
            }
            finally
            {
                try
                {
                    if (pre != null)
                    {
                        pre.Close();
                        pre = null;
                    }
                }
                catch (Exception e2)
                {
                    Log.Info("exportImg2 exception: " + e2.Message);
                }
                app = null;
            }

            Log.Info("PPT.exportImg over.  name=" + name);
        }
Example #14
0
        public static void exportImg(string path)
        {
            Log.Info("PPT.exportImg  path=" + path);
            string name = Path.GetFileName(path);

            string dir = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (name.IndexOf("ppt") < 0 && name.IndexOf("PPT") < 0)
            {
                return;
            }



            if (g_fileImgStatus.Contains(name))
            {
                g_fileImgStatus.Remove(name);
            }
            g_fileImgStatus.Add(name, 0);//正在导入

            POWERPOINT.Application  app = null;
            POWERPOINT.Presentation pre = null;
            try
            {
                app = new POWERPOINT.Application();

                #region check ppt or pptx
                try{
                    pre = app.Presentations.Open(path, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse);
                }catch (Exception e1) {
                    Log.Info("Presentations.Open exception. " + e1 + "," + path);
                    if (g_fileImgStatus.Contains(name))
                    {
                        g_fileImgStatus.Remove(name);
                        g_fileImgStatus.Add(name, 1);
                    }
                    Form1.DeleteFile(name);
                    MessageBox.Show("打开" + path + "失败,请检查该文件!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    app = null;
                }
                #endregion

                Log.Info("Presentations.Open succeed. " + name);
                POWERPOINT.Slides slides = pre.Slides;
                int pageTotal            = pre.Slides.Count;

                bool bOver = true;
                for (int k = 1; k <= pageTotal; k++)
                {
                    string imgpath1 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + k + ".jpg";
                    if (!File.Exists(imgpath1))
                    {
                        bOver = false;
                    }
                }

                if (bOver)
                {
                    try
                    {
                        if (pre != null)
                        {
                            pre.Close();
                            pre = null;
                        }
                    }
                    catch (Exception e2)
                    {
                        Log.Info("exportImg2 exception: " + e2.Message);
                    }
                    app = null;

                    return;
                }



                IEnumerator e = slides.GetEnumerator();
                int         i = 0;

                while (e.MoveNext())
                {
                    i++;
                    PPT.Slide slide   = (PPT.Slide)e.Current;
                    string    imgpath = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + i + ".jpg";
                    slide.Export(imgpath, "jpg", 400, 300);
                }
            }
            catch (Exception e1)
            {
                Log.Info("exportImg1 exception: " + e1.Message);
            }
            finally
            {
                if (g_fileImgStatus.Contains(name))
                {
                    g_fileImgStatus.Remove(name);
                    g_fileImgStatus.Add(name, 1);
                }

                try
                {
                    if (pre != null)
                    {
                        pre.Close();
                        pre = null;
                    }
                }
                catch (Exception e2)
                {
                    Log.Info("exportImg2 exception: " + e2.Message);
                }
                app = null;
            }

            Log.Info("PPT.exportImg over.  name=" + name);
        }
Example #15
0
        private void InsertItem(IFileItem item)
        {
            if (item == null)
            {
                return;
            }

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

            PPT.Presentation pptx   = pres.Open(item.File.FullPath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
            PPT.Slides       slides = pptx.Slides;
            PPT.Slide        slide  = slides[item.Index];

            if (item.Type == ItemType.Slide)
            {
                slide.Copy();
            }
            else
            {
                PPT.Shapes shapes = slide.Shapes;
                PPT.Shape  shape  = shapes[1];

                shape.Copy();

                shapes.ReleaseCOM();
                shapes = null;
                shape.ReleaseCOM();
                shape = null;
            }

            PPT.Presentation dstpptx = app.ActivePresentation;

            PPT.DocumentWindow wnd  = app.ActiveWindow;
            PPT.View           view = wnd.View;

            //TODO: Check if there is no selection (selection between slides)
            PPT.Slides dstSlides = dstpptx.Slides;
            PPT.Slide  dstSlide  = null;

            dstSlide = view.Slide as PPT.Slide;
            int ix = dstSlide.SlideIndex + 1;

            if (item.Type == ItemType.Slide)
            {
                dstSlide.Copy();

                var r = dstSlides.Paste(); //TODO: dstSlides.Paste(ix) Hangs here
                var s = r[1];

                s.MoveTo(ix);

                s.ReleaseCOM();
                s = null;

                r.ReleaseCOM();
                r = null;
            }
            else
            {
                view.Paste();
            }

            dstSlide.ReleaseCOM();
            dstSlide = null;

            wnd.ReleaseCOM();
            wnd = null;

            view.ReleaseCOM();
            view = null;

            dstpptx.ReleaseCOM();
            dstpptx = null;


            slide.ReleaseCOM();
            slide = null;

            slides.ReleaseCOM();
            slides = null;

            pptx.Close();
            pptx.ReleaseCOM();
            pptx = null;

            pres.ReleaseCOM();
            pres = null;

            app.ReleaseCOM();
            app = null;

            dstSlides.ReleaseCOM();
            dstSlides = null;
        }
Example #16
0
        private int convertPowerp2pdf(List <string> pwr, string dirsal)
        {
            PowerPoint.Application  pptApplication  = null;
            PowerPoint.Presentation pptPresentation = null;

            object unknownType = Type.Missing;

            try
            {
                //Abrir aplicacion de PowerPoint
                pptApplication = new PowerPoint.Application();
            }
            catch (Exception exect) { }
            int code = 0;

            for (int i = 0; i < pwr.Count; i++)
            {
                string entrada = pwr[i];
                consola.escribir("Convirtiendo: " + entrada, true);
                string archSalida = Path.GetFileNameWithoutExtension(pwr[i]) + ".pdf";
                string salida     = Path.Combine(dirsal, archSalida);

                try
                {
                    //abrir el docuemento de PowerPoint
                    pptPresentation = pptApplication.Presentations.Open(entrada,
                                                                        MsoTriState.msoTrue,
                                                                        MsoTriState.msoTrue,
                                                                        MsoTriState.msoFalse);


                    //exportar documento a PDF
                    if (pptPresentation != null)
                    {
                        pptPresentation.ExportAsFixedFormat(salida,
                                                            PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
                                                            PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
                                                            MsoTriState.msoFalse,
                                                            PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                                                            PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
                                                            MsoTriState.msoFalse, null,
                                                            PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty,
                                                            true, true, true, true, false, unknownType);
                        consola.escribir("OK", false);
                        consola.salto();
                        code += 1;
                    }
                    else
                    {
                        consola.escribir(" fallo", false);
                        consola.salto();
                    }
                }
                catch (Exception exPowerPoint2Pdf)
                {
                    consola.escribir(" fallo", false);
                    consola.salto();
                }
                finally
                {
                    // cerrar y liberar documento
                    if (pptPresentation != null)
                    {
                        try
                        {
                            pptPresentation.Close();
                        }
                        catch (Exception dedsa) { }
                        funcionesVarias.liberarObjet(pptPresentation);
                        pptPresentation = null;
                    }
                }
            }
            try
            {
                // cerrar aplicacion y liberar objeto que lo representa
                pptApplication.Quit();
                funcionesVarias.liberarObjet(pptApplication);
                pptApplication = null;
            }
            catch (Exception ex) { }

            return(code);
        }
        public void AddSlides(Item scheduleItem)
        {
            if (!scheduleItem.IsFound || !IsRunning)
            {
                return;
            }

            double progress    = scheduleItem.Ordinal / (double)scheduleItem.Schedule.Items.Count;
            double progressEnd = (scheduleItem.Ordinal + 1) / (double)scheduleItem.Schedule.Items.Count;
            string filename    = Path.GetFullPath(scheduleItem.Filename).ToLower();
            string filetype    = System.IO.Path.GetExtension(filename).TrimStart('.').ToLower();

            if (Config.VideoFormats.Contains(filetype))
            {
                AddSlide(scheduleItem.Name, Labels.SlideShowVideoLabel, null, null, SlideType.Video, filename, progressEnd, scheduleItem, 1);
            }
            else if (Config.AudioFormats.Contains(filetype))
            {
                AddSlide(scheduleItem.Name, Labels.SlideShowAudioLabel, null, null, SlideType.Audio, filename, progressEnd, scheduleItem, 1);
            }
            else if (Config.ImageFormats.Contains(filetype))
            {
                var s = AddSlide(scheduleItem.Name, Labels.SlideShowImageLabel, null, null, SlideType.Image, filename, progressEnd, scheduleItem, 1);
                Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                    s.Image   = SlideShow.RetrieveImage(s.Filename, Config.ProjectorScreen.Bounds.Width, Config.ProjectorScreen.Bounds.Height);
                    s.Preview = SlideShow.RetrieveImage(s.Filename, 333, 250);
                }));
            }
            else if (Config.PowerPointTemplates.Contains(filetype))
            {
                if (template != null)
                {
                    template.Close();
                    template = null;
                }

                if (!scheduleItem.IsTemplateNone)
                {
                    template = OpenPresentation(filename);
                }

                if (SlideAdded != null)
                {
                    SlideAdded(this, new SlideAddedEventArgs(null, progressEnd));
                }
            }
            else if (Config.PowerPointFormats.Contains(filetype))
            {
                var pres = OpenPresentation(filename);

                if (template != null)
                {
                    pres.Slides.Range().Design = template.Designs[1];
                }

                for (int i = 1; i <= pres.Slides.Count; i++)
                {
                    var defaultText = pres.Slides[i].Layout == PP.PpSlideLayout.ppLayoutBlank && pres.Slides[i].Shapes.Count == 0 ? "" : Labels.SlideShowSlideLabel + pres.Slides[i].SlideIndex;
                    var _slide      = AddSlide(GetStringSummary(pres.Slides[i].Shapes).ToNullIfEmpty() ?? defaultText, GetStringSummary(pres.Slides[i].NotesPage.Shapes), pres, null, SlideType.PowerPoint, "", progressEnd, scheduleItem, i);
                    _slide.AnimationCount = pres.Slides[i].TimeLine.MainSequence.Cast <PP.Effect>().Sum(e => e.Timing.TriggerType == PP.MsoAnimTriggerType.msoAnimTriggerOnPageClick ? 1 : 0);
                    _slide.AdvanceOnTime  = pres.Slides[i].SlideShowTransition.AdvanceOnTime;
                }

                pres.SlideShowSettings.AdvanceMode = PP.PpSlideShowAdvanceMode.ppSlideShowUseSlideTimings;
                if (!Config.UseSlideTimings)
                {
                    pres.Slides.Range().SlideShowTransition.AdvanceOnTime = Core.MsoTriState.msoFalse;
                }

                if (!IsRunning)
                {
                    pres.Close();
                    return;
                }

                app.SlideShowNextSlide -= new PP.EApplication_SlideShowNextSlideEventHandler(app_SlideShowNextSlide);

                var slide = pres.Slides.Add(1, PP.PpSlideLayout.ppLayoutBlank);
                slide.FollowMasterBackground        = Core.MsoTriState.msoFalse;
                slide.Background.Fill.ForeColor.RGB = Util.ToOle(Config.ScreenBlankColour);
                slide.Background.Fill.Solid();
                slide.SlideShowTransition.EntryEffect = PP.PpEntryEffect.ppEffectNone;

                //todo PPT 2010 shows presenter view, 2007 doesn't throws error if the is called though
                //pres.SlideShowSettings.ShowPresenterView = Core.MsoTriState.msoFalse;
                pres.SlideShowSettings.Run();
                Util.SlideShowWindows[pres] = pres.SlideShowWindow;

                //ensure presenter has focus otherwise if ppt has focus and user moves scrollwheel over presenter expecting the listview to scroll it will actually change slides instead and can end slideshow unexpectedly
                System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { System.Windows.Application.Current.MainWindow.Activate(); }));

                var taskbarList = (ITaskbarList) new CTaskbarList();
                taskbarList.HrInit();
                taskbarList.DeleteTab(new IntPtr(pres.SlideShowWindow().HWND));

                app.SlideShowNextSlide += new PP.EApplication_SlideShowNextSlideEventHandler(app_SlideShowNextSlide);
            }

            if (Config.InsertBlankAfterPres && Config.PowerPointFormats.Contains(filetype) || Config.InsertBlankAfterVideo && Config.VideoFormats.Concat(Config.AudioFormats).Contains(filetype))
            {
                AddSlide("", "Blank", null, null, SlideType.Blank, "", progressEnd, new Item(), 1);
            }
        }
Example #18
0
        static int Main(string[] args)
        {
            try
            {
                string path = Directory.GetCurrentDirectory();
                Console.WriteLine(path);
                path = path.Replace("\\ConvertToPDF\\bin\\Debug", "");
                path = path + "\\";

                word.Application app = new word.Application();
                Document         doc = app.Documents.Open(path + "..\\ProfilesRNS_ReadMeFirst.docx");
                if (doc != null)

                {
                    doc.SaveAs2(path + "ProfilesRNS\\ProfilesRNS_ReadMeFirst.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ProfilesRNS_ArchitectureGuide.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ProfilesRNS_ArchitectureGuide.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ProfilesRNS_InstallGuide.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ProfilesRNS_InstallGuide.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ProfilesRNS_APIGuide.doc");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ProfilesRNS_APIGuide.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ProfilesRNS_ReleaseNotes.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ProfilesRNS_ReleaseNotes.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ORNG\\ORNG_GadgetDevelopment.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ORNG\\ORNG_GadgetDevelopment.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ORNG\\ORNG_InstallationGuide.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ORNG\\ORNG_InstallationGuide.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    doc = app.Documents.Open(path + "..\\Documentation\\ORNG\\ORNG_TroubleShootingGuide.docx");
                    doc.SaveAs2(path + "ProfilesRNS\\Documentation\\ORNG\\ORNG_TroubleShootingGuide.pdf", word.WdSaveFormat.wdFormatPDF);
                    doc.Close();

                    app.Quit();


                    Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();

                    Microsoft.Office.Interop.PowerPoint.Presentation presentation = pptApp.Presentations.Open(path + "..\\Documentation\\ProfilesRNS_DataFlowDiagram.pptx");
                    presentation.SaveAs(path + "ProfilesRNS\\Documentation\\ProfilesRNS_DataFlowDiagram.pdf", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
                    presentation.Close();


                    presentation = pptApp.Presentations.Open(path + "..\\Documentation\\ProfilesRNS_OntologyDiagram.pptx");
                    presentation.SaveAs(path + "ProfilesRNS\\Documentation\\ProfilesRNS_OntologyDiagram.pdf", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
                    presentation.Close();

                    presentation = pptApp.Presentations.Open(path + "..\\Documentation\\ORNG\\ORNGArchitecturalDiagram.pptx");
                    presentation.SaveAs(path + "ProfilesRNS\\Documentation\\ORNG\\ORNGArchitecturalDiagram.pdf", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
                    presentation.Close();

                    pptApp.Quit();
                }
                else
                {
                    app.Quit();
                    return(2);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(1);
            }
            return(0);
        }
Example #19
0
        private void  除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (fName != "")
            {
                List <int> del = new List <int>();
                int        n   = listView1.SelectedItems.Count;
                for (int i = n - 1; i >= 0; i--)
                {
                    ListViewItem item = listView1.SelectedItems[i];
                    item.Remove();
                    del.Add(item.ImageIndex);
                }

                listView1.Clear();
                this.listView1.Refresh();
                imageList1.Images.Clear();

                if (!Directory.Exists(Location + @"temp_gallery2\"))
                {
                    Directory.CreateDirectory(Location + @"temp_gallery2\");
                }

                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location + @"temp_gallery2\");

                PowerPoint.Application  pptapp = new PowerPoint.Application();
                PowerPoint.Presentation pptpr  = pptapp.Presentations.Open(fName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse);
                for (int k = del.Count() - 1; k >= 0; k--)
                {
                    int cn = del[k];
                    if (k != del.Count() - 1)
                    {
                        cn = cn - 1;
                    }
                    int sn = 0;
                    if (pptpr.Slides.Count > 1)
                    {
                        for (int i = 1; i <= pptpr.Slides.Count; i++)
                        {
                            PowerPoint.Slide oslide = pptpr.Slides[i];
                            if (oslide.Shapes.Count != 0)
                            {
                                sn += oslide.Shapes.Count;
                                if (cn + 1 <= sn)
                                {
                                    oslide.Shapes[oslide.Shapes.Count - (sn - cn - 1)].Delete();
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        pptpr.Slides[1].Shapes[cn + 1].Delete();
                    }
                }
                pptpr.Save();
                if (pptpr.Slides.Count != 0)
                {
                    for (int i = 1; i <= pptpr.Slides.Count; i++)
                    {
                        PowerPoint.Slide oslide = pptpr.Slides[i];
                        if (oslide.Shapes.Count != 0)
                        {
                            for (int j = 1; j <= oslide.Shapes.Count; j++)
                            {
                                PowerPoint.Shape oshape = oslide.Shapes[j];
                                int k = dir.GetFiles().Length + 1;
                                oshape.Export(Location + @"temp_gallery2\gshape_" + k + ".png", PowerPoint.PpShapeFormat.ppShapeFormatPNG);
                                Image  img = Image.FromFile(Location + @"temp_gallery2\gshape_" + k + ".png");
                                Bitmap bmp = new Bitmap(img);
                                img.Dispose();
                                imageList1.Images.Add(bmp);
                            }
                        }
                    }
                }

                Properties.Settings.Default.GalleryRefresh = 1;
                Directory.Delete(Location + @"temp_gallery2\", true);

                pptpr.Close();
                listView1.LargeImageList = imageList1;
                listView1.BeginUpdate();
                for (int i = 0; i < imageList1.Images.Count; i++)
                {
                    ListViewItem item = new ListViewItem();
                    item.ImageIndex = i;
                    listView1.Items.Add(item);
                }
                this.listView1.EndUpdate();
            }
            else
            {
                MessageBox.Show("请先加载库");
            }
        }
        public static new int Convert(String inputFile, String outputFile, Hashtable options, ref List <PDFBookmark> bookmarks)
        {
            // Check for password protection
            if (Converter.IsPasswordProtected(inputFile))
            {
                Console.WriteLine("Unable to open password protected file");
                return((int)ExitCode.PasswordFailure);
            }

            Boolean running = (Boolean)options["noquit"];

            try
            {
                Microsoft.Office.Interop.PowerPoint.Application   app = null;
                Microsoft.Office.Interop.PowerPoint.Presentation  activePresentation = null;
                Microsoft.Office.Interop.PowerPoint.Presentations presentations      = null;
                try
                {
                    try
                    {
                        app = (Microsoft.Office.Interop.PowerPoint.Application)Marshal.GetActiveObject("PowerPoint.Application");
                    }
                    catch (System.Exception)
                    {
                        int tries = 10;
                        app     = new Microsoft.Office.Interop.PowerPoint.Application();
                        running = false;
                        while (tries > 0)
                        {
                            try
                            {
                                // Try to set a property on the object
                                app.DisplayAlerts = PpAlertLevel.ppAlertsNone;
                            }
                            catch (COMException)
                            {
                                // Decrement the number of tries and have a bit of a snooze
                                tries--;
                                Thread.Sleep(500);
                                continue;
                            }
                            // Looks ok, so bail out of the loop
                            break;
                        }
                        if (tries == 0)
                        {
                            Converter.releaseCOMObject(app);
                            return((int)ExitCode.ApplicationError);
                        }
                    }
                    MSCore.MsoTriState nowrite = (Boolean)options["readonly"] ? MSCore.MsoTriState.msoTrue : MSCore.MsoTriState.msoFalse;
                    bool pdfa = (Boolean)options["pdfa"] ? true : false;
                    if ((Boolean)options["hidden"])
                    {
                        // Can't really hide the window, so at least minimise it
                        app.WindowState = PpWindowState.ppWindowMinimized;
                    }
                    PpFixedFormatIntent quality = PpFixedFormatIntent.ppFixedFormatIntentScreen;
                    if ((Boolean)options["print"])
                    {
                        quality = PpFixedFormatIntent.ppFixedFormatIntentPrint;
                    }
                    if ((Boolean)options["screen"])
                    {
                        quality = PpFixedFormatIntent.ppFixedFormatIntentScreen;
                    }
                    Boolean includeProps = !(Boolean)options["excludeprops"];
                    Boolean includeTags  = !(Boolean)options["excludetags"];
                    app.FeatureInstall = MSCore.MsoFeatureInstall.msoFeatureInstallNone;
                    app.DisplayDocumentInformationPanel = false;
                    app.DisplayAlerts        = PpAlertLevel.ppAlertsNone;
                    app.Visible              = MSCore.MsoTriState.msoTrue;
                    app.AutomationSecurity   = MSCore.MsoAutomationSecurity.msoAutomationSecurityLow;
                    presentations            = app.Presentations;
                    activePresentation       = presentations.Open2007(inputFile, nowrite, MSCore.MsoTriState.msoTrue, MSCore.MsoTriState.msoTrue, MSCore.MsoTriState.msoTrue);
                    activePresentation.Final = false;

                    // Sometimes, presentations can have restrictions on them that block
                    // access to the object model (e.g. fonts containing restrictions).
                    // If we attempt to access the object model and fail, then try a more
                    // sneaky method of getting the presentation - create an empty presentation
                    // and insert the slides from the original file.
                    var fonts = activePresentation.Fonts;
                    try
                    {
                        var fontCount = fonts.Count;
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        Converter.releaseCOMObject(fonts);
                        // This presentation looked read-only
                        activePresentation.Close();
                        Converter.releaseCOMObject(activePresentation);
                        // Create a new blank presentation and insert slides from the original
                        activePresentation = presentations.Add(MSCore.MsoTriState.msoFalse);
                        // This is only a band-aid - backgrounds won't come through
                        activePresentation.Slides.InsertFromFile(inputFile, 0);
                    }
                    Converter.releaseCOMObject(fonts);
                    activePresentation.ExportAsFixedFormat(outputFile, PpFixedFormatType.ppFixedFormatTypePDF, quality, MSCore.MsoTriState.msoFalse, PpPrintHandoutOrder.ppPrintHandoutVerticalFirst, PpPrintOutputType.ppPrintOutputSlides, MSCore.MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, "", includeProps, true, includeTags, true, pdfa, Type.Missing);

                    // Determine if we need to make bookmarks
                    if ((bool)options["bookmarks"])
                    {
                        loadBookmarks(activePresentation, ref bookmarks);
                    }
                    activePresentation.Saved = MSCore.MsoTriState.msoTrue;
                    activePresentation.Close();

                    return((int)ExitCode.Success);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return((int)ExitCode.UnknownError);
                }
                finally
                {
                    Converter.releaseCOMObject(activePresentation);
                    Converter.releaseCOMObject(presentations);

                    if (app != null && !running)
                    {
                        app.Quit();
                    }
                    Converter.releaseCOMObject(app);
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
        }
Example #21
0
 public void Close()
 {
     //_presentation?.SlideShowWindow?.View?.Exit();
     _presentation?.Close();
     _presentation = null;
 }
 private void closeDictionary(string dictionary, string location)
 {
     presentation = Globals.ThisAddIn.Application.ActivePresentation;
        presentation.Close();
 }
Example #23
0
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string      Location = "";
            RegistryKey path     = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Slibe\OneKeyTools", false);

            if (Properties.Settings.Default.Galleryfolder == "")
            {
                Location = path.GetValue("Path", "").ToString();
            }
            else
            {
                Location = Properties.Settings.Default.Galleryfolder;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = Location;
            openFileDialog.Filter           = "PowerPoint演示文稿|*.pptx";
            openFileDialog.FilterIndex      = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                fName = openFileDialog.FileName;
                if (fName.Contains("pptx"))
                {
                    PowerPoint.Application  pptapp = new PowerPoint.Application();
                    PowerPoint.Presentation pptpr  = pptapp.Presentations.Open(fName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse, Office.MsoTriState.msoFalse);

                    listView1.Clear();
                    this.listView1.Refresh();
                    imageList1.Images.Clear();

                    if (!Directory.Exists(Location + @"temp_gallery2\"))
                    {
                        Directory.CreateDirectory(Location + @"temp_gallery2\");
                    }
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location + @"temp_gallery2\");

                    int n = 0;
                    foreach (PowerPoint.Slide oslide in pptpr.Slides)
                    {
                        if (oslide.Shapes.Count != 0)
                        {
                            for (int i = 1; i <= oslide.Shapes.Count; i++)
                            {
                                PowerPoint.Shape oshape = oslide.Shapes[i];
                                int    k     = dir.GetFiles().Length + 1;
                                string npath = Location + @"temp_gallery2\gshape_" + k + ".png";
                                oshape.Export(npath, PowerPoint.PpShapeFormat.ppShapeFormatPNG, 300, 300);
                                Image  img = Image.FromFile(npath);
                                Bitmap bmp = new Bitmap(img);
                                img.Dispose();
                                imageList1.Images.Add(bmp);
                            }
                            n += 1;
                        }
                    }
                    Directory.Delete(Location + @"temp_gallery2\", true);
                    pptpr.Close();

                    if (n == 0)
                    {
                        MessageBox.Show("所选文稿中没有图形,请重新加载");
                    }
                    else
                    {
                        listView1.View           = View.LargeIcon;
                        listView1.LargeImageList = imageList1;
                        listView1.BeginUpdate();
                        for (int i = 0; i < imageList1.Images.Count; i++)
                        {
                            ListViewItem item = new ListViewItem();
                            item.ImageIndex = i;
                            listView1.Items.Add(item);
                        }
                        this.listView1.EndUpdate();
                    }
                }
            }
        }
Example #24
0
        public ActionResult UploadPowerPoint(string cod_unidad_negocio)
        {
            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var fileContent = Request.Files[i];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        string fileCliente   = Path.GetFileName(fileContent.FileName);
                        string fileExtension = Path.GetExtension(fileContent.FileName).ToLower();
                        string filePpt       = string.Empty;
                        string filePptDBS    = string.Empty;
                        string fileVideo     = string.Empty;
                        string fileVideoDBS  = string.Empty;

                        if (fileExtension != ".ppt" && fileExtension != ".pptx")
                        {
                            return(Json(
                                       new Response
                            {
                                Status = HttpStatusCode.BadRequest,
                                Message = "El archivo debe ser tipo Excel (.xlsx,.xls)",
                            },
                                       JsonRequestBehavior.AllowGet));
                        }

                        // get a stream
                        var stream            = fileContent.InputStream;
                        var nomenclaturaPPT   = cod_unidad_negocio + "_Presentacion.pptx";
                        var nomenclaturaVideo = cod_unidad_negocio + "_Presentacion.mp4";

                        if (HttpContext.IsDebuggingEnabled)
                        {
                            filePpt = Path.Combine(@"M:\MVC\com\ppt", nomenclaturaPPT);
                            //filePptDBS = filePpt.Replace(@"M:\MVC\com\ppt", pptPathDES);
                            fileVideo = Path.Combine(@"M:\TV\com\pages\" + cod_unidad_negocio + @"\ppt", nomenclaturaVideo);
                            //fileVideoDBS = filePpt.Replace(@"M:\TV\com\pages\" + cod_unidad_negocio + @"\ppt", videoPathDES + cod_unidad_negocio + @"\ppt");
                        }
                        else
                        {
                            filePpt = Path.Combine(Server.MapPath("~/ppt"), nomenclaturaPPT);
                            //filePptDBS = filePpt.Replace(Server.MapPath("~/ppt"), pptPathPRO);
                            fileVideo = Path.Combine(videoPathPRO + cod_unidad_negocio + @"\ppt", nomenclaturaVideo);
                            //fileVideoDBS = filePpt.Replace(videoPathPRO + cod_unidad_negocio + @"\ppt", videoPathPRO + cod_unidad_negocio + @"\ppt");
                        }

                        fileContent.SaveAs(filePpt);
                        Microsoft.Office.Interop.PowerPoint.Application  appPpt = new Microsoft.Office.Interop.PowerPoint.Application();
                        Microsoft.Office.Interop.PowerPoint.Presentation objTempPresentation = appPpt.Presentations.Open(FileName: filePpt, ReadOnly: Microsoft.Office.Core.MsoTriState.msoFalse, Untitled: Microsoft.Office.Core.MsoTriState.msoFalse, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse);
                        objTempPresentation.CreateVideo(FileName: fileVideo, UseTimingsAndNarrations: false, DefaultSlideDuration: 2, VertResolution: 1080, FramesPerSecond: 60, Quality: 90);
                        while (objTempPresentation.CreateVideoStatus == PpMediaTaskStatus.ppMediaTaskStatusInProgress)
                        {
                            Thread.Sleep(100);
                        }

                        //Close PowerPoint
                        objTempPresentation.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(objTempPresentation);
                        objTempPresentation = null;
                        appPpt.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(appPpt);
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appPpt);
                        appPpt = null;

                        //force a garbage collection
                        GC.Collect();
                        GC.WaitForPendingFinalizers();

                        GC.Collect();
                        GC.WaitForPendingFinalizers();

                        foreach (var item in System.Diagnostics.Process.GetProcessesByName("powerpnt"))
                        {
                            item.Kill();
                        }

                        return(Json(
                                   new Response
                        {
                            Status = HttpStatusCode.OK,
                            Message = "SUCCESS: Carga exitosa."
                        },
                                   JsonRequestBehavior.AllowGet));
                    }
                }
            }
            catch (Exception e)
            {
                return(Json(
                           new Response
                {
                    Status = HttpStatusCode.BadRequest,
                    Message = "El archivo no se cargó. " + e.Message,
                },
                           JsonRequestBehavior.AllowGet));
            }

            return(Json(
                       new Response
            {
                Status = HttpStatusCode.BadRequest,
                Message = "No se puede continuar por errores en el modelo",
                Errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage)
            },
                       JsonRequestBehavior.AllowGet));
        }
Example #25
0
        //private static OfficeToXpsConversionResult ConvertFromWord(string sourceFilePath, ref string resultFilePath)
        //{
        //    object pSourceDocPath = sourceFilePath;

        //    string pExportFilePath = string.IsNullOrEmpty(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

        //    try
        //    {
        //        var pExportFormat = Word.WdExportFormat.wdExportFormatXPS;
        //        bool pOpenAfterExport = false;
        //        var pExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen;
        //        var pExportRange = Word.WdExportRange.wdExportAllDocument;
        //        int pStartPage = 0;
        //        int pEndPage = 0;
        //        var pExportItem = Word.WdExportItem.wdExportDocumentContent;
        //        var pIncludeDocProps = true;
        //        var pKeepIRM = true;
        //        var pCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
        //        var pDocStructureTags = true;
        //        var pBitmapMissingFonts = true;
        //        var pUseISO19005_1 = false;


        //        Word.Application wordApplication = null;
        //        Word.Document wordDocument = null;

        //        try
        //        {
        //            wordApplication = new Word.Application();
        //        }
        //        catch (Exception exc)
        //        {
        //            return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Word", exc);
        //        }

        //        try
        //        {
        //            try
        //            {
        //                wordDocument = wordApplication.Documents.Open(ref pSourceDocPath);
        //            }
        //            catch (Exception exc)
        //            {
        //                return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
        //            }

        //            if (wordDocument != null)
        //            {
        //                try
        //                {
        //                    wordDocument.ExportAsFixedFormat(
        //                                        pExportFilePath,
        //                                        pExportFormat,
        //                                        pOpenAfterExport,
        //                                        pExportOptimizeFor,
        //                                        pExportRange,
        //                                        pStartPage,
        //                                        pEndPage,
        //                                        pExportItem,
        //                                        pIncludeDocProps,
        //                                        pKeepIRM,
        //                                        pCreateBookmarks,
        //                                        pDocStructureTags,
        //                                        pBitmapMissingFonts,
        //                                        pUseISO19005_1
        //                                    );
        //                }
        //                catch (Exception exc)
        //                {
        //                    return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Word", exc);
        //                }
        //            }
        //            else
        //            {
        //                return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
        //            }
        //        }
        //        finally
        //        {
        //            // Close and release the Document object.
        //            if (wordDocument != null)
        //            {
        //                wordDocument.Close();
        //                wordDocument = null;
        //            }

        //            // Quit Word and release the ApplicationClass object.
        //            if (wordApplication != null)
        //            {
        //                wordApplication.Quit();
        //                wordApplication = null;
        //            }

        //            GC.Collect();
        //            GC.WaitForPendingFinalizers();
        //            GC.Collect();
        //            GC.WaitForPendingFinalizers();
        //        }
        //    }
        //    catch (Exception exc)
        //    {
        //        return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Word", exc);
        //    }

        //    resultFilePath = pExportFilePath;

        //    return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
        //}

        //    private static OfficeToXpsConversionResult ConvertFromExcel(string sourceFilePath, ref string resultFilePath)
        //    {
        //        string pSourceDocPath = sourceFilePath;

        //        string pExportFilePath = string.IsNullOrEmpty(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

        //        try
        //        {
        //            var pExportFormat = Excel.XlFixedFormatType.xlTypeXPS;
        //            var pExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
        //            var pOpenAfterPublish = false;
        //            var pIncludeDocProps = true;
        //            var pIgnorePrintAreas = true;


        //            Excel.Application excelApplication = null;
        //            Excel.Workbook excelWorkbook = null;

        //            try
        //            {
        //                excelApplication = new Excel.Application();
        //            }
        //            catch (Exception exc)
        //            {
        //                return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Excel", exc);
        //            }

        //            try
        //            {
        //                try
        //                {
        //                    excelWorkbook = excelApplication.Workbooks.Open(pSourceDocPath);
        //                }
        //                catch (Exception exc)
        //                {
        //                    return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
        //                }

        //                if (excelWorkbook != null)
        //                {
        //                    try
        //                    {
        //                        excelWorkbook.ExportAsFixedFormat(
        //                                            pExportFormat,
        //                                            pExportFilePath,
        //                                            pExportQuality,
        //                                            pIncludeDocProps,
        //                                            pIgnorePrintAreas,

        //                                            OpenAfterPublish : pOpenAfterPublish
        //                                        );
        //                    }
        //                    catch (Exception exc)
        //                    {
        //                        return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "Excel", exc);
        //                    }
        //                }
        //                else
        //                {
        //                    return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
        //                }
        //            }
        //            finally
        //            {
        //                // Close and release the Document object.
        //                if (excelWorkbook != null)
        //                {
        //                    excelWorkbook.Close();
        //                    excelWorkbook = null;
        //                }

        //                // Quit Word and release the ApplicationClass object.
        //                if (excelApplication != null)
        //                {
        //                    excelApplication.Quit();
        //                    excelApplication = null;
        //                }

        //                GC.Collect();
        //                GC.WaitForPendingFinalizers();
        //                GC.Collect();
        //                GC.WaitForPendingFinalizers();
        //            }
        //        }
        //        catch (Exception exc)
        //        {
        //            return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Excel", exc);
        //        }

        //        resultFilePath = pExportFilePath;

        //        return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
        //    }

        private static OfficeToXpsConversionResult ConvertFromPowerPoint(string sourceFilePath, ref string resultFilePath, ref int resultCount)
        {
            resultCount = 0;

            string pSourceDocPath = sourceFilePath;

            string pExportFilePath = string.IsNullOrEmpty(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

            try
            {
                PowerPoint.Application  pptApplication  = null;
                PowerPoint.Presentation pptPresentation = null;
                try
                {
                    pptApplication = new PowerPoint.Application();
                }
                catch (Exception exc)
                {
                    return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "PowerPoint", exc));
                }

                try
                {
                    try
                    {
                        pptPresentation = pptApplication.Presentations.Open(pSourceDocPath,
                                                                            Microsoft.Office.Core.MsoTriState.msoFalse,
                                                                            Microsoft.Office.Core.MsoTriState.msoTrue,
                                                                            Microsoft.Office.Core.MsoTriState.msoFalse);
                    }
                    catch (Exception exc)
                    {
                        return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc));
                    }

                    if (pptPresentation != null)
                    {
                        try
                        {
                            pptPresentation.Export(
                                pExportFilePath,
                                "JPG",
                                (int)System.Windows.SystemParameters.PrimaryScreenWidth,
                                (int)System.Windows.SystemParameters.PrimaryScreenHeight
                                );

                            resultCount = pptPresentation.Slides.Count;
                        }
                        catch (Exception exc)
                        {
                            System.Windows.MessageBox.Show(exc.ToString());

                            return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, "PowerPoint", exc));
                        }
                    }
                    else
                    {
                        return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile));
                    }
                }
                finally
                {
                    // Close and release the Document object.
                    if (pptPresentation != null)
                    {
                        pptPresentation.Close();
                        pptPresentation = null;
                    }

                    // Quit Word and release the ApplicationClass object.
                    if (pptApplication != null)
                    {
                        pptApplication.Quit();
                        pptApplication = null;
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (Exception exc)
            {
                return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "PowerPoint", exc));
            }

            resultFilePath = pExportFilePath;

            return(new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath));
        }
Example #26
0
        private static OfficeToXpsConversionResult ConvertFromPowerPoint(string sourceFilePath, ref string resultFilePath)
        {
            string pSourceDocPath = sourceFilePath;

            string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

            try
            {
                PowerPoint.Application  pptApplication  = null;
                PowerPoint.Presentation pptPresentation = null;

                try
                {
                    pptApplication = new PowerPoint.Application();
                }
                catch (Exception exc)
                {
                    return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, exc.Message, exc));
                }

                try
                {
                    try
                    {
                        pptPresentation = pptApplication.Presentations.Open(pSourceDocPath,
                                                                            Microsoft.Office.Core.MsoTriState.msoTrue,
                                                                            Microsoft.Office.Core.MsoTriState.msoTrue,
                                                                            Microsoft.Office.Core.MsoTriState.msoFalse);
                    }
                    catch (Exception exc)
                    {
                        return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc));
                    }

                    if (pptPresentation != null)
                    {
                        try
                        {
                            pptPresentation.ExportAsFixedFormat(
                                pExportFilePath,
                                PowerPoint.PpFixedFormatType.ppFixedFormatTypeXPS,
                                PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen,
                                Microsoft.Office.Core.MsoTriState.msoFalse,
                                PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                                PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
                                Microsoft.Office.Core.MsoTriState.msoFalse,
                                null,
                                PowerPoint.PpPrintRangeType.ppPrintAll,
                                string.Empty,
                                true,
                                true,
                                true,
                                true,
                                false
                                );
                        }
                        catch (Exception exc)
                        {
                            return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToExportToXps, exc.Message, exc));
                        }
                    }
                    else
                    {
                        return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile));
                    }
                }
                finally
                {
                    // Close and release the Document object.
                    if (pptPresentation != null)
                    {
                        pptPresentation.Close();
                        pptPresentation = null;
                    }

                    // Quit Word and release the ApplicationClass object.
                    if (pptApplication != null)
                    {
                        pptApplication.Quit();
                        pptApplication = null;
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (Exception exc)
            {
                return(new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, exc.Message, exc));
            }

            resultFilePath = pExportFilePath;

            return(new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath));
        }
        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;
                }
            }
        }
Example #28
0
        private void CreateSlide(object sender, EventArgs e)
        {
            //initialize PowerPoint
            PPT.Application  pptApplication  = new PPT.Application();
            PPT.Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
            try
            {
                // My version of PowerPoint doesn't seem to match up with the version expected here so I hardcoded the number that matches my content with caption layout
                // I think The commented out line of code below works in Office 365
                //var customLayout = pptPresentation.SlideMaster.CustomLayouts[PPT.PpSlideLayout.ppLayoutContentWithCaption];
                var customLayout = pptPresentation.SlideMaster.CustomLayouts[8];
                var slide        = pptPresentation.Slides.AddSlide(1, customLayout);

                // Add Title text
                var title = slide.Shapes[1].TextFrame.TextRange;
                title.Text      = this.textBox1.Text;
                title.Font.Name = "Arial";
                title.Font.Size = 46;

                // Add Content text
                var content = slide.Shapes[3].TextFrame.TextRange;
                content.Text = this.richTextBox1.Text;

                //Get parameters of where images should be placed based on third box then remove that box
                PPT.Shape imageBox = slide.Shapes[2];
                float     left     = imageBox.Left;
                float     top      = imageBox.Top;
                float     width    = imageBox.Width / 2;
                float     height   = imageBox.Height / 2;
                int       bit      = 0;
                slide.Shapes[2].Delete();

                string fullPath = Directory.GetCurrentDirectory();

                foreach (int i in selected)
                {
                    // Only allow 4 pictures to be added since there isn't really space for more
                    if (bit == 4)
                    {
                        break;
                    }
                    string fileName = string.Format(@"{0}\\full{1}.jpg", fullPath, i);

                    // download the image and load it into the presentation. If the image can't be downloaded from the site skip it gracefully
                    try { downloader.DownloadFile(images.items[i].link, fileName); }
                    catch { continue; }
                    slide.Shapes.AddPicture(
                        fileName,
                        MsoTriState.msoFalse,
                        MsoTriState.msoTrue,
                        // Isn't bit shifting fun? The below code aligns the 4 pictures to be laid out in a square
                        left + ((bit & 1) * width),
                        top + ((bit >> 1) * height),
                        width,
                        height);

                    bit++;
                }

                //Save the file to the user's documents folder
                var documentsPath = string.Format(@"{0}\\trialPowerPoint.pptx", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
                pptPresentation.SaveAs(documentsPath, PPT.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);

                // Make sure we always close PowerPoint after finishing
                pptPresentation.Close();
                pptApplication.Quit();

                resultLabel.Text = "The powerpoint slide has been successfully created and saved to your Documents folder as 'trialPowerPoint'";
            }
            // Catch any errors, let the user know it didn't go through, and make sure the powerpoint is cleaned up
            catch (Exception ex)
            {
                // Make sure we always close PowerPoint after finishing
                pptPresentation.Close();
                pptApplication.Quit();
                resultLabel.Text = "Sorry, we ran into an issue and were unable to create your PowerPoint Slide.";
                Console.WriteLine(ex);
            }
        }
Example #29
0
        private void savePage(int pptNum)
        {
            savePptNum  = pptNum;
            savePageNum = ppt[pptNum].ActiveWindow.Selection.SlideRange.SlideNumber;

            //save와lock다른경우
            if ((savePageNum != lockPageNum) || (savePptNum != lockPptNum))
            {
                MessageBox.Show(lockPageNum + "의 slide를 수정완료먼저해주세요");
                return;
            }

            try
            {
                //save slide복사해서 새로운피피티 생성
                presentation[pptNum].Save();
                PowerPoint.Application  tempPpt          = new PowerPoint.Application();
                PowerPoint.Presentation tempPresentation = tempPpt.Presentations.Add(MsoTriState.msoFalse);
                PowerPoint.Slides       tempSlides       = tempPresentation.Slides;
                tempSlides.InsertFromFile(ButtonPPT[pptNum].Tag.ToString(), 0, savePageNum, savePageNum);
                tempPresentation.SaveAs(_namePath + @"\" + "slide");
                FileInfo file = new FileInfo(_namePath + @"\" + "slide.pptx");

                //savePacket
                Console.WriteLine("client : save");
                byte[] buffer = new byte[1024 * 4];
                savePacket          = new SavePacket();
                savePacket.type     = (int)PacketType.SAVE;
                savePacket.pptNum   = savePptNum;
                savePacket.pageNum  = savePageNum;
                savePacket.isSave   = true;
                savePacket.fileSize = file.Length;
                if (presentation[pptNum].Slides.Count == slideCnt[pptNum])  //추가된슬라이드인가
                {
                    savePacket.isAdd = false;
                }
                else
                {
                    savePacket.isAdd = true;
                }
                slideCnt[pptNum] = presentation[pptNum].Slides.Count;

                Packet.Serialize(savePacket).CopyTo(buffer, 0);
                stream.Write(buffer, 0, buffer.Length);


                //새로운피피티 server로보냄
                FileStream fs    = file.OpenRead();
                byte[]     bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                stream.Write(bytes, 0, bytes.Length);

                tempPresentation.Close();
                fs.Close();
                stream.Flush();
                File.Delete(_namePath + @"\" + "slide.pptx");
            }
            catch (Exception e)
            {
                Console.WriteLine("savePage() 에러 : " + e.Message);
            }
        }
Example #30
0
 public void ClosePresentation()
 {
     Presentation.Close();
     PowerPointApp.Quit();
 }
Example #31
0
        private void ExtractSlidesFromPPT(bool visible)
        {
            Microsoft.Office.Interop.PowerPoint.Application  app = null;
            Microsoft.Office.Interop.PowerPoint.Presentation ppt = null;
            try {
                // PPTのインスタンス作成
                app = new Microsoft.Office.Interop.PowerPoint.Application();

                // 表示する
                app.Visible = (visible) ? Microsoft.Office.Core.MsoTriState.msoTrue : Microsoft.Office.Core.MsoTriState.msoFalse;

                foreach (ListViewItem lvi in listView1.Items)
                //foreach (string item in listBox1.Items)
                {
                    String pptfilename = lvi.SubItems[0].Text;//item;// label1.Text;

                    if (lvi.SubItems[2].Text == "Done")
                    {
                        label2.Text = "Skipping " + pptfilename + "... ";
                        continue;
                    }
                    else
                    {
                        label2.Text = "Opening " + pptfilename + "... ";
                    }


                    // オープン
                    ppt = app.Presentations.Open(pptfilename,
                                                 Microsoft.Office.Core.MsoTriState.msoTrue,
                                                 Microsoft.Office.Core.MsoTriState.msoFalse,
                                                 Microsoft.Office.Core.MsoTriState.msoFalse);

                    // https://msdn.microsoft.com/JA-JP/library/office/ff746030.aspx
                    String basefilename = Properties.Settings.Default.BaseFolderPath + "\\" + pptfilename.Replace("\\", "_").Replace(":", "_");
                    label2.Text += "#Slides=" + ppt.Slides.Count;
                    int numslides = ppt.Slides.Count;
                    for (int i = 1; i <= numslides; i++)
                    {
                        // スライド番号は1から始まるのに注意
                        ppt.Slides.Range(i).Export(basefilename + i.ToString("_%03d") + ".png", "png", 640, 480);
                    }
                    ppt.Close();
                    lvi.SubItems[1].Text = numslides.ToString();
                    lvi.SubItems[2].Text = "Done";
                    //app.Presentations[1].Close();
                }
                label2.Text = "Done.";

                // http://stackoverflow.com/questions/981547/powerpoint-launched-via-c-sharp-does-not-quit
                GC.Collect();
                GC.WaitForPendingFinalizers();
//                ppt.Close();
                Marshal.ReleaseComObject(ppt);
                app.Quit();
                Marshal.ReleaseComObject(app);

//                app.Presentations[0].Close();
            }
            catch { }
        }
Example #32
0
        public List <IFileItem> AppendSlides(List <PPT.Slide> srcSlides)
        {
            PPT.Application   ppt             = null;
            PPT.Presentations pres            = null;
            PPT.Presentation  pptPresentation = null;
            try
            {
                ppt  = new PPT.Application();
                pres = ppt.Presentations;

                pptPresentation = pres.Open(FullPath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue);

                PPT.DocumentWindow wnd = pptPresentation.Windows[1];
                //wnd.Height = 200;
                //wnd.Top = -200;
                wnd.WindowState = PPT.PpWindowState.ppWindowMinimized;
                wnd             = null;

                #region Alt. slower approach by copy ppt and insert slides from file
                //Copy
                //string tempFile = @"c:\WRK\Temp.pptx";
                //ppt.ActivePresentation.SaveCopyAs(tempFile, PPT.PpSaveAsFileType.ppSaveAsDefault, Microsoft.Office.Core.MsoTriState.msoTrue);
                //PPT.Presentation tempPPT = ppt.Presentations.Open(tempFile,MsoTriState.msoFalse,MsoTriState.msoFalse, MsoTriState.msoFalse);

                //List<string> slideNames = slides.Select(slide => slide.Name).ToList();
                //var v = from PPT.Slide sl in tempPPT.Slides where !slideNames.Contains(sl.Name) select sl;
                //foreach(PPT.Slide s in v)
                //{
                //    s.Delete();
                //}
                //tempPPT.Save();
                //tempPPT.Close();
                //gallery.Slides.InsertFromFile(tempFile, gallery.Slides.Count);
                #endregion

                PPT.Slides gSlides    = pptPresentation.Slides;
                int        startIndex = gSlides.Count + 1;
                foreach (PPT.Slide slide in srcSlides)
                {
                    slide.Copy();
                    gSlides.Paste();
                }
                List <IFileItem> newItems = new List <IFileItem>();
                newItems = fileIndex.UpdateIndex(pptPresentation, startIndex);

                return(newItems);
            }
            finally
            {
                if (pptPresentation != null)
                {
                    pptPresentation.Save();
                    pptPresentation.Close();
                }
                pptPresentation.ReleaseCOM();
                pptPresentation = null;

                pres.ReleaseCOM();
                pres = null;

                ppt.ReleaseCOM();
                ppt = null;
            }
        }
Example #33
0
        public void ToPdf()
        {
            bool occupy = true;

            while (occupy)
            {
                try
                {
                    using (File.Open(m_FilePathPowerPoint, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                    { }
                    occupy = false;//如果可以运行至此那么就是
                }
                catch (IOException e)
                {
                    e.ToString();
                    Thread.Sleep(100);
                }
            }
            PPT.Application  pptApp       = null;
            PPT.Presentation presentation = null;
            try
            {
                pptApp       = new PPT.Application();
                presentation = pptApp.Presentations.Open(m_FilePathPowerPoint,
                                                         Microsoft.Office.Core.MsoTriState.msoCTrue,
                                                         Microsoft.Office.Core.MsoTriState.msoFalse,
                                                         Microsoft.Office.Core.MsoTriState.msoFalse);
                string strPdf = m_FilePathPowerPoint.Substring(0, m_FilePathPowerPoint.LastIndexOf('.')) + ".pdf";
                if (presentation != null)
                {
                    presentation.ExportAsFixedFormat(strPdf, PPT.PpFixedFormatType.ppFixedFormatTypePDF,
                                                     PPT.PpFixedFormatIntent.ppFixedFormatIntentPrint,
                                                     CORE.MsoTriState.msoFalse, PPT.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                                                     PPT.PpPrintOutputType.ppPrintOutputSlides, Microsoft.Office.Core.MsoTriState.msoFalse,
                                                     null, PPT.PpPrintRangeType.ppPrintAll, "",
                                                     false, false, false, true, true, System.Reflection.Missing.Value);
                }
                if (presentation != null)
                {
                    presentation.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(presentation);
                }
                if (pptApp != null)
                {
                    pptApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pptApp);
                }
                PostHttpMsg pm = new PostHttpMsg();
                pm.DataPost = strPdf;
                pm.PostMsg();
            }
            catch (System.Exception e)
            {
                e.ToString();
            }
            finally
            {
                presentation = null;
                pptApp       = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        /// <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 { }
        }