Example #1
0
        /// <summary>
        ///     Converts the power point to PDF.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="processingPath">The processing path.</param>
        /// TODO Edit XML Comment Template for ConvertPowerPointToPdf
        private static void ConvertPowerPointToPdf(
            string fileName,
            string processingPath)
        {
            var powerPointApplication = new PowerPointApplication
            {
                DisplayAlerts      = PpAlertLevel.ppAlertsNone,
                AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable,
                DisplayDocumentInformationPanel = false
            };

            var powerPointPresentation =
                powerPointApplication.Presentations.Open(
                    fileName,
                    WithWindow: MsoTriState.msoFalse);

            if (powerPointPresentation == null)
            {
                powerPointApplication.Quit();
                return;
            }

            try
            {
                powerPointPresentation.ExportAsFixedFormat(
                    processingPath,
                    PpFixedFormatType.ppFixedFormatTypePDF);
            }
            finally
            {
                powerPointPresentation.Close();
                powerPointApplication.Quit();
            }
        }
Example #2
0
 public void replaceContent(List <Segment> segments, string path)
 {
     Microsoft.Office.Interop.PowerPoint.Application   application         = new Microsoft.Office.Interop.PowerPoint.Application();
     Microsoft.Office.Interop.PowerPoint.Application   pwpApp              = new Microsoft.Office.Interop.PowerPoint.Application();
     Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = pwpApp.Presentations;
     Microsoft.Office.Interop.PowerPoint.Presentation  presentation        = multi_presentations.Open(path, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
     try
     {
         foreach (Segment segment in segments)
         {
             int    shape  = segment.shape;
             int    slide  = segment.slide;
             string source = segment.getTMSource();
             string target = segment.getTMTarget();
             if (!string.IsNullOrEmpty(target))
             {
                 Microsoft.Office.Interop.PowerPoint.TextRange textRange = presentation.Slides[slide].Shapes[shape].TextFrame.TextRange;
                 textRange.Replace(source, target, 0, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
             }
         }
         presentation.Save();
         presentation.Close();
         pwpApp.Quit();
     }
     catch (Exception ex)
     {
         presentation.Save();
         presentation.Close();
         pwpApp.Quit();
         File.Delete(path);
     }
 }
        public static void ConvertFromPowerPoint(string sourcePath, string targetPath)
        {
            PowerPoint.Application  application  = new PowerPoint.Application();
            PowerPoint.Presentation presentation = null;
            try
            {
                application  = new PowerPoint.Application();
                presentation = application.Presentations.Open(sourcePath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                presentation.SaveAs(targetPath, PowerPoint.PpSaveAsFileType.ppSaveAsXPS);
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
            }
        }
Example #4
0
        private void Release()
        {
            if (presentation != null)
            {
                try
                {
                    presentation.Close();
                    ReleaseCOMObject(presentation);
                }
                catch
                {
                }
            }

            if (app != null)
            {
                try
                {
                    app.Quit();
                    ReleaseCOMObject(app);
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// Quits the PowerPoint Application.
        /// </summary>
        public void QuitPowerPoint()
        {
            if (m_pptApp == null)
            {
                return;
            }

            // closing the presentation would not close the application, so we
            // close it explicitly if there are no more presentations.  Since
            // only one instance of PowerPoint can be running at a time, we need
            // to make sure that there are no more presentations before quiting the
            // application
            if (m_pptApp.Presentations != null && m_pptApp.Presentations.Count == 0)
            {
                try
                {
                    m_pptApp.Quit();
                }
                catch (Exception e)
                {
                    Logger.LogError("Failed to quit PowerPoint", e);
                }
            }

            m_pptApp = null;
        }
Example #6
0
        public void CreatePowerPoint(CreateFileBindingModel createPPBindingModel)
        {
            //Uses CreateFileBindingModel to get specific information from it.

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

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

            //This closes the created in the background application and quits it.
            objPresentation.Close();
            objPowerPoint.Quit();
        }
Example #7
0
        /// <summary>
        /// Converts PowerPoint documents to PDFs
        /// </summary>
        /// <param name="rootPath">The path of the directory that contains all PowerPoint documents to be converted</param>
        static void ppt2pdf(string rootPath)
        {
            var objPowerPoint = new PowerPoint.Application()
            {
                DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone
            };

            objPowerPoint.WindowState = PowerPoint.PpWindowState.ppWindowMinimized;
            convert2pdf(rootPath, "*.ppt?", (inputPath, outputPath) =>
            {
                var pptDoc = objPowerPoint.Presentations.Open(inputPath, ReadOnly: MsoTriState.msoTrue);
                pptDoc.ExportAsFixedFormat2(outputPath, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint, OutputType: PowerPoint.PpPrintOutputType.ppPrintOutputNotesPages, PrintHiddenSlides: MsoTriState.msoTrue, UseISO19005_1: true);
                //Using printers to generate pdfs

                /*
                 * pptDoc.PrintOptions.ActivePrinter = "Microsoft Print to PDF";
                 * pptDoc.PrintOptions.OutputType = PowerPoint.PpPrintOutputType.ppPrintOutputNotesPages;
                 * pptDoc.PrintOptions.PrintHiddenSlides = MsoTriState.msoTrue;
                 * pptDoc.PrintOptions.HighQuality = MsoTriState.msoTrue;
                 * pptDoc.PrintOptions.FitToPage = MsoTriState.msoTrue;
                 * pptDoc.PrintOut(PrintToFile: outputPath);
                 */
                pptDoc.Close();
                return(true);
            });
            objPowerPoint.Quit();
        }
Example #8
0
 public DirectoryInfo Convert(FileInfo ppt)
 {
     DirectoryInfo dir = new DirectoryInfo(ppt.Directory.FullName + "/" + Path.GetFileNameWithoutExtension(ppt.Name));
     dir.Create();
     PowerPoint.Application pptApp = null;
     PowerPoint.Presentation pptDoc = null;
     try
     {
         pptApp = new PowerPoint.Application();
         pptDoc = pptApp.Presentations.Open(ppt.FullName, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse);
         if (pptDoc.CreateVideoStatus != PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusInProgress
             && pptDoc.Slides.Count > 0)
         {
             pptDoc.Export(dir.FullName, "png");
         }
     }
     catch (Exception e)
     {
         log.Error("Convert PPT error", e);
     }
     finally
     {
         if (pptDoc != null)
             pptDoc.Close();
         if(pptApp != null)
             pptApp.Quit();
     }
     return dir;
 }
        private void PPTAs(string infile, string outfile, PpSaveAsFileType targetFileType)
        {
            object       missing      = Type.Missing;
            Presentation persentation = null;

            PowerPoint.Application pptApp = null;
            try
            {
                pptApp       = new PowerPoint.Application();
                persentation = pptApp.Presentations.Open(infile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(outfile, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("PPT {0} 转换出错,异常信息: {1}", infile, ex.Message);
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (pptApp != null)
                {
                    pptApp.Quit();
                    pptApp = null;
                }
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Example #10
0
        public static void OpenPresentationToUser(PowerpointLoadInfo info)
        {
            if (!System.IO.File.Exists(info.filePath))
            {
                return;
            }
            PowerpointLoader loader;

            if (PRESENTATIONS.TryGetValue(info.filePath, out loader))
            {
                loader.saveAndClose();
            }

            MsoTriState ofalse = MsoTriState.msoFalse;
            MsoTriState otrue  = MsoTriState.msoTrue;

            PowerPoint.Application PowerPointApplication = new PowerPoint.Application();
            PowerPointApplication.Presentations.Open(@info.filePath, ofalse, ofalse, otrue);

            int currrent = PowerPointApplication.Presentations.Count;

            PowerPoint.Presentation Presentation = PowerPointApplication.Presentations[currrent];

            //if (Presentation != null) Presentation.Close();
            if (PowerPointApplication == null)
            {
                return;
            }
            if (PowerPointApplication.Presentations.Count == 0)
            {
                PowerPointApplication.Quit();
            }
        }
Example #11
0
        private void Form2_Load(object sender, EventArgs e)
        {
            string fileName   = @"C:\Users\Tridip\Desktop\KPIDashBoard20170125 125513.pptx";
            string exportName = "video_of_presentation";
            string exportPath = @"D:\test\Export\{0}.wmv";

            Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
            ppApp.Visible     = Microsoft.Office.Core.MsoTriState.msoTrue;
            ppApp.WindowState = PpWindowState.ppWindowMinimized;
            Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;
            Microsoft.Office.Interop.PowerPoint._Presentation oPres    = oPresSet.Open(fileName,
                                                                                       Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse,
                                                                                       Microsoft.Office.Core.MsoTriState.msoFalse);
            try
            {
                //oPres.CreateVideo(exportName);
                oPres.SaveCopyAs(String.Format(exportPath, exportName),
                                 Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsEMF,
                                 Microsoft.Office.Core.MsoTriState.msoCTrue);
            }
            finally
            {
                ppApp.Quit();
            }
        }
Example #12
0
        /// <summary>
        /// 清理资源
        /// </summary>
        /// <param name="applicationObject"></param>
        /// <param name="presentationObject"></param>
        private void Dispose(object applicationObject, object presentationObject)
        {
            Application  app = (Application)applicationObject;
            Presentation pp  = (Presentation)presentationObject;

            try
            {
                if (pp != null)
                {
                    pp.Close();
                    Marshal.ReleaseComObject(pp);
                }
                if (app != null)
                {
                    app.Quit();
                    Marshal.ReleaseComObject(app);
                }
            }
            catch (Exception ex)
            {
                // 当 app or pp 带着异常进入时,这里可能再次抛出异常。
                // 如:上文中的 -2147467262 异常。
                Trace.WriteLine($"ppttoenbx:Error When Dispose. 异常信息可能是重复的-{ex.Message}");
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Example #13
0
        private static string ParsePowerPointToText(string inputFile, string outputFile)
        {
            var PowerPoint_App = new PowerPoint.Application();

            try
            {
                var multi_presentations = PowerPoint_App.Presentations;
                var presentation        = multi_presentations.Open(inputFile);
                var presentation_text   = "";
                for (var i = 0; i < presentation.Slides.Count; i++)
                {
                    presentation_text = (from PowerPoint.Shape shape in presentation.Slides[i + 1].Shapes where shape.HasTextFrame == MsoTriState.msoTrue where shape.TextFrame.HasText == MsoTriState.msoTrue select shape.TextFrame.TextRange into textRange select textRange.Text).Aggregate(presentation_text, (current, text) => current + (text + " "));
                }

                if (string.IsNullOrEmpty(outputFile))
                {
                    return(presentation_text);
                }

                using (var sw = new StreamWriter(outputFile))
                {
                    sw.WriteLine(presentation_text);
                }
                Console.WriteLine(presentation_text);
            }
            finally
            {
                PowerPoint_App.Quit();
                Marshal.FinalReleaseComObject(PowerPoint_App);
                GC.Collect();
                KillProcess();
            }
            return(string.Empty);
        }
Example #14
0
        public override void Dispose()
        {
            if (_app == null)
            {
                // 已经释放,无需再释放
                return;
            }

            Console.WriteLine("关闭PowerPoint!");

            try
            {
                if (_ppts != null)
                {
                    ReleaseCOMObject(_ppts);
                    _ppts = null;
                }

                _app.Quit();
                ReleaseCOMObject(_app);
                _app = null;
            }
            catch
            {
                // TODO 退出Wold程序失败
            }
        }
Example #15
0
        private bool disposedValue = false; // To detect redundant calls

        protected override void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    try
                    {
                        if (POWERPNT != null && POWERPNT.Presentations.Count == 0)
                        {
                            POWERPNT.Quit();
                            POWERPNT = null;
                        }
                    }
                    catch { }
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
            base.Dispose(disposing);
        }
        /// <summary>
        /// PPTs to PDF.
        /// </summary>
        /// <param name="inputFilePath">The input file path.</param>
        /// <returns>Pdf檔案路徑.</returns>
        public static string PptToPdf(string inputFilePath)
        {
            var ext = Path.GetExtension(inputFilePath);

            if (string.IsNullOrEmpty(ext) || (!ext.Equals(".ppt") && !ext.Equals(".pptx")))
            {
                throw new ArgumentException("副檔名錯誤!應為*.ppt, *.pptx", nameof(inputFilePath));
            }

            string outputDir      = Path.GetTempPath();
            string outputFileName = Guid.NewGuid().ToString().ToUpper();
            string outputPath     = string.Empty;

            if (!File.Exists(inputFilePath))
            {
                throw new ArgumentException(string.Format("找不到檔案:{0}!", inputFilePath), nameof(inputFilePath));
            }

            var          pptApp       = new Microsoft.Office.Interop.PowerPoint.Application();
            Presentation presentation = pptApp.Presentations.Open(
                inputFilePath,
                MsoTriState.msoTrue,
                MsoTriState.msoFalse,
                MsoTriState.msoFalse);

            outputPath = Path.Combine(outputDir, outputFileName + ".pdf");
            presentation.SaveAs(outputPath, PpSaveAsFileType.ppSaveAsPDF);
            pptApp.DisplayAlerts = PpAlertLevel.ppAlertsNone;
            pptApp.Quit();

            return(outputPath);
        }
Example #17
0
        private void OutputImageFiles(string fileName)
        {
            Directory.CreateDirectory(OutputPath);

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

            try
            {
                app = new Microsoft.Office.Interop.PowerPoint.Application();
                ppt = app.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                int width  = DefaultWidth * 2;
                int height = DefaultHeight * 2;
                totalSlideNum = ppt.Slides.Count;

                for (int i = 1; i <= totalSlideNum; i++)
                {
                    string output = OutputPath + String.Format("/slide{0:0000}.jpg", i - 1);
                    ppt.Slides[i].Export(output, "jpg", width, height);
                }
            }
            finally
            {
                if (ppt != null)
                {
                    ppt.Close();
                }

                if (app != null)
                {
                    app.Quit();
                    app = null;
                }
            }
        }
Example #18
0
        public void createFile(string filepath)
        {
            if (filepath.EndsWith(".xlsx"))
            {
                Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                Workbook ExcelWorkBook = null;
                ExcelApp.Visible       = false;
                ExcelApp.DisplayAlerts = false;

                ExcelWorkBook = ExcelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                ExcelWorkBook.SaveAs(filepath);
                ExcelWorkBook.Close();
                ExcelApp.Quit();
            }
            else if (filepath.EndsWith(".pptx"))
            {
                Application pptApplication = new Application();
                // Create the Presentation File
                Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
                Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];

                Microsoft.Office.Interop.PowerPoint.Slides slides = pptPresentation.Slides;
                Microsoft.Office.Interop.PowerPoint.Slide  slide  = slides.AddSlide(1, customLayout);
                pptPresentation.SaveAs(filepath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
                pptPresentation.Close();
                pptApplication.Quit();
            }
            else
            {
                File.Create(filepath).Close();
            }
        }
Example #19
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。
                if (app != null)
                {
                    try
                    {
                        app.SlideShowBegin -= OnAppOnSlideShowBegin;
                        app.SlideShowEnd   -= OnAppOnSlideShowEnd;
                        if (app.Visible == MsoTriState.msoFalse)
                        {
                            app.Quit();
                        }
                    }
                    catch (COMException)
                    {
                    }
                }
                disposedValue = true;
            }
        }
        /// <summary>
        /// Converts PowerPoint presentation to images where is slide is given by one image
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputDir"></param>
        /// <returns>the directory of the images</returns>
        protected string ConvertPowerPointToImages(string inputFile, string outputDir)
        {
            // temp directory for images
            string imgsPath = Utility.CreateDirectory(Utility.NewFolderPath(outputDir, "imgs"));

            //Get the presentation
            var powerPoint   = new Microsoft.Office.Interop.PowerPoint.Application();
            var presentation = powerPoint.Presentations.Open(inputFile);

            // Save each slide as picture
            try
            {
                presentation.SaveAs(imgsPath, PpSaveAsFileType.ppSaveAsPNG);
            }
            catch (COMException e)
            {
                Console.WriteLine("Presenation doesn't have any slide.");
                Console.WriteLine(e.Message);
                return(String.Empty);
            }
            finally
            {
                // Close power point application
                presentation.Close();
                powerPoint.Quit();
            }
            return(imgsPath);
        }
Example #21
0
        public static void ExecuteExtraction(string sourceFileName, string destFileName)
        {
            Application  _application = new Microsoft.Office.Interop.PowerPoint.Application();
            var          pres         = _application.Presentations;
            Presentation pptFile      = pres.Open(sourceFileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

            string storeContent = "";
            int    slideCount   = pptFile.Slides.Count;

            for (int i = 1; i <= slideCount; i++)
            {
                Slide slide = pptFile.Slides[i];
                slide.FollowMasterBackground = MsoTriState.msoFalse;
                foreach (var item in slide.Shapes)
                {
                    var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        //shape.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToWin32(Color.Red);
                        var textRange = shape.TextFrame.TextRange;
                        var text      = textRange.Text;
                        storeContent += text + " ";
                    }
                }
            }

            FileOperators.FileWrite(destFileName, storeContent);
            pptFile.Close();
            _application.Quit();
        }
        private void release()
        {
            if (presentation != null)
            {
                try
                {
                    presentation.Close();
                    releaseCOMObject(presentation);
                }
                catch (Exception e)
                {
                }
            }

            if (app != null)
            {
                try
                {
                    app.Quit();
                    releaseCOMObject(app);
                }
                catch (Exception e)
                {
                }
            }
        }
Example #23
0
        //edits text in project description ppt
        private static void EditPPT(string parkName, string projectName)
        {
            string pPath = localPath + parkName + "\\" + projectName + "\\Project Description, Photos, Map\\Project Description.pptx";

            if (!File.Exists(pPath))
            {
                return;
            }

            PPT.Application  pApp   = new PPT.Application();
            PPT.Presentation pPres  = pApp.Presentations.Open(pPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            PPT.Slide        pSlide = pPres.Slides[1];

            foreach (PPT.Shape s in pSlide.Shapes)
            {
                if (s.Name.Equals("Title 2"))
                {
                    s.TextFrame.TextRange.Delete();
                    s.TextFrame.TextRange.InsertBefore(projectName);
                }

                if (s.Name.Equals("Text Placeholder 3"))
                {
                    s.TextFrame.TextRange.Delete();
                    s.TextFrame.TextRange.InsertBefore(parkName);
                }
            }

            pPres.Save();
            pPres.Close();
            pApp.Quit();
            pApp = null;
            GC.Collect();
        }
Example #24
0
 public void Dispose()
 {
     _presentation?.Close();
     _app?.Quit();
     _app          = null;
     _presentation = null;
 }
Example #25
0
        private void cmbOutput_Click(object sender, EventArgs e)
        {
            PowerPoint.Application  pptApp;
            PowerPoint.Presentation pptDoc;


            pptApp         = new PowerPoint.Application();
            pptApp.Visible = OfficeCore.MsoTriState.msoTrue;
            pptDoc         = pptApp.Presentations.Open(txtInput.Text, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse);
            if (pptDoc.CreateVideoStatus != PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusInProgress)
            {
                pptDoc.Export(txtOutput.Text, "jpg", Convert.ToInt32(txtWidth.Text), Convert.ToInt32(txtHeight.Text));
            }


            pptDoc.Close();
            System.Threading.Thread.Sleep(1000);
            pptApp.Quit();
            pptDoc = null;
            pptApp = null;

            FileInfo[] dirFile = new DirectoryInfo(txtOutput.Text).GetFiles();
            foreach (FileInfo fioFile in dirFile)
            {
                System.IO.File.Move(fioFile.FullName, fioFile.FullName.Replace(fioFile.Name, fioFile.Name.ToLower().Replace("幻灯片", "image")));
            }
        }
Example #26
0
        public void ConvertToPPTX(string vfileName)
        {
            try
            {
                PowerPoint.Application powerpoint = new PowerPoint.Application();
                // Excel.Workbook wbook = new Excel.Workbook();

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


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


                //
                //excel.Quit();
            }
            catch (Exception exception)
            {
                LogManager.GetLogger(typeof(BusinessClass).FullName).Error("Error is directory search, Error: " + exception.Message);
            }
        }
Example #27
0
 /// <summary>
 /// Close the Powerpoint Application
 /// </summary>
 private void CloseOfficeApplication()
 {
     if (powerPointApplication != null)
     {
         powerPointApplication.Quit();
         powerPointApplication = null;
     }
 }
 public void MyTestCleanup()
 {
     foreach (PowerPoint.Presentation presentation in application.Presentations)
     {
         presentation.Close();
     }
     application.Quit();
 }
 public void QuitApplication()
 {
     if (!HasActivePresentation())
     {
         return;
     }
     Application.Quit();
 }
 public void Quit()
 {
     app = new PP.Application();
     if (app.Presentations.Count == 0)
     {
         app.Quit();
     }
 }
Example #31
0
 /// <summary>
 ///		Close MS Application. Throws ApplicationException upon failure.
 /// </summary>
 public void Close()
 {
     try {
         // Exit without prompting the save dialog
         app.Quit();
     } catch (Exception ex) {
         throw new ApplicationException("Could not cleanly shutdown MS Word. Error message: " + ex.Message);
     }
 }
Example #32
0
        public static void convert(int coursewareId, int userId, String inputFileName)
        {
            //输入文件的所在文件夹路径(ppt所在文件夹)
            string inputFilePath = System.Configuration.ConfigurationManager.AppSettings["FILE_SERVER_PATH"] + "input\\" + coursewareId + "\\";
            string inputFilePathName = inputFilePath + inputFileName;

            //输出图片文件夹路径
            string outputFilePath = System.Configuration.ConfigurationManager.AppSettings["FILE_SERVER_PATH"] + "output\\" + coursewareId + "\\pic\\";
            //输出图片的宽度
            int outputPicWidth = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PPT_OUTPUT_PIC_WIDTH"]);
            //输出图片的高度
            int outputPicHeight = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PPT_OUTPUT_PIC_HEIGHT"]);

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

            PowerPoint.Application pptApplication = new PowerPoint.Application();
            //记录日志(目前暂记录到系统日志中,可考虑写到数据库)
            EventLog.WriteEntry("ppt-start", "try convert " + inputFilePathName);

            PowerPoint.Presentation ppt = pptApplication.Presentations.Open(inputFilePathName,

                                    Microsoft.Office.Core.MsoTriState.msoTrue,

                                    Microsoft.Office.Core.MsoTriState.msoFalse,

                                    Microsoft.Office.Core.MsoTriState.msoFalse);

            PowerPoint.Presentation pptPresentation = pptApplication.Presentations.Open(inputFilePathName, MsoTriState.msoFalse,
            MsoTriState.msoFalse, MsoTriState.msoFalse);

            string fileNameTmp = coursewareId + "_{0}.jpg";
            for (int i = 1; i <= ppt.Slides.Count; i++)
            {//循环保存每帧图片
                string fileName = string.Format(fileNameTmp, i);
                //输出到文件
                ppt.Slides[i].Export(outputFilePath + fileName, "jpg", outputPicWidth, outputPicHeight);
                //保存到数据库
                PptDao.savePptImage(userId, coursewareId, i, "/res/data/coursewarePkg/output/" + coursewareId + "/pic/" + fileName);
            }
            EventLog.WriteEntry("ppt-complete", "convert complete " + inputFilePathName);

            ppt.Close();

            pptApplication.Quit();
        }
Example #33
0
 public static new Boolean Convert(String inputFile, String outputFile) {
     Microsoft.Office.Interop.PowerPoint.Application app;
     try {
         app = new Microsoft.Office.Interop.PowerPoint.Application();
         app.Visible = MSCore.MsoTriState.msoTrue;
         app.Presentations.Open(inputFile, MSCore.MsoTriState.msoFalse, MSCore.MsoTriState.msoTrue, MSCore.MsoTriState.msoTrue);
         app.ActivePresentation.SaveAs(outputFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MSCore.MsoTriState.msoCTrue);
         app.ActivePresentation.Close();
         app.Quit();
         return true;
     } catch (Exception e) {
         Console.WriteLine(e.Message);
         return false;
     } finally {
         app = null;
     }
 }
Example #34
0
        public override string Read()
        {
            try
            {
                powerPointApp = new PowerPoint.Application();
                powerPointApp.Visible = MsoTriState.msoFalse;
                multiPresentations = powerPointApp.Presentations;

                MsoTriState trueState = MsoTriState.msoTrue;
                MsoTriState falseState = MsoTriState.msoFalse;
                string filePath = (string)FilePath;

                presentation = multiPresentations.Open(filePath,
                                                       trueState,
                                                       falseState,
                                                       falseState);

                string result = string.Empty;

                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (PowerPoint.Shape)item;
                        if (shape.HasTextFrame == MsoTriState.msoTrue && shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            result += textRange.Text;
                        }
                    }
                }

                powerPointApp.Quit();

                return result;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #35
0
        static int Main(string[] args)
        {
            string usage = "Usage: PPTVideo.exe <infile> <outfile> [-d]";

                        try{
                                if (args.Length < 2)
                                        throw new ArgumentException("Wrong number of arguments.\n" + usage);

                                PowerPoint._Presentation objPres;
                                objApp = new PowerPoint.Application();
                                //objApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

                                objPres = objApp.Presentations.Open(Path.GetFullPath(args[0]), MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
                                objPres.SaveAs(Path.GetFullPath(args[1]), PowerPoint.PpSaveAsFileType.ppSaveAsWMV, MsoTriState.msoTriStateMixed);
                                long len = 0;
                                do{
                                        System.Threading.Thread.Sleep(500);
                                        try {
                                                FileInfo f = new FileInfo(args[1]);
                                                len = f.Length;
                                        } catch {
                                                continue;
                                        }
                                } while (len == 0);
                                objApp.Quit();

                                //
                                // Check if we want to delete the input file
                                //
                                if (args.Length > 2 && args[2] == "-d")
                                        File.Delete(args[0]);
                        }
                        catch (Exception e)
                        {
                                System.Console.WriteLine("Error: " + e.Message);
                                return 1;
                        }

                        return 0;
        }
Example #36
0
        public static QuizDocument Parse(string filePath)
        {
            QuizDocument doc = new QuizDocument();
            PPT.Application pptApp = new PPT.Application();
            PPT.Presentation ppt = pptApp.Presentations.Open(filePath);
            Directory.Delete(IMAGE_TEMP_PATH, true);
            ppt.SaveCopyAs(IMAGE_TEMP_PATH, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsJPG);
            doc.ExtractDetails(filePath);

            foreach (PPT.Slide pptSlide in ppt.Slides)
            {
                QuizSlide docSlide = QuizSlide.Parse(pptSlide, IMAGE_TEMP_PATH);
                docSlide.QuizDoc = doc;
                doc.Slides.Add(docSlide);
                ImageHelper.ResaveImage(docSlide.ImagePath, 0.5m, IMAGE_RESIZED_TEMP_PATH);
                docSlide.ImagePath = docSlide.ImagePath.Replace(IMAGE_TEMP_PATH, IMAGE_RESIZED_TEMP_PATH);
            }
            ppt.Close();
            pptApp.Quit();

            return doc;
        }
Example #37
0
        /// <summary>
        /// ファイルをPDF形式で保存
        /// </summary>
        public override void SavePdf()
        {
            //ファイルを取得
            string file = this.GetAbsolutePath();

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

            try
            {
                ppt = new Microsoft.Office.Interop.PowerPoint.Application();

                //ファイルを開く
                p = ppt.Presentations.Open(file);

                //PDFとして保存
                p.SaveAs(this.GetPdfPath(),
                    PpSaveAsFileType.ppSaveAsPDF,
                    Microsoft.Office.Core.MsoTriState.msoTrue);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                if(p != null)
                {
                    p.Close();
                }
                if (ppt != null)
                {
                    ppt.Quit();
                }
            }
        }
Example #38
0
    public static string StoreMediaTemp(HttpContextBase context, HttpPostedFileBase file, UploadType type, out string thumbPath, out string physicalPath, out TimeSpan duration, out string fileType)
    {
        duration = TimeSpan.Zero;
        fileType = "";
        if (context.Session != null)
        {
            UrlFriendlyGuid GUID = (UrlFriendlyGuid) context.Session["UploadGUID"];

            List<UploadedContent> lastSavedFile = new List<UploadedContent>();

            if (context.Session["SavedFileList"] != null)
                lastSavedFile = (List<UploadedContent>) context.Session["SavedFileList"];

            physicalPath = TempPathForUpload(context, file.FileName, type, GUID);
            thumbPath = TempPathForUpload(context, file.FileName, type, GUID, true);

            //Todo: Use mimes here instead of basic extension check
            if (ImageExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
            {
                var image = (Bitmap) Image.FromStream(file.InputStream);


                var fullImage =
                    (Bitmap) ImageUtilities.Resize(image, image.Width, image.Height, RotateFlipType.RotateNoneFlipNone); //No need to resize
                ImageUtilities.SaveImage(fullImage, physicalPath, ImageFormat.Jpeg, true);



                var thumbNail =
                    (Bitmap) ImageUtilities.Resize(image, 216, 132, RotateFlipType.RotateNoneFlipNone);
                ImageUtilities.SaveImage(thumbNail, thumbPath, ImageFormat.Jpeg, true);

                duration = new TimeSpan(0,0,10);

                fileType = "Image";
            }
            else
            {
                var extension = Path.GetExtension(file.FileName);
                if (extension != null && extension.ToLower()==(".txt"))
                {
                    FileUtilities.SaveStream(file.InputStream,physicalPath,false);
                    duration = new TimeSpan(0, 0, 20);
                    var text = new StreamReader(physicalPath).ReadToEnd();
                    var ssHot = CreateImage(text.Substring(0, text.Length>15?15:text.Length));
                    thumbPath = thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                    ssHot.Save(thumbPath);

                    fileType = "Marquee";
                }
                else
                {
                    var s = Path.GetExtension(file.FileName);
                    if (s != null && (s.ToLower() == (".ppt") || s.ToLower() == (".pps") || s.ToLower() == (".pptx") || s.ToLower() == (".odt"))) // Powerpoint presentation
                    {
                        string path = context.Server.MapPath("~/Logs/" + "serverlog.txt");

                        Logger.WriteLine(path, "UploadRepository:  Powerpoint");

                        FileUtilities.SaveStream(file.InputStream, physicalPath, false);

                        Logger.WriteLine(path, "UploadRepository:  Saved File @ " + physicalPath);
                        var finalPath = Path.ChangeExtension(physicalPath, "wmv");
                        Microsoft.Office.Interop.PowerPoint._Presentation objPres;
                        var objApp = new Microsoft.Office.Interop.PowerPoint.Application();

                        objApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
                        objApp.Activate();
                        try
                        {
                            objPres = objApp.Presentations.Open(physicalPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse); //Last value causes powerpoint to physically open
                            // Thread.Sleep(10000);
                            objPres.SaveAs(Path.GetFullPath(finalPath), Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV);
                            Logger.WriteLine(path, "UploadRepository:  SaveCopy As Successfully Started @ " + physicalPath + " to "+ finalPath);
               
                            long len = 0;
                            do
                            {
                                System.Threading.Thread.Sleep(500);
                                try
                                {
                                    FileInfo f = new FileInfo(finalPath);
                                    len = f.Length;
                                    Logger.WriteLine(path, "UploadRepository:  SaveCopy Current Length  " + len);
               
                                }
                                catch
                                {
                                    //continue;
                                }
                            }
                            while (len == 0);
                            objPres.Close();
                            objApp.Quit();

                            Marshal.ReleaseComObject(objPres);
                            Marshal.ReleaseComObject(objApp);

                            objApp = null;
                            objPres = null;

                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            Logger.WriteLine(path, "UploadRepository:  SaveCopy Done, Creating Thumbnails  ");
           

                            thumbPath = thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                            // thumbPath = "Content\\Images\\powerpoint.jpg";
                            duration = VideoUtilities.GetVideoDuration(finalPath);
                            // duration = new TimeSpan(0, 0, 0,60);
                            VideoUtilities.GetVideoThumbnail(finalPath, thumbPath);

                            physicalPath = finalPath;
                            fileType = "Powerpoint";
                        }
                        catch (COMException exception)
                        {
              
                            Logger.WriteLine(path, "UploadRepository: " + exception.StackTrace + "\n" + exception.Message + " Powerpoint fin:" + finalPath +" phys:" +physicalPath);

                            //   Logger.WriteLine(path, greenlotsInfo.email);

                            //    throw exception;
                        }

                    }
                    else // Must Be Video
                    {
                        FileUtilities.SaveStream(file.InputStream, physicalPath, false);

                        thumbPath= thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                        duration = VideoUtilities.GetVideoDuration(physicalPath);

                        VideoUtilities.GetVideoThumbnail(physicalPath,thumbPath);

                        fileType = "Video";
                    }
                }
            }

            var uploadedContent = new UploadedContent
                                      {
                                          MediaGuid = GUID,
                                          Type = type,
                                          Pictures = new List<string>(2),
                                          Duration = duration
                                      };

            if (physicalPath != null)
                uploadedContent.Pictures.Add(ResolvePath(context, physicalPath));
            if (thumbPath != null)
                uploadedContent.Pictures.Add(ResolvePath(context, thumbPath));



            if (uploadedContent.Pictures.Count > 0)
                lastSavedFile.Add(uploadedContent);


            context.Session["SavedFileList"] = lastSavedFile;


            return "Upload Sucessful";
        }
        thumbPath = "";
        physicalPath = "";

        return "Failed To Upload File(s)";
    }
Example #39
0
        static int Main(string[] args)
        {
            string usage = "Usage: converter.exe <infile> <outfile> <png|jpg|video> <useTimings> <> <>";
            try {
                if(args.Length < 3) {
                    throw new ArgumentException("Wrong number of arguments.\n" + usage);
                }
                string sourceFile = Path.GetFullPath(args[0]);
                string destFile = Path.GetFullPath(args[1]);

                PowerPoint.Application pptApplication = new PowerPoint.Application();
                PowerPoint.Presentation pptPresentation = pptApplication.Presentations.Open(sourceFile, MsoTriState.msoFalse,
                MsoTriState.msoFalse, MsoTriState.msoFalse);

                switch (args[2]){
                    case "video" :
                        bool useTimings = true;
                        int slideTime = 5;
                        int verticalResolution = 480;
                        int framePerSecond = 10;
                        int quality = 70;
                        if(args.Length > 3) {
                            useTimings = Convert.ToBoolean(args[3]);
                            if(args.Length > 4) {
                                slideTime = Convert.ToInt16(args[4]);
                                if(args.Length > 5) {
                                    verticalResolution = Convert.ToInt16(args[5]);
                                    if(args.Length > 6) {
                                        framePerSecond = Convert.ToInt16(args[6]);
                                        if(args.Length > 7) {
                                            quality = Convert.ToInt16(args[7]);
                                        }
                                    }
                                }
                            }
                        }
                        pptPresentation.CreateVideo(destFile, useTimings, slideTime, verticalResolution, framePerSecond, quality);
                        do{
                            System.Threading.Thread.Sleep(500);
                            System.Console.WriteLine(pptPresentation.CreateVideoStatus);
                        } while (pptPresentation.CreateVideoStatus != PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusDone);
                        System.Console.WriteLine("File converted to video");
                        break;
                    case "jpg" :
                    case "videofromjpg":
                        pptPresentation.Slides[1].Name = "moco";
                        pptPresentation.SaveAs(destFile, PowerPoint.PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue);
                        System.Console.WriteLine("File converted to jpg");
                        break;
                    case "png" :
                    case "videofrompng":
                    default:
                        pptPresentation.SaveAs(destFile, PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
                        System.Console.WriteLine("File converted to png");
                        break;
                }
                pptApplication.Quit();
            }
            catch (Exception e) {
                System.Console.WriteLine("Error: " + e.Message);
                return 1;
            }
            return 0;
        }
Example #40
0
        private void OutputImageFiles(string fileName)
        {
            Directory.CreateDirectory(OutputPath);

            Microsoft.Office.Interop.PowerPoint.Application app = null;
            Presentation ppt = null;
            try
            {
                app = new Microsoft.Office.Interop.PowerPoint.Application();
                ppt = app.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                int width = DefaultWidth * 2;
                int height = DefaultHeight * 2;
                totalSlideNum = ppt.Slides.Count;

                for (int i = 1; i <= totalSlideNum; i++)
                {
                    string output = OutputPath + String.Format("/slide{0:0000}.jpg", i-1);
                    ppt.Slides[i].Export(output, "jpg", width, height);
                }
            }
            finally
            {
                if (ppt != null)
                {
                    ppt.Close();
                }

                if (app != null)
                {
                    app.Quit();
                    app = null;
                }
            }
        }
Example #41
0
        static void Main(string[] args)
        {
            ParseArgs(args);

            var fileName = Path.GetFileNameWithoutExtension(_filePath);

            _noteFilePath =  Path.Combine(_outputPath, fileName + "_note.txt");
            _resultFilePath = Path.Combine(_outputPath, fileName + "_result.txt");

            if (!Directory.Exists(Path.Combine(_outputPath, "images")))
            {
                Directory.CreateDirectory(Path.Combine(_outputPath, "images"));
            }

            var imgsPath = Path.Combine(_outputPath, "images.jpg");
            try
            {
                _objApp = new PowerPoint.Application();
                _objPres = _objApp.Presentations.Open(_filePath, WithWindow: MsoTriState.msoFalse);

                _objPres.SaveAs(imgsPath, PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);

                // 保存备注
                SaveNoteInfo();

                // 设置呈现窗口
                SetSildeShowWindow();

                var pptRenderThread = InitPPTRenderThread();
                var imageSaveThread = InitImageSaveThread();

                pptRenderThread.Start();
                imageSaveThread.Start();

                while (_objApp.SlideShowWindows.Count >= 1) Thread.Sleep(deplyTime / 10);

                pptRenderThread.Abort();
                //pptRenderThread.Join();
                imageSaveThread.Abort();
                //imageSaveThread.Join();

                _objPres.Save();

                _objApp.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // 杀死powerpnt
            KillProcess("powerpnt");

            SaveResult();

            // 退出
            Environment.Exit(0);
        }
Example #42
0
        private static void AutomatePowerPointImpl()
        {
            try
            {
            // 创建一个Microsoft PowerPoint实例并使其不可见。

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

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

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

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

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

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

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

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

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

            // 退出PowerPoint应用程序

                Console.WriteLine("退出PowerPoint应用程序");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("解决方案2.AutomatePowerPoint抛出的错误: {0}",
                    ex.Message);
            }
        }
 /// <summary>
 /// ppt转换成pdf
 /// </summary>
 /// <param name="filePath"></param>
 public static void PPT2Pdf(string filePath)
 {
     path = filePath;
     saveFileName = filePath + ".pdf";
     var ppt = new PPT.Application();
     var doc = ppt.Presentations.Open(path.ToString(),
                Microsoft.Office.Core.MsoTriState.msoFalse,
                Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
     doc.SaveAs(saveFileName.ToString(), PPT.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
     doc.Close();
     doc = null;
     ppt.Quit();
     ppt = null;
 }
Example #44
0
        private void InsertPictureButton_Click(object sender, EventArgs e)
        {
            // Insert pictures from listbox one by one

            try
            {
                // Create an instance of Microsoft PowerPoint and make it
                // invisible. (Not allowed???)

                PowerPoint.Application oPowerPoint = new PowerPoint.Application();
                oPowerPoint.Visible = Office.MsoTriState.msoFalse;

                // Create a new Presentation.
                PowerPoint.Presentation oPre = oPowerPoint.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
                Debug.WriteLine("New presentation created");

                // Insert a new Slide with the picture name as title and a short explanation.
                string slideTitle = pictureListBox.Items[0].ToString();
                slideTitle = System.IO.Path.GetFileNameWithoutExtension(slideTitle);

                PowerPoint.Slide oSlide = oPre.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutText);
                oSlide.Shapes[1].TextFrame.TextRange.Text = "Slides about "+slideTitle;
                oSlide.Shapes[2].TextFrame.TextRange.Text = "Explanation about the build nature of the slide...";

                // Make the slide hidden, so it will not appear in the slide show
                oSlide.SlideShowTransition.Hidden = MsoTriState.msoTrue;

                // Insert a new blank Slide for the picture.
                oSlide = oPre.Slides.Add(2, PowerPoint.PpSlideLayout.ppLayoutBlank);
                Debug.WriteLine("Blank slide for images inserted");

                Boolean FirstImage = true;  // Used to handle special effect for very first picture
                foreach (string p in pictureListBox.Items)
                {
                    string imageFileName = p;

                    mcImageDetails imageDetails = new mcImageDetails(imageFileName);
                    float dx = imageDetails.dx;
                    float dy = imageDetails.dy;
                    double imageWidth = imageDetails.imageWidth;
                    double imageHeight = imageDetails.imageHeight;

                    PowerPoint.Shape myPic;
                    myPic = oSlide.Shapes.AddPicture(imageFileName, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue, 1, 1, -1, -1);

                    const float PixelPerPoint=(float)4/3;
                    double slideWidth = oPowerPoint.ActivePresentation.PageSetup.SlideWidth * PixelPerPoint;
                    double slideHeight = oPowerPoint.ActivePresentation.PageSetup.SlideHeight * PixelPerPoint;

                    // Scale to fit slide area
                    double xfactor = 1.0;
                    double ppp = dx / 96;

                    if (imageWidth> imageHeight) {
                          // X Scaling
                          xfactor=(slideWidth/imageWidth)*ppp;
                          myPic.ScaleWidth((float)xfactor, Office.MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle);
                    }
                    else
                    {
                          // Y Scaling
                          xfactor = (slideHeight / imageHeight)*ppp;
                          myPic.ScaleHeight((float)xfactor, Office.MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle);
                    }

                    Debug.WriteLine("Image w x h:" + imageWidth + ", " + imageHeight);
                    Debug.WriteLine("Slide  w x h: " + slideWidth + ", " + slideHeight);
                    Debug.WriteLine("Xfactor : " + xfactor);

                    myPic.Left = oPowerPoint.ActivePresentation.PageSetup.SlideWidth / 2 - myPic.Width / 2;
                    myPic.Top = oPowerPoint.ActivePresentation.PageSetup.SlideHeight / 2 - myPic.Height / 2;

                    // Add animation to the screenshot
                    // Remove the trigger for first image, so that it will appear automatically
                    PowerPoint.MsoAnimTriggerType thisTrigger;
                    thisTrigger=myTrigger;
                    if (FirstImage && FirstImageAppearWithPrevious) {
                        thisTrigger=PowerPoint.MsoAnimTriggerType.msoAnimTriggerWithPrevious;
                    }
                    PowerPoint.Effect myEffect;
                    myEffect = oSlide.TimeLine.MainSequence.AddEffect(myPic, myAnimation, trigger: myTrigger);

                    // Include timing etc
                    myEffect.Timing.Duration = myDuration;
                    myEffect.Timing.TriggerDelayTime = myDelay;

                    if (myTrigger == PowerPoint.MsoAnimTriggerType.msoAnimTriggerAfterPrevious) {
                        if (FirstImage) {
                            if (myAnimation != PowerPoint.MsoAnimEffect.msoAnimEffectAppear) {
                                myEffect.Timing.Duration=myFirstDuration;
                                myEffect.Timing.TriggerDelayTime=myFirstDelay;
                            }
                        }   else {
                                myEffect.Timing.Duration=myDuration;
                                myEffect.Timing.TriggerDelayTime=myDelay;
                        }
                    }

                    FirstImage=false;
                }

                // Save the presentation as a pptx file and close it.
                Debug.WriteLine("Save and close the presentation");

                string shortFileName = System.IO.Path.GetFileName(fileName);
                string saveDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                int decimalPoint = shortFileName.LastIndexOf(".");
                string fileType = shortFileName.Substring(decimalPoint);
                string sFileName = shortFileName.Substring(0, decimalPoint);
                string newFileName = saveDirectory + "\\" + sFileName + ".pptx";

                oPre.SaveAs(newFileName,
                    PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                    Office.MsoTriState.msoTriStateMixed);
                oPre.Close();

                // Quit the PowerPoint application.
                Debug.WriteLine("Quit the PowerPoint application");
                oPowerPoint.Quit();

            }
            catch (Exception ex)
            {
                Debug.WriteLine("Solution1.AutomatePowerPoint throws the error: {0}",
                    ex.Message);
            }
        }
Example #45
0
        static int Main(string[] args)
        {
            string usage = "Usage: PPTVideo.exe <infile> <outfile> <animation delay in sec. Float value> [-d]";

            try
            {
                if (args.Length < 2)
                {
                    Console.Out.WriteLine("Wrong argument number");
                    Console.In.ReadLine();
                    throw new ArgumentException("Wrong number of arguments.\n" + usage);
                }

                PowerPoint._Presentation objPres;
                objApp = new PowerPoint.Application();
                objPres = objApp.Presentations.Open(Path.GetFullPath(args[0]), MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);

                Slides slides = objPres.Slides;

                List<float> timeList = new List<float>();

                for (int s = 1; s <= slides.Count; s++)
                {

                    addSlideTimings(slides[s], timeList);
                }

                timeList.RemoveAt(timeList.Count - 1);

                printOut(timeList, args[1] + ".txt");

                objPres.SaveAs(Path.GetFullPath(args[1]), PowerPoint.PpSaveAsFileType.ppSaveAsWMV, MsoTriState.msoTriStateMixed);
                long len = 0;
                do
                {
                    System.Threading.Thread.Sleep(500);
                    try
                    {
                        FileInfo f = new FileInfo(args[1]);
                        len = f.Length;
                    }
                    catch
                    {
                        continue;
                    }
                } while (len == 0);

                objApp.Quit();

                Console.Out.WriteLine("Timing file created: " + args[1] + ".txt");

                //
                // Check if we want to delete the input file
                //
                if (args.Length > 3 && args[3] == "-d")
                    File.Delete(args[0]);

            }
            catch (Exception e)
            {
                System.Console.WriteLine("Error: " + e.Message);
                return 1;
            }
            // Console.In.ReadLine();
            return 0;
        }
Example #46
0
        //TODO: Image type needs to be more dynamically chosen...
        public static DeckModel OpenPPT(FileInfo file, BackgroundWorker worker, DoWorkEventArgs progress)
        {
            //Start the progress bar
            if (worker != null) {
                worker.ReportProgress(0, "  Initializing...");
            }

            //Make the default flat tree representation of the PPT
            //Try to detect if powerpoint is already running (powerpnt.exe)
            bool pptAlreadyRunning = false;
            Process[] processes = Process.GetProcesses();
            for (int i = 0; i < processes.Length; i++) {
                string currentProcess = processes[i].ProcessName.ToLower();
                if (currentProcess == "powerpnt") {
                    pptAlreadyRunning = true;
                    break;
                }
            }
            //Open PowerPoint + open file
            PowerPoint.Application pptapp = null;
            try {
                pptapp = new PowerPoint.Application();
            }
            catch (Exception e) {
                throw new PPTNotInstalledException("Failed to create PowerPoint Application.  See InnerException for details.", e);
            }

            PowerPoint._Presentation presentation;
            try {
                presentation = pptapp.Presentations.Open(file.FullName, Core.MsoTriState.msoTrue, Core.MsoTriState.msoFalse, Core.MsoTriState.msoFalse);
            }
            catch (Exception e) {
                throw new PPTFileOpenException("Failed to open PowerPoint file.  See InnerException for details.", e);
            }

            //Initialize the PPT Shape tag reader
            PPTPaneManagement.PPTPaneManager pptpm = new PPTPaneManagement.PPTPaneManager();
            //Create a new DeckModel

            Guid deckGuid = Guid.Empty;
            try {
                string g = presentation.Tags["WEBEXPORTGUID"];
                if (g == "") {
                    deckGuid = Guid.NewGuid();
                }
                else {
                    deckGuid = new Guid(g);
                }
            }
            catch {
                deckGuid = Guid.NewGuid();
            }

            DeckModel deck = new DeckModel(deckGuid, DeckDisposition.Empty, file.Name);

            //Initialize a temporary file collection that will be where slide images are exported to
            TempFileCollection tempFileCollection = new TempFileCollection();
            string dirpath = tempFileCollection.BasePath;
            if (!Directory.Exists(dirpath)) {
                Directory.CreateDirectory(dirpath);
            } else {
                Directory.Delete(dirpath, true);
                Directory.CreateDirectory(dirpath);
            }

            //Lock it
            using(Synchronizer.Lock(deck.SyncRoot)) {
                //Iterate over all slides
                for (int i = 1;  i <= presentation.Slides.Count; i++) {
                    if (progress != null && progress.Cancel)
                        break;

                    //Get the slide
                    PowerPoint._Slide currentSlide= presentation.Slides[i];

                    if (currentSlide.SlideShowTransition.Hidden == Core.MsoTriState.msoTrue)
                        continue;

                    SlideModel newSlideModel = CreateSlide(presentation.PageSetup, pptpm, deck, tempFileCollection, dirpath, currentSlide);

                    //Create a new Entry + reference SlideModel
                    TableOfContentsModel.Entry newEntry = new TableOfContentsModel.Entry(Guid.NewGuid(), deck.TableOfContents, newSlideModel);
                    //Lock the TOC
                    using(Synchronizer.Lock(deck.TableOfContents.SyncRoot)) {
                        //Add Entry to TOC
                        deck.TableOfContents.Entries.Add(newEntry);
                    }
                    //Increment the ProgressBarForm
                    if (worker != null) {
                        worker.ReportProgress((i * 100) / presentation.Slides.Count, "  Reading slide " + i + " of " + presentation.Slides.Count);
                    }
                }
            }
            //Close the presentation
            presentation.Close();
            presentation = null;
            //If PowerPoint was not open before, close PowerPoint
            if (!pptAlreadyRunning) {
                pptapp.Quit();
                pptapp = null;
            }
            GC.Collect();
            //Delete temp directory
            tempFileCollection.Delete();
            Directory.Delete(dirpath);

            if (worker != null)
                worker.ReportProgress(100, " Done!");

            //Return the deck
            if (progress != null)
                progress.Result = deck;
            return deck;
        }
Example #47
0
        public static void ConvertDocumentToSwf(string documentPath)
        {
            FileInfo originalFile = new FileInfo(documentPath);
            string outputPdfFolder = Path.Combine(REPO_ROOT, @"pdf");

            object outputPdfFile = Path.Combine(outputPdfFolder, originalFile.Name.Replace(originalFile.Extension, ".pdf"));

            // C# doesn't have optional arguments so we'll need a dummy value
            object oMissing = System.Reflection.Missing.Value;

            if (originalFile.Extension == ".doc" || originalFile.Extension == ".docx")
            {
                // 将word转成pdf,存放在pdf目录下
                // Create a new Microsoft Word application object
                msWord.Application word = new msWord.Application();

                word.Visible = false;
                word.ScreenUpdating = false;

                Object filename = (Object)originalFile.FullName;

                // Use the dummy value as a placeholder for optional arguments
                msWord.Document doc = word.Documents.Open(ref filename, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                doc.Activate();

                object fileFormat = msWord.WdSaveFormat.wdFormatPDF;

                // Save document into PDF Format
                doc.SaveAs(ref outputPdfFile,
                    ref fileFormat, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                // Close the Word document, but leave the Word application open.
                // doc has to be cast to type _Document so that it will find the
                // correct Close method.
                object saveChanges = msWord.WdSaveOptions.wdDoNotSaveChanges;
                ((msWord._Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
                doc = null;

                // word has to be cast to type _Application so that it will find
                // the correct Quit method.
                ((msWord._Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
                word = null;
            }
            else if (originalFile.Extension == ".xls" || originalFile.Extension == ".xlsx")
            {
                msExcel.Application excel = new msExcel.Application();
                excel.Visible = false;
                excel.ScreenUpdating = false;
                excel.DisplayAlerts = false;

                string filename = originalFile.FullName;

                msExcel.Workbook wbk = excel.Workbooks.Open(filename, oMissing,
                    oMissing, oMissing, oMissing, oMissing, oMissing,
                    oMissing, oMissing, oMissing, oMissing, oMissing,
                    oMissing, oMissing, oMissing);
                wbk.Activate();

                msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;

                // Save document into PDF Format
                wbk.ExportAsFixedFormat(fileFormat, outputPdfFile,
                    oMissing, oMissing, oMissing,
                    oMissing, oMissing, oMissing,
                    oMissing);

                object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges;
                ((msExcel._Workbook)wbk).Close(saveChanges, oMissing, oMissing);
                wbk = null;

                ((msExcel._Application)excel).Quit();
                excel = null;
            }
            else if (originalFile.Extension == ".ppt" || originalFile.Extension == ".pptx")
            {
                msPPT.Application app = new msPPT.Application();
                string sourcePptx = originalFile.FullName;
                msPPT.Presentation pptx = app.Presentations.Open(
                    sourcePptx, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
                pptx.SaveAs((string)outputPdfFile, msPPT.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
                app.Quit();
            }

            // 第二步,将pdf转成swf,存放在swf目录下
            ConvertPdfToSwf((string)outputPdfFile);
        }
Example #48
0
    static void Main(string[] args)
    {
        Boolean bl = initialize();

        while (!bl)
        {
            Console.WriteLine("--> Press Any Key to Fresh.");
            ConsoleKeyInfo input = Console.ReadKey();
            if (!string.IsNullOrEmpty(input.KeyChar.ToString()))
            {
                Console.Clear();
                bl = initialize();
            }
        }

        DataSet structure = new DataSet();

        IEnumerable<string> excelFiles;
        IEnumerable<string> tempo;

        getLists(out excelFiles, out tempo);

        List<string> todoList = new List<string>();
        foreach (string s in excelFiles)
        {
            if (!tempo.Contains<string>(Path.GetFileName(s)))
            {
                todoList.Add(s);
            }
        }

        while(todoList.Count<string>() == 0)
        {
            Console.WriteLine("--> No new excel files, Press any key to fresh.");
            Console.ReadKey();
            Console.Clear();
            initialize();
            getLists(out excelFiles, out tempo);
            foreach (string s in excelFiles)
            {
                if (!tempo.Contains<string>(Path.GetFileName(s)))
                {
                    todoList.Add(s);
                }
            }
        }
        PowerPoint.Application app = new PowerPoint.Application();
        PowerPoint.Presentation ppt = SlidesEditer.openPPT(projectSlides, app);
        /*
        try
        {
            ppt.Windows._Index(0);
        }
        catch
        {
            ppt.Close();
            app.Quit();
            GC.Collect();
        }
        */
        if (todoList.Count<string>() != 0)
        {
            Console.WriteLine("-->  _(:3 」∠)_ ..");
            foreach (string s in todoList)
            {
                Console.WriteLine("--> Reading {0}:", Path.GetFileName(s));
                DataSet sheets = ReadExcel(s, gameConfig);
                if (tempo.Count<string>() != 0)
                {
                    structureFile = projectFolder + "\\SlidesMap.xlsx";
                    structure = ExcelReader.getAllSheets(structureFile);
                    for (int i = 0; i < structure.Tables.Count; i++)
                    {
                        Functions.regulateData(structure.Tables[i], structure.Tables[i].Columns.Count);
                    }
                }
                makeStructure(ppt, sheets, structure);
                using (StreamWriter sw = File.AppendText(tempoFile))
                {
                    sw.WriteLine(Path.GetFileName(s));
                    sw.Close();
                }
            }

        }
        Console.WriteLine("--> Done.");
        Console.WriteLine("--> Press Enter to Exit.");
        ppt.Close();
        app.Quit();
        GC.Collect();
        Console.SetWindowPosition(0, 0);
        Console.ReadKey();
    }
Example #49
0
        public static string GetVideoFromPpt(string _filename)
        {
            filename = _filename;

            string rv = Path.GetTempPath() + "videoFromppt.wmv";

            Microsoft.Office.Interop.PowerPoint.Application objApp;
            Microsoft.Office.Interop.PowerPoint.Presentation objPres;
            objApp = new Microsoft.Office.Interop.PowerPoint.Application();
            //objApp.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
            objApp.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMinimized;

            objPres = objApp.Presentations.Open(filename, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
            Console.WriteLine("File name: " + filename);
            try
            {
                objPres.SaveAs(rv, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV, MsoTriState.msoTrue);
                // Wait for creation of video file
                while (objApp.ActivePresentation.CreateVideoStatus == Microsoft.Office.Interop.PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusInProgress || objApp.ActivePresentation.CreateVideoStatus == Microsoft.Office.Interop.PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusQueued)
                {
                    //Application.DoEvents();
                    System.Threading.Thread.Sleep(500);
                }

                //txtStat.Text = "Done";
                objPres.Close();
                objApp.Quit();
                // Release COM Objects
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objPres);
                objPres = null;
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objApp);
                objApp = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return rv;

            /*
            var app = new Microsoft.Office.Interop.PowerPoint.Application();
            var presentation = app.Presentations.Open(filename, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

            var wmvfile = Guid.NewGuid().ToString() + ".wmv";
            var fullpath = filename;

            try
            {
                presentation.CreateVideo(wmvfile);
                presentation.SaveCopyAs(fullpath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV, MsoTriState.msoCTrue);
            }
            catch (COMException)
            {
                wmvfile = null;
            }
            finally
            {
                app.Quit();
            }

            return wmvfile;
            */
        }
Example #50
0
 private static void ShowPresentation()
 {
     string strTemplate = @"C:\Program Files (x86)\Microsoft Office\Templates\1042\ClassicPhotoAlbum.potx";
     string strPic = @"C:\Users\Administrator\Documents\Cropper Captures\CropperCapture[1].bmp";
     bool bAssistantOn;
     Application objApp;
     Presentations objPresSet;
     _Presentation objPres;
     Slides objSlides;
     _Slide objSlide;
     TextRange objTextRng;
     PowerPoint.Shapes objShapes;
     PowerPoint.Shape objShape;
     SlideShowWindows objSSWs;
     SlideShowTransition objSST;
     SlideShowSettings objSSS;
     SlideRange objSldRng;
     Graph.Chart objChart;
     //Create a new presentation based on a template.
     objApp = new PowerPoint.Application();
     objApp.Visible = MsoTriState.msoTrue;
     objPresSet = objApp.Presentations;
     objPres = objPresSet.Open(strTemplate, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
     objSlides = objPres.Slides;
     //Build Slide #1:
     //Add text to the slide, change the font and insert/position a
     //picture on the first slide.
     objSlide = objSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
     objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
     objTextRng.Text = "My Sample Presentation";
     objTextRng.Font.Name = "Comic Sans MS";
     objTextRng.Font.Size = 48;
     objSlide.Shapes.AddPicture(strPic, MsoTriState.msoFalse, MsoTriState.msoTrue, 150, 150, 500, 350);
     //Build Slide #2:
     //Add text to the slide title, format the text. Also add a chart to the
     //slide and change the chart type to a 3D pie chart.
     objSlide = objSlides.Add(2, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
     objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
     objTextRng.Text = "My Chart";
     objTextRng.Font.Name = "Comic Sans MS";
     objTextRng.Font.Size = 48;
     objChart = (Graph.Chart)objSlide.Shapes.AddOLEObject(150, 150, 480, 320, "MSGraph.Chart.8", "", MsoTriState.msoFalse, "", 0, "", MsoTriState.msoFalse).OLEFormat.Object;
     objChart.ChartType = Graph.XlChartType.xl3DPie;
     objChart.Legend.Position = Graph.XlLegendPosition.xlLegendPositionBottom;
     objChart.HasTitle = true;
     objChart.ChartTitle.Text = "Here it is...";
     //Build Slide #3:
     //Change the background color of this slide only. Add a text effect to the slide
     //and apply various color schemes and shadows to the text effect.
     objSlide = objSlides.Add(3, PowerPoint.PpSlideLayout.ppLayoutBlank);
     objSlide.FollowMasterBackground = MsoTriState.msoFalse;
     objShapes = objSlide.Shapes;
     objShape = objShapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect27, "The End", "Impact", 96, MsoTriState.msoFalse, MsoTriState.msoFalse, 230, 200);
     //Modify the slide show transition settings for all 3 slides in
     //the presentation.
     int[] SlideIdx = new int[3];
     for (int i = 0; i < 3; i++)
         SlideIdx[i] = i + 1;
     objSldRng = objSlides.Range(SlideIdx);
     objSST = objSldRng.SlideShowTransition;
     objSST.AdvanceOnTime = MsoTriState.msoTrue;
     objSST.AdvanceTime = 3;
     objSST.EntryEffect = PowerPoint.PpEntryEffect.ppEffectBoxOut;
     //Prevent Office Assistant from displaying alert messages:
     bAssistantOn = objApp.Assistant.On;
     objApp.Assistant.On = false;
     //Run the Slide show from slides 1 thru 3.
     objSSS = objPres.SlideShowSettings;
     objSSS.StartingSlide = 1;
     objSSS.EndingSlide = 3;
     objSSS.Run();
     //Wait for the slide show to end.
     objSSWs = objApp.SlideShowWindows;
     while (objSSWs.Count >= 1)
         System.Threading.Thread.Sleep(100);
     //Reenable Office Assisant, if it was on:
     if (bAssistantOn)
     {
         objApp.Assistant.On = true;
         objApp.Assistant.Visible = false;
     }
     //Close the presentation without saving changes and quit PowerPoint.
     objPres.Close();
     objApp.Quit();
 }
        private static OfficeToXpsConversionResult ConvertFromPowerPoint(string sourceFilePath, ref string resultFilePath)
        {
            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.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, "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();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (Exception exc)
            {
                return new OfficeToXpsConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "PowerPoint", exc);
            }

            resultFilePath = pExportFilePath;

            return new OfficeToXpsConversionResult(ConversionResult.OK, pExportFilePath);
        }
Example #52
0
        private static string ParsePowerPointToText(string inputFile, string outputFile)
        {
            var PowerPoint_App = new PowerPoint.Application();
            try
            {
                var multi_presentations = PowerPoint_App.Presentations;
                var presentation = multi_presentations.Open(inputFile);
                var presentation_text = "";
                for (var i = 0; i < presentation.Slides.Count; i++)
                {
                    presentation_text = (from PowerPoint.Shape shape in presentation.Slides[i + 1].Shapes where shape.HasTextFrame == MsoTriState.msoTrue where shape.TextFrame.HasText == MsoTriState.msoTrue select shape.TextFrame.TextRange into textRange select textRange.Text).Aggregate(presentation_text, (current, text) => current + (text + " "));
                }

                if (string.IsNullOrEmpty(outputFile))
                    return presentation_text;

                using (var sw = new StreamWriter(outputFile))
                {
                    sw.WriteLine(presentation_text);
                }
                Console.WriteLine(presentation_text);
            }
            finally
            {
                PowerPoint_App.Quit();
                Marshal.FinalReleaseComObject(PowerPoint_App);
                GC.Collect();
                KillProcess();
            }
            return string.Empty;
        }
Example #53
0
// 
//         private void OpenPPT()
//         {
//             //Create an instance of PowerPoint.
//             oPPT = new Microsoft.Office.Interop.PowerPoint.Application();
//             // Show PowerPoint to the user.
//             oPPT.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
//             objPresSet = oPPT.Presentations;
// 
//             //open the presentation
//             objPres = objPresSet.Open(Path, MsoTriState.msoFalse,
//             MsoTriState.msoTrue, MsoTriState.msoTrue);
// 
//             objPres.SlideShowSettings.ShowPresenterView = MsoTriState.msoFalse;
//             System.Diagnostics.Debug.WriteLine(objPres.SlideShowSettings.ShowWithAnimation);
//             objPres.SlideShowSettings.Run();
// 
//             oSlideShowView = objPres.SlideShowWindow.View;
//         }

        private void ReadPPTfile(string path)
        {
            Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
            PPT = app.Presentations.Open(path, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
            app.Quit();
        }
Example #54
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 #55
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();
     }
 }
Example #56
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                showUsage = true;
            }

            foreach (string arg in args)
            {
                if ("--help".Equals(arg))
                {
                    showUsage = true;
                }

                if ("--version".Equals(arg))
                {
                    showVersion = true;
                }
            }

            if (showUsage)
            {
                Console.WriteLine(typeof(Ppt2Pdf).Name + " input_ppt output_pdf");
                Console.WriteLine("\t--help Show usage.");
                //Console.WriteLine("\t-v verbose mode.");
                Console.WriteLine("\t--version Show version.");
                System.Environment.Exit(0);
            }
            if (showVersion)
            {
                System.Version ppt2pdfVersion = Assembly.GetExecutingAssembly().GetName().Version;
                System.Version excelVersion = Assembly.GetAssembly(typeof(Microsoft.Office.Interop.PowerPoint.Application)).GetName().Version;
                Console.WriteLine(typeof(Ppt2Pdf).Name + " " + ppt2pdfVersion + " - Microsoft PowerPoint " + excelVersion);

                System.Environment.Exit(0);
            }
            else
            {
                try
                {

                    string originalPptFile = Path.GetFullPath(args[0]);
                    string convertedPdfFile = Path.GetFullPath(args[1]);

                    if (verbose)
                    {
                        Console.WriteLine("Creating PowerPoint application");
                    }

                    var pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();

                    if (verbose)
                    {
                        Console.WriteLine(string.Format("PowerPoint application, version: {0} created",
                            pptApplication.Version
                            )
                        );
                    }

                    object missing = System.Reflection.Missing.Value;

                    object confirmConversions = missing;
                    object readOnly = true;
                    object addToRecentFiles = missing;
                    object passwordDocument = missing;
                    object passwordTemplate = missing;
                    object revert = missing;
                    object writePasswordDocument = missing;
                    object writePasswordTemplate = missing;
                    object format = missing;
                    object encoding = missing;
                    object visible = missing;
                    object openAndRepair = missing;
                    object documentDirection = missing;
                    object noEncodingDialog = missing;
                    object xmlTranform = missing;

                    if (verbose)
                    {
                        Console.WriteLine("Opening PPT file " + originalPptFile);
                    }

                    var presentation = pptApplication.Presentations.Open(
                        originalPptFile,
                        MsoTriState.msoTrue,
                        MsoTriState.msoFalse,
                        MsoTriState.msoFalse
                    );

                    if (verbose)
                    {
                        Console.WriteLine("Saving PDF file " + convertedPdfFile);
                    }

                    presentation.ExportAsFixedFormat(
                        convertedPdfFile,
                        PpFixedFormatType.ppFixedFormatTypePDF,
                        PpFixedFormatIntent.ppFixedFormatIntentScreen,
                        MsoTriState.msoFalse,
                        PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                        PpPrintOutputType.ppPrintOutputSlides,
                        MsoTriState.msoFalse,
                        null,
                        PpPrintRangeType.ppPrintAll,
                        "",
                        false,
                        true,
                        true,
                        true,
                        false,
                        Type.Missing
                        );

                    object saveChanges = false;

                    if (verbose)
                    {
                        Console.WriteLine("Closing presentation");
                    }
                    presentation.Close();

                    if (verbose)
                    {
                        Console.WriteLine("Closing PowerPoint application");
                    }
                    pptApplication.Quit();

                    pptApplication = null;
                    presentation = null;
                }
                catch (Exception ex)
                {
                    if (verbose)
                    {
                        Console.Error.WriteLine("ERROR - " + ex.Message);
                    }

                    System.Environment.Exit(1);
                }
                finally
                {
                    System.GC.WaitForPendingFinalizers();
                    System.GC.Collect();
                }
            }
        }
 /// <summary>
 /// 获取PPT内容
 /// </summary>
 /// <param name="filePath"></param>
 /// <returns></returns>
 public static List<string> GetPPTContent(string filePath)
 {
     path = filePath;
     List<string> allContent = new List<string>();
     string content = string.Empty;
     var ppt = new PPT.Application();
     var doc = ppt.Presentations.Open(path.ToString(),
                Microsoft.Office.Core.MsoTriState.msoCTrue,
                Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
     int Slides = doc.Slides.Count;
     foreach (PPT.Slide slide in doc.Slides)
     {
         foreach (PPT.Shape shape in slide.Shapes)
         {
             if (content.Length <= 300)
                 content += shape.TextFrame.TextRange.Text;
             else
             {
                 allContent.Add(content);
                 content = "";
                 content += shape.TextFrame.TextRange.Text;
             }
         }
         if (allContent.Count == 0)
             allContent.Add(content);
     }
     ppt.Quit();
     return allContent;
 }
		/// <summary>
		/// Converts PowerPoint presentation to images where is slide is given by one image
		/// </summary>
		/// <param name="inputFile"></param>
		/// <param name="outputDir"></param>
		/// <returns>the directory of the images</returns>
		protected string ConvertPowerPointToImages(string inputFile, string outputDir)
		{
			// temp directory for images
			string imgsPath = Utility.CreateDirectory(Utility.NewFolderPath(outputDir, "imgs"));

			//Get the presentation
			var powerPoint = new Microsoft.Office.Interop.PowerPoint.Application();
			var presentation = powerPoint.Presentations.Open(inputFile);

			// Save each slide as picture
			try
			{
				presentation.SaveAs(imgsPath, PpSaveAsFileType.ppSaveAsPNG);
			}
			catch (COMException e)
			{
                Console.WriteLine("Presenation doesn't have any slide.");
                Console.WriteLine(e.Message);
				return String.Empty;
			}
			finally
			{
				// Close power point application
				presentation.Close();
				powerPoint.Quit();
			}
			return imgsPath;
		}
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            // 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)
                    {
                        app = new Microsoft.Office.Interop.PowerPoint.Application();
                        running = false;
                    }
                    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);
                    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 #60
0
        public Boolean toPowerPoint(string url)
        {
            string[] str = Regex.Split(smartStr, "\r\n");

            string titleTmp = "";
            string comment = "Smart Thai";
            string Arial = "Arial";
            string Tahoma = "Tahoma";

            powerPoint.Application objApp = new powerPoint.Application();
            powerPoint.Slides objSlides;
            powerPoint._Slide objSlide;
            powerPoint.TextRange objTextRng;

            // Create the Presentation File
            powerPoint.Presentation objPresSet = objApp.Presentations.Add(MsoTriState.msoTrue);

            powerPoint.CustomLayout customLayout = objPresSet.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutTitle];

            // Create new Slide
            objSlides = objPresSet.Slides;
            objSlide = objSlides.AddSlide(1, customLayout);
            objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;

            // Add title
            objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
            objTextRng.Text = str[0];
            objTextRng.Font.Name = Tahoma;
            objTextRng.Font.Size = 72;
            titleTmp = str[0];
            if (str[1].IndexOf("http") != -1)
            {
                new WebClient().DownloadFile(str[1].Trim(), "./tmp.png");
                objSlide.Shapes.AddPicture(Application.StartupPath + "/tmp.png", MsoTriState.msoFalse, MsoTriState.msoTrue,
                    260, 300, 200, 200);
            }

            customLayout = objPresSet.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
            int tab, slideCount = 1, lineCount = 0;
            bool specialText = false, define = true;
            int tabSpecial = 0;
            int picInSlide = 0;

            objSlide = objSlides.AddSlide(++slideCount, customLayout);
            objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
            objTextRng.Text = str[0];
            objTextRng.Font.Name = Tahoma;
            objTextRng.Font.Size = 40;
            objTextRng.ParagraphFormat.Alignment = powerPoint.PpParagraphAlignment.ppAlignLeft;
            objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;
            for (int i = 2; i < str.Length - 1; i++)
            {
                tab = 0;
                foreach (char ch in str[i])
                {
                    if (ch == '\t')
                        tab++;
                    else
                        break;
                }
                if (define)
                {
                    if (i + 1 < str.Length - 1)
                    {
                        int nextTab = 0;
                        foreach (char ch in str[i + 1])
                        {
                            if (ch == '\t')
                                nextTab++;
                            else
                                break;
                        }
                        if (nextTab == tab)
                        {
                            if (lineCount > 5)
                            {
                                objSlide = objSlides.AddSlide(++slideCount, customLayout);
                                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                                objTextRng.Text = titleTmp + " (ต่อ)";
                                objTextRng.Font.Name = Tahoma;
                                objTextRng.Font.Size = 40;
                                objTextRng.ParagraphFormat.Alignment = powerPoint.PpParagraphAlignment.ppAlignLeft;
                                objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;
                                lineCount = 0;
                            }
                            objTextRng = objSlide.Shapes[2].TextFrame.TextRange;
                            if (lineCount != 0)
                                objTextRng.Text += "\r\n";
                            objTextRng.Text += str[i].Trim();
                            objTextRng.Font.Name = Arial;
                            objTextRng.Font.Size = 28;
                            lineCount++;
                        }
                        else
                        {
                            objSlide = objSlides.AddSlide(++slideCount, customLayout);

                            objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                            objTextRng.Text = str[i].Trim();
                            objTextRng.Font.Name = Tahoma;
                            objTextRng.Font.Size = 40;
                            objTextRng.ParagraphFormat.Alignment = powerPoint.PpParagraphAlignment.ppAlignLeft;
                            objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;
                            lineCount = 0;
                            titleTmp = str[i].Trim();
                            define = false;
                        }
                    }
                    else
                    {
                        objTextRng = objSlide.Shapes[2].TextFrame.TextRange;
                        if (lineCount != 0)
                            objTextRng.Text += "\r\n";
                        objTextRng.Text += str[i].Trim();
                        objTextRng.Font.Name = Arial;
                        objTextRng.Font.Size = 28;
                        lineCount++;
                    }
                }
                else
                {
                    if (str[i].Trim() == "-Extrack Bullet-" || str[i].Trim() == "-Extrack Paragraph-")
                    {
                        specialText = true;
                        tabSpecial = tab;
                        continue;
                    }
                    if (specialText && tab == tabSpecial)
                        continue;
                    else
                        specialText = false;
                    if (tab == 1)
                    {
                        lineCount = 0;
                        objSlide = objSlides.AddSlide(++slideCount, customLayout);

                        objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                        objTextRng.Text = str[i].Trim();
                        objTextRng.Font.Name = Tahoma;
                        objTextRng.Font.Size = 40;
                        objTextRng.ParagraphFormat.Alignment = powerPoint.PpParagraphAlignment.ppAlignLeft;
                        objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;
                        picInSlide = 0;
                        titleTmp = str[i].Trim();
                    }
                    else
                    {
                        if (lineCount > 5 || picInSlide == 2)
                        {
                            objSlide = objSlides.AddSlide(++slideCount, customLayout);

                            objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                            objTextRng.Text = titleTmp + " (ต่อ)";
                            objTextRng.Font.Name = Tahoma;
                            objTextRng.Font.Size = 40;
                            objTextRng.ParagraphFormat.Alignment = powerPoint.PpParagraphAlignment.ppAlignLeft;
                            objSlide.NotesPage.Shapes[2].TextFrame.TextRange.Text = comment;
                            lineCount = 0;
                            picInSlide = 0;
                        }
                        string link = "", text = "";
                        if (str[i].IndexOf("[SMARTTHAI]") != -1)
                        {
                            text = Regex.Split(str[i], @"\[SMARTTHAI\]")[0].Trim();
                            link = Regex.Split(str[i], @"\[SMARTTHAI\]")[1];
                            objTextRng = objSlide.Shapes[2].TextFrame.TextRange;
                            if (lineCount != 0)
                                objTextRng.Text += "\r\n";
                            objTextRng.Text += text;
                            objTextRng.Font.Name = Arial;
                            objTextRng.Font.Size = 28;
                            if (picInSlide < 2)
                            {
                                new WebClient().DownloadFile(link, "./tmp.png");
                                objSlide.Shapes.AddPicture(Application.StartupPath + "/tmp.png", MsoTriState.msoFalse, MsoTriState.msoTrue, 360, (lineCount * 45) + 130, 160, 160);
                                picInSlide++;
                            }
                            lineCount += 3;
                            objTextRng.Text += "\r\n\r\n\r\n";
                        }
                        else
                        {
                            objTextRng = objSlide.Shapes[2].TextFrame.TextRange;
                            if (lineCount != 0)
                                objTextRng.Text += "\r\n";
                            objTextRng.Text += str[i].Trim();
                            objTextRng.Font.Name = Arial;
                            objTextRng.Font.Size = 28;
                        }

                        lineCount++;
                    }
                }
            }
            try
            {
                string[] a = url.Split('.');
                if (a[1] == "pdf")
                {
                    objPresSet.SaveAs(url, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
                    objPresSet.Close();
                    objApp.Quit();
                    File.Delete(Application.StartupPath + "/tmp.png");
                }
                else
                {
                    objPresSet.SaveAs(url, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }