Example #1
0
        /// <summary>
        /// Converts a PowerPoint document to PDF
        /// </summary>
        /// <param name="inputFile">The PowerPoint input file</param>
        /// <param name="outputFile">The PDF output file</param>
        /// <returns></returns>
        internal static void Convert(string inputFile, string outputFile)
        {
            DeleteAutoRecoveryFiles();

            PowerPointInterop.ApplicationClass powerPoint   = null;
            PowerPointInterop.Presentation     presentation = null;

            try
            {
                powerPoint = new PowerPointInterop.ApplicationClass
                {
                    DisplayAlerts = PowerPointInterop.PpAlertLevel.ppAlertsNone,
                    DisplayDocumentInformationPanel = false,
                    AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable
                };

                presentation = Open(powerPoint, inputFile, false);
                presentation.ExportAsFixedFormat(outputFile, PowerPointInterop.PpFixedFormatType.ppFixedFormatTypePDF);
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Saved = MsoTriState.msoFalse;
                    presentation.Close();
                    Marshal.ReleaseComObject(presentation);
                }

                if (powerPoint != null)
                {
                    powerPoint.Quit();
                    Marshal.ReleaseComObject(powerPoint);
                }
            }
        }
Example #2
0
 public PPT(string fileName)
 {
     _fileName     = fileName;
     _application  = new MSPowerPoint.ApplicationClass();
     _presentation = _application.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
     _tempFileName = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), string.Format("{0}.png", Guid.NewGuid().ToString("N")));
 }
Example #3
0
        /// <summary>
        /// 打开PPT文档并播放显示。
        /// </summary>
        /// <param name="filePath">PPT文件路径</param>
        public void PPTOpen(string filePath)
        {
            try
            {
                CurrentFile = filePath;
                Thread.Sleep(100);
                //防止连续打开多个PPT程序.
                if (this.objApp != null)
                {
                    this.objApp.Quit();
                    this.objApp = null;
                }
                Thread.Sleep(100);

                objApp = new POWERPOINT.ApplicationClass();
                //以非只读方式打开,方便操作结束后保存.
                objPresSet = objApp.Presentations.Open(filePath, MsoTriState.msoCTrue, MsoTriState.msoCTrue, MsoTriState.msoFalse);
                //Prevent Office Assistant from displaying alert messages:
                //bAssistantOn = objApp.Assistant.On;
                //objApp.Assistant.On = false;
                objSSS = this.objPresSet.SlideShowSettings;
                objSSS.Run();
                currentPage = 1;
                pageCount   = objPresSet.Slides.Count;
                //this.objPresSet.SlideShowWindow.View.GotoSlide(2, OFFICECORE.MsoTriState.msoFalse);
            }
            catch (Exception)
            {
                //this.objApp.Quit();
                //Thread.Sleep(1000);
                //PPTOpen(filePath);
            }
        }
Example #4
0
        /// <summary>
        /// Check and duplicate the single slide ppt
        /// Copy to the destination
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="target"></param>
        public void CheckCopySlides(string origin, string target)
        {
            POWERPOINT.ApplicationClass ppt = new POWERPOINT.ApplicationClass();
            POWERPOINT.Presentation pres = ppt.Presentations.Open(
                    origin,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoFalse);

            if (pres.Slides.Count == 1)
            {
                pres.SaveAs(
                    target,
                    POWERPOINT.PpSaveAsFileType.ppSaveAsDefault,
                    Microsoft.Office.Core.MsoTriState.msoCTrue);

                pres.Slides[1].Copy();
                pres.Slides.Paste(2);
                pres.Save();
            }
            else
            {
                System.IO.FileInfo file = new System.IO.FileInfo(origin);
                file.CopyTo(target, true);
            }

            pres.Close();
            ppt.Quit();
        }
Example #5
0
    public void exportPPT()
    {
        string path;                           //文件路径变量

        PPT.Application pptApp;                //Excel应用程序变量

        PPT.Presentation pptDoc;               //Excel文档变量

        path = @"D:\MyPPT.ppt";                //路径

        pptApp = new PPT.ApplicationClass();   //初始化

        //如果已存在,则删除

        if (File.Exists((string)path))

        {
            File.Delete((string)path);
        }

        //由于使用的是COM库,因此有许多变量需要用Nothing代替

        Object Nothing = Missing.Value;

        pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);

        pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutBlank);

        string pic = @"D:\1.png";

        foreach (PPT.Slide slide in pptDoc.Slides)

        {
            slide.Shapes.AddPicture(pic, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 150, 300, 200);
        }



        //WdSaveFormat为PPTs文档的保存格式

        PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;

        //将 pptDoc文档对象的内容保存为XLSX文档

        pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);

        //关闭pptDoc文档对象

        pptDoc.Close();

        //关闭pptApp组件对象

        pptApp.Quit();

        Console.WriteLine(path + " 创建完毕!");

        // Console.ReadLine();
    }
Example #6
0
 /// <summary>
 /// 关闭PPT
 /// </summary>
 public void PPTClose()
 {
     CurrentFile = string.Empty;
     if (objApp != null)
     {
         this.objApp.Quit();
         this.objApp = null;
     }
 }
Example #7
0
        /// <summary>
        ///     Stops PowerPoint
        /// </summary>
        private void StopPowerPoint()
        {
            if (IsPowerPointRunning)
            {
                Logger.WriteToLog("Stopping PowerPoint");

                try
                {
                    _powerPoint.Quit();
                }
                catch (Exception exception)
                {
                    Logger.WriteToLog($"PowerPoint did not shutdown gracefully, exception: {ExceptionHelpers.GetInnerException(exception)}");
                }

                var counter = 0;

                // Give PowerPoint 2 seconds to close
                while (counter < 200)
                {
                    if (!IsPowerPointRunning)
                    {
                        break;
                    }
                    counter++;
                    Thread.Sleep(10);
                }

                if (IsPowerPointRunning)
                {
                    Logger.WriteToLog(
                        $"PowerPoint did not shutdown gracefully in 2 seconds ... killing it on process id {_powerPointProcess.Id}");
                    _powerPointProcess.Kill();
                    Logger.WriteToLog("PowerPoint process killed");
                }
                else
                {
                    Logger.WriteToLog("PowerPoint stopped");
                }
            }

            if (_powerPoint != null)
            {
                Marshal.ReleaseComObject(_powerPoint);
                _powerPoint = null;
            }

            _powerPointProcess = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Example #8
0
        private static void ConvertPPTToDoc(Options options)
        {
            PPT.ApplicationClass pptApp = new PPT.ApplicationClass();
            pptApp.DisplayAlerts = PPT.PpAlertLevel.ppAlertsNone;

            // make copy so we don't change the original
            string tempPptFilePath = System.IO.Path.Combine(System.IO.Path.GetTempFileName());
            System.IO.File.Copy(options.InPath, tempPptFilePath, true);

            PPT.Presentation pptPresentation = pptApp.Presentations.Open(new FileInfo(tempPptFilePath).FullName, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse);

            DOC.Application docApp = new DOC.Application();
            var doc = docApp.Documents.Add();

            Console.WriteLine("Converting powerpoint to word");
            ProgressBar progress = new ProgressBar();

            try
            {
                string currentTitle = "";
                string currentSubTitle = "";

                for (int slideNr = 1; slideNr <= pptPresentation.Slides.Count; slideNr++)
                {
                    progress.Report(slideNr / (float)pptPresentation.Slides.Count, "Slide " + slideNr + "/" + pptPresentation.Slides.Count);
                    CopySlide(pptPresentation, doc, options, ref currentTitle, ref currentSubTitle, slideNr);
                }
            }
            finally
            {
                pptPresentation.Close();

                if (System.IO.File.Exists(tempPptFilePath))
                    System.IO.File.Delete(tempPptFilePath);
            }
            //docApp.Visible = true;
            doc.SaveAs(new FileInfo(options.Outpath).FullName);
            doc.Close();

            progress.Dispose();

            Console.WriteLine("Conversion complete, word file written to " + new FileInfo(options.Outpath).FullName);

            try
            {
                docApp.Quit();
                pptApp.Quit();
            }
            catch (Exception)
            {
            }
        }
        private static void createPresentation(OutlineParagraph outlineParagraph, string targetFile, Action <string> fileCreated, Logger logger)
        {
            var pptApplication = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();

            var currentDirectory = System.IO.Directory.GetCurrentDirectory();
            var targetName       = System.IO.Path.GetFileNameWithoutExtension(targetFile);
            //var pptFileTargetPath = System.IO.Path.Combine(currentDirectory, "PPT", targetName, outlineParagraph.Text.Trim() + ".ppt");
            var odpOutputfile = Path.Combine(currentDirectory, "ODP", targetName, outlineParagraph.Text.Trim() + ".odp");

            if (System.IO.File.Exists(odpOutputfile))
            {
                logger.Log($"{odpOutputfile} already exists to recreate it delete the existing version.");
                return;
            }

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

            var filePath = typeof(Generator).Assembly.Location;
            var path     = System.IO.Path.GetDirectoryName(filePath);


            pptPresentation.ApplyTheme(path + @"\BibleStudy.thmx");
            createPresentation(outlineParagraph, pptPresentation, fileCreated);

            //try
            //{
            //    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(pptFileTargetPath));

            //    pptPresentation.SaveAs(pptFileTargetPath);
            //    fileCreated(pptFileTargetPath);
            //}
            //catch(Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //    throw;
            //}

            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(odpOutputfile));

            pptPresentation.SaveAs(odpOutputfile, PpSaveAsFileType.ppSaveAsOpenDocumentPresentation);
            fileCreated(odpOutputfile);
            pptPresentation.Close();
            pptApplication.Quit();
        }
Example #10
0
        public static void Convert(String file, String safeFile)
        {
            Powerpoint.Application  PP;
            Powerpoint.Presentation Presentation;
            PP             = new Powerpoint.ApplicationClass();
            PP.Visible     = MsoTriState.msoTrue;
            PP.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMinimized;
            var presentations = PP.Presentations;

            Presentation = presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
            // Voor elke slide, exporteren
            String exportSlidesPath = Path.Combine(Properties.Settings.Default.CacheDir, @"presentatienaam1\slides");

            // Kijk of de directory bestaat
            if (!Directory.Exists(exportSlidesPath))
            {
                Directory.CreateDirectory(exportSlidesPath);
            }
            // Kijk of er al bestanden in de directory staan
            // Zo ja: verwijderen
            String[] files = Directory.GetFiles(exportSlidesPath, "*.png");
            if (files.Length > 0)
            {
                foreach (string fileName in files)
                {
                    File.Delete(Path.Combine(exportSlidesPath, fileName));
                }
            }
            // Elke slide exporteren
            var slides = Presentation.Slides;

            foreach (Slide slide in slides)
            {
                slide.Export(Path.Combine(exportSlidesPath, "slide_" + slide.SlideIndex + ".png"), "PNG", 1024, 768);
                Marshal.ReleaseComObject(slide);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Marshal.ReleaseComObject(presentations);
            Marshal.ReleaseComObject(slides);
            Presentation.Close();
            Marshal.FinalReleaseComObject(Presentation);
            PP.Quit();
            Marshal.FinalReleaseComObject(PP);
        }
Example #11
0
        private static void createPowerPoint(OutlineParagraph outlineParagraph, string targetFile)
        {
            var pptApplication = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();

            var rootPath          = System.IO.Path.GetDirectoryName(targetFile);
            var targetName        = System.IO.Path.GetFileNameWithoutExtension(targetFile);
            var pptFileTargetPath = System.IO.Path.Combine(rootPath, targetName) + $"\\" + outlineParagraph.Text.Trim() + ".ppt";


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

            var filePath = typeof(PPTGenerator).Assembly.Location;
            var path     = System.IO.Path.GetDirectoryName(filePath);


            pptPresentation.ApplyTheme(path + @"\BibleStudy.thmx");
            createPowerPoint(outlineParagraph, pptPresentation);

            Console.WriteLine(pptFileTargetPath);

            try
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(pptFileTargetPath));

                pptPresentation.SaveAs(pptFileTargetPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            var odpOutputfile = Path.Combine(rootPath, "..\\ODP", targetName, outlineParagraph.Text.Trim() + ".odp");



            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(odpOutputfile));
            pptPresentation.SaveAs(odpOutputfile, PpSaveAsFileType.ppSaveAsOpenDocumentPresentation);

            pptPresentation.Close();
            pptApplication.Quit();
        }
Example #12
0
        /// <summary>
        /// 切取PPT为图片
        /// </summary>
        private int GetPptPic(string pptPath, string imagePath, int imageWidth, int imageHeight)
        {
            int count = 0;

            try
            {
                POWERPOINT.ApplicationClass ac = new POWERPOINT.ApplicationClass();
                POWERPOINT.Presentation     p  = ac.Presentations.Open(pptPath, MsoTriState.msoCTrue, MsoTriState.msoCTrue, MsoTriState.msoFalse);
                count = p.Slides.Count;;
                DeleteInDir(imagePath);
                p.SaveAs(imagePath, POWERPOINT.PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue);
                RenameImage(imagePath, imageWidth, imageHeight);
                p.Close();
            }
            catch
            {
            }
            return(count);
        }
Example #13
0
        /// <summary>
        /// 转换函数
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="savePath">保存的路径</param>
        /// <returns></returns>
        public bool Convert(string sourcePath, string savePath)
        {
            bool result = false;

            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;

            try
            {
                pptApplication = new PowerPoint.ApplicationClass();
                presentation   = pptApplication.Presentations.Open(sourcePath,
                                                                   MsoTriState.msoTrue,
                                                                   MsoTriState.msoFalse,
                                                                   MsoTriState.msoFalse);
                presentation.SaveAs(savePath, targetFileType, MsoTriState.msoTrue);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }

                if (pptApplication != null)
                {
                    pptApplication.Quit();
                    pptApplication = null;
                }

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

            return(result);
        }
Example #14
0
        /// <summary>
        /// 把PowerPoing文件转换成PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool PPTConvertToPDF(string sourcePath, string targetPath)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            targetPath = HttpContext.Current.Server.MapPath(targetPath);
            bool result;

            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;

            PowerPoint.ApplicationClass application  = null;
            PowerPoint.Presentation     persentation = null;
            try
            {
                application  = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
Example #15
0
    /// <summary>
    /// 把PowerPoing文件转换成PDF格式文件
    /// </summary>
    /// <param name="sourcePath">源文件路径</param>
    /// <param name="targetPath">目标文件路径</param>
    /// <returns>true=转换成功</returns>
    private bool PPTConvertToPDF(string sourcePath, string targetPath)
    {
        bool result = false;

        //string er = "";
        PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
        object missing = Type.Missing;

        PowerPoint.ApplicationClass application  = null;
        PowerPoint.Presentation     persentation = null;
        try
        {
            application  = new PowerPoint.ApplicationClass();
            persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
            persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
            result = true;
            //er = "1";
        }
        catch (Exception ex)
        {
            //er= ex.Message.ToString();
            result = false;
        }
        finally
        {
            if (persentation != null)
            {
                persentation.Close();
                persentation = null;
            }
            if (application != null)
            {
                application.Quit();
                application = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        return(result);
    }
Example #16
0
        //将ppt文档转换成PDF格式
        private bool FConvertPPT(string sourcePath, string targetPath
                                 //, PpSaveAsFileType targetFileType
                                 )
        {
            PpSaveAsFileType targetFileType = PpSaveAsFileType.ppSaveAsPDF;
            bool             result;
            object           missing = Type.Missing;

            PowerPoint.ApplicationClass application = null;
            Presentation persentation = null;

            try
            {
                application  = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }
            return(result);
        }
Example #17
0
        /// <summary>
        /// Create the current argument in MS PowerPoint using COM
        /// </summary>
        /// <param name="a"></param>
        public void outputToPowerPoint(Argument a)
        {
            Node n;

            n = a.findHead();               // find main premise node
            a.referenceTree();              // reference tree
            index = 1;
            PPapp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
            object missing = System.Reflection.Missing.Value;

            Microsoft.Office.Core.MsoTriState mts = MsoTriState.msoTrue;

            PPapp.Presentations.Add(mts);
            PPapp.Visible = mts;

            doNode(n);

            // release the COM object. GC.Collect(); would be overkill
            System.Runtime.InteropServices.Marshal.ReleaseComObject(PPapp);
        }
Example #18
0
        /// <summary>
        /// 把PowerPoing文件转换成PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool PPTConvertToPDF(string sourcePath, string targetPath)
        {
            bool result;

            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;

            PowerPoint.ApplicationClass application  = null;
            PowerPoint.Presentation     persentation = null;
            try
            {
                application  = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                //Logger.WriteLog("Service Error:PowerPoing转pdf" + ex.ToString(), "Log\\ServiceInfoError.txt", true);
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
        ///<summary>把PowerPoint文件转换成PDF格式文件</summary>
        ///<param name="sourcePath">源文件路径</param>
        ///<param name="targetPath">目标文件路径</param>
        ///<returns>true=转换成功</returns>
        public static bool PPt2Pdf(string sourcePath, string targetPath)
        {
            bool result;

            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            //object missing = Type.Missing;
            PowerPoint.ApplicationClass application  = null;
            PowerPoint.Presentation     persentation = null;
            try
            {
                string source = sourcePath;
                string target = targetPath;
                application  = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(source, MsoTriState.msoTrue
                                                              , MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(target
                                    , targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                throw ex;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
        private Bitmap[] Scan4PowerPoint(string filePath, ICollection <int> pageIndexCollection)
        {
            List <Bitmap> bmList = new List <Bitmap>();

            MSPowerPoint.ApplicationClass pptApplicationClass = new MSPowerPoint.ApplicationClass();

            try
            {
                MSPowerPoint.Presentation presentation = pptApplicationClass.Presentations.Open(filePath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                int totalCount = presentation.Slides.Count;
                if (pageIndexCollection != null)
                {
                    totalCount = pageIndexCollection.Count;
                }
                int index = 0;
                foreach (MSPowerPoint.Slide slide in presentation.Slides)
                {
                    if (pageIndexCollection == null || pageIndexCollection.Contains(index))
                    {
                        slide.Export(@"C:\Users\74908\Desktop\111\" + index + ".png", "PNG");
                    }
                    ++index;
                }

                presentation.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(presentation);

                return(bmList.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                pptApplicationClass.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pptApplicationClass);
            }
        }
Example #21
0
        private static void ConvertPowerPointToPdf(string filePath)
        {
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
            string outputFilePath           = OutputFolder + fileNameWithoutExtension + ".pdf";

            Microsoft.Office.Interop.PowerPoint.ApplicationClass applicationClass = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
            Presentation presentation = null;

            try
            {
                Presentations presentations = applicationClass.Presentations;
                presentation = presentations.Open(filePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                presentation.ExportAsFixedFormat(outputFilePath, PpFixedFormatType.ppFixedFormatTypePDF,
                                                 PpFixedFormatIntent.ppFixedFormatIntentScreen, MsoTriState.msoFalse,
                                                 PpPrintHandoutOrder.ppPrintHandoutVerticalFirst, PpPrintOutputType.ppPrintOutputSlides,
                                                 MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, string.Empty, false, true, true, true, false, Type.Missing);
            }
            catch (System.Exception e)
            {
                log.Error("Eccezione durante la conversione del file PowerPoint " + filePath);
                log.Error(e.StackTrace);
                File.Move(filePath, ErrorFolder + Path.GetFileName(filePath));
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    Marshal.ReleaseComObject(presentation);
                }
                if (applicationClass != null)
                {
                    applicationClass.Quit();
                    Marshal.ReleaseComObject(applicationClass);
                }
                CloseProcess("powerpnt");
                File.Delete(filePath);
            }
        }
Example #22
0
        /// <summary>
        ///     Starts PowerPoint
        /// </summary>
        private void StartPowerPoint()
        {
            if (IsPowerPointRunning)
            {
                Logger.WriteToLog($"Powerpoint is already running on PID {_powerPointProcess.Id}... skipped");
                return;
            }

            Logger.WriteToLog("Starting PowerPoint");

            _powerPoint = new PowerPointInterop.ApplicationClass
            {
                DisplayAlerts = PowerPointInterop.PpAlertLevel.ppAlertsNone,
                DisplayDocumentInformationPanel = false,
                AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable
            };

            ProcessHelpers.GetWindowThreadProcessId(_powerPoint.HWND, out var processId);
            _powerPointProcess = Process.GetProcessById(processId);

            Logger.WriteToLog($"PowerPoint started with process id {_powerPointProcess.Id}");
        }
Example #23
0
        static void ppt2pdf(string sourcePath, string targetPath)
        {
            bool   result  = false;
            object missing = Type.Missing;

            PowerPoint.ApplicationClass application  = null;
            PowerPoint.Presentation     persentation = null;
            try
            {
                application  = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            // return result;
        }
Example #24
0
        public static bool PowerPointToPdf(string sourcePath, string targetPath, out string exmsg)
        {
            exmsg = string.Empty;
            bool               result;
            object             missing      = Type.Missing;
            PPApplicationClass application  = null;
            Presentation       persentation = null;

            try
            {
                application  = new PPApplicationClass();
                persentation = application.Presentations.Open(sourcePath);
                persentation.SaveAs(targetPath, PpSaveAsFileType.ppSaveAsPDF);

                result = true;
            }
            catch (Exception ex)
            {
                exmsg  = ex.Message;
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
            }
            return(result);
        }
Example #25
0
        public static string ReadPPT(string pptFileName)
        {
            string text = string.Empty;

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

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

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

            return(text);
        }
Example #26
0
        // http://support.microsoft.com/kb/303718/
        // http://msdn.microsoft.com/hi-in/magazine/cc163471(en-us).aspx


        static void Main(string[] args)
        {
            double bitmap_pixels_per_inch = 96.0;


            double slide_points_per_inch = 72.0;
            double scale = 1.0; // 1.0 = 100% - pixel to pixel
            // WORKITEM: FOrce scale between 0>scale<=1.0

            double bitmap_w_in_pixels = 1280;
            double bitmap_h_in_pixels = 1024;
            double h_excess           = 0.3;
            double v_excess           = 0.1;

            double bitmap_w_in_inches = scale * (bitmap_w_in_pixels / bitmap_pixels_per_inch);
            double bitmap_h_in_inches = scale * (bitmap_h_in_pixels / bitmap_pixels_per_inch);

            double excess_w_in_points = (h_excess * bitmap_w_in_inches) * slide_points_per_inch;
            double excess_h_in_points = (v_excess * bitmap_w_in_inches) * slide_points_per_inch;

            double excess_w_in_inches = excess_w_in_points / slide_points_per_inch;
            double excess_h_in_inches = excess_h_in_points / slide_points_per_inch;

            double slide_w_in_inches = (bitmap_w_in_inches) + excess_w_in_inches;
            double slide_h_in_inches = (bitmap_h_in_inches) + excess_h_in_inches;


            int placeholder_width_points  = (int)System.Math.Round(bitmap_w_in_inches * slide_points_per_inch, 0);
            int placeholder_height_points = (int)System.Math.Round(bitmap_h_in_inches * slide_points_per_inch, 0);

            int pic_left    = (int)(excess_w_in_points);
            int pic_top     = 0;
            int text_width  = (int)(excess_w_in_points);
            int text_height = (int)(bitmap_h_in_inches * slide_points_per_inch);


            var app = new PP.ApplicationClass();

            app.Visible = MOC.MsoTriState.msoTrue;
            var presentation = app.Presentations.Add(MOC.MsoTriState.msoTrue);

            presentation.PageSetup.SlideWidth  = (int)(slide_w_in_inches * slide_points_per_inch);
            presentation.PageSetup.SlideHeight = (int)(slide_h_in_inches * slide_points_per_inch);

            string input_folder = System.IO.Path.GetFullPath(args[0]);

            Console.WriteLine("PATH {0}", input_folder);
            var files = System.IO.Directory.GetFiles(input_folder, "*.png");

            string custom_layout_name = "ScreenShot";

            var customlayout = presentation.SlideMaster.CustomLayouts.Add(presentation.SlideMaster.CustomLayouts.Count + 1);

            customlayout.Name = custom_layout_name;
            var s1 = customlayout.Shapes[1];

            s1.Delete();


            var comment_shape = customlayout.Shapes.AddPlaceholder(Microsoft.Office.Interop.PowerPoint.PpPlaceholderType.ppPlaceholderBody, 0, 0, text_width, text_height);
            var pic_shape     = customlayout.Shapes.AddPlaceholder(Microsoft.Office.Interop.PowerPoint.PpPlaceholderType.ppPlaceholderBitmap, pic_left, pic_top, placeholder_width_points, placeholder_height_points);

            int?debug_slide_limit = 3;

            var files_for_slides = files.AsEnumerable();

            if (debug_slide_limit.HasValue)
            {
                files_for_slides = files_for_slides.Take(debug_slide_limit.Value);
            }

            foreach (var file in files_for_slides)
            {
                var slide            = presentation.Slides.AddNew(customlayout);
                var linktofile       = MOC.MsoTriState.msoFalse;
                var savewithdocument = MOC.MsoTriState.msoTrue;
                var bitmap_shape     = slide.Shapes.AddPicture(file, linktofile, savewithdocument, pic_left, pic_top, placeholder_width_points, placeholder_height_points);
                bitmap_shape.ScaleHeight((float)scale, MOC.MsoTriState.msoTrue, MOC.MsoScaleFrom.msoScaleFromTopLeft);
                bitmap_shape.ScaleWidth((float)scale, MOC.MsoTriState.msoTrue, MOC.MsoScaleFrom.msoScaleFromTopLeft);

                PP.Shape ns = null;
                if (slide.NotesPage.Shapes.Count < 1)
                {
                    //ns = slide.NotesPage.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeRectangle, 0, 0, 0, 0);
                }
                else
                {
                    //ns = slide.NotesPage.Shapes[1];
                }
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            string path;             //文件路径变量

            PPT.Application  pptApp; //Excel应用程序变量
            PPT.Presentation pptDoc; //Excel文档变量

            PPT.Presentation pptDoctmp;



            path   = @"C:\MyPPT.ppt";            //路径
            pptApp = new PPT.ApplicationClass(); //初始化

            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }

            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;

            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);

            string text = "示例文本";

            foreach (PPT.Slide slide in pptDoc.Slides)
            {
                foreach (PPT.Shape shape in slide.Shapes)
                {
                    shape.TextFrame.TextRange.InsertAfter(text);
                }
            }


            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;

            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);

            //关闭excelDoc文档对象
            pptDoc.Close();

            //关闭excelApp组件对象
            pptApp.Quit();

            Console.WriteLine(path + " 创建完毕!");

            Console.ReadLine();


            string pathHtml = @"c:\MyPPT.html";

            PPT.Application pa = new PPT.ApplicationClass();

            pptDoctmp = pa.Presentations.Open(path, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            PPT.PpSaveAsFileType formatTmp = PPT.PpSaveAsFileType.ppSaveAsHTML;
            pptDoctmp.SaveAs(pathHtml, formatTmp, Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoctmp.Close();
            pa.Quit();
            Console.WriteLine(pathHtml + " 创建完毕!");
        }
Example #28
0
        /// <summary>
        /// 把PowerPoing文件转换成PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool PPTConvertToPDF(string sourcePath, string targetPath)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            targetPath = HttpContext.Current.Server.MapPath(targetPath);
            bool result;
            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;
            PowerPoint.ApplicationClass application = null;
            PowerPoint.Presentation persentation = null;
            try
            {
                application = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
Example #29
0
 //获取置顶ppt的页数
 public int GetPageCountByPPT(string pptPath)
 {
     POWERPOINT.ApplicationClass ac = new POWERPOINT.ApplicationClass();
     POWERPOINT.Presentation     p  = ac.Presentations.Open(pptPath, MsoTriState.msoCTrue, MsoTriState.msoCTrue, MsoTriState.msoFalse);
     return(p.Slides.Count);
 }
        // Test driver.
        public static bool Test()
        {
            bool passed = true;
            PowerPoint.Application app = new PowerPoint.ApplicationClass();
            app.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

            PowerPoint.Presentation presentation = app.Presentations.Add(Core.MsoTriState.msoFalse);
            PowerPoint.Slide slide = presentation.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutBlank);
            PowerPoint.Shape shape = slide.Shapes.AddLine(0, 0, 100, 100);

            Console.WriteLine("Test on presentation.");
            passed = passed && TestTags(presentation.Tags);

            Console.WriteLine("Test on slide.");
            passed = passed && TestTags(slide.Tags);

            Console.WriteLine("Test on shape.");
            passed = passed && TestTags(shape.Tags);

            app = null;

            return passed;
        }
        void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            DirectoryInfo diPPT = null;
            string str1 = null;
            try
            {
               // if (tbUpload.Text != "")
                if(!string.IsNullOrEmpty(tbUpload.Text))
                {
                    if (File.Exists(tbUpload.Text))
                    {
                        string[] strarray = tbUpload.Text.Split('\\');

                        if(strarray[strarray.Length-1].Contains("pptx"))
                        {
                            str1 = strarray[strarray.Length - 1].Replace(".pptx", "").Trim();
                        }
                        else
                        {
                        str1 = strarray[strarray.Length - 1].Replace(".ppt", "").Trim();
                        }


                        if (!str1.Contains("."))
                        {
                            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + "\\" + str1))
                            {
                                Microsoft.Office.Interop.PowerPoint.Application oPPT;
                                Microsoft.Office.Interop.PowerPoint.Presentations objPresSet;
                                Microsoft.Office.Interop.PowerPoint.Presentation objPres;

                                oPPT = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();                                

                                objPresSet = oPPT.Presentations;

                                diPPT = Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                                File.Copy(tbUpload.Text, diPPT.FullName + "\\" + str1 + ".ppt");

                                objPres = objPresSet.Open(diPPT.FullName + "\\" + str1 + ".ppt", MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
                                objPres.SaveAs(diPPT.FullName + "\\" + str1, PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoFalse);
                                File.Move(diPPT.FullName + "\\" + str1 + ".ppt", diPPT.FullName + "\\" + str1 + "\\" + str1 + ".ppt");

                                string[] strJPG = Directory.GetFiles(diPPT.FullName + "\\" + str1, "*.JPG");

                                for (int k = 0; k < strJPG.Length; k++)
                                {

                                    FileInfo f = new FileInfo(strJPG[k]);
                                    string strName = "";
                                    string newstr1 = "";
                                    if (f.Name.Split('.')[0].Length < 7)
                                    {
                                        strName = f.Name.Replace("Slide", "Slide0");
                                        newstr1 = strJPG[k].Replace(f.Name, "");
                                        File.Move(strJPG[k], newstr1 + strName);
                                    }                                  
                                }

                                ListBoxItem lbi = new ListBoxItem();

                                ContextMenu cntMenuCollMod = new ContextMenu();

                                System.Windows.Controls.MenuItem mnu;
                                mnu = new System.Windows.Controls.MenuItem();
                                mnu.Header = "Remove";
                                mnu.Click += new RoutedEventHandler(mnu_Click);
                                cntMenuCollMod.Items.Add(mnu);
                                
                                lbi.Content = str1;
                                lbi.ContextMenu = cntMenuCollMod;
                                
                                listBox1.Items.Add(lbi);
                                ClsException.WriteToLogFile("Presentation module:");
                                ClsException.WriteToLogFile("user click pptupload button");
                                ClsException.WriteToLogFile("ppt name :" + str1);
                                MessageBox.Show("File Uploaded");
                                tbUpload.Text = "";

                            }
                            else
                            {
                                MessageBox.Show("File with same name already exists!!");
                                tbUpload.Text = "";
                            }
                        }
                        else
                        {
                            MessageBox.Show(@"FileName contains ""."" Rename the File ", "Rename File", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
                            tbUpload.Text = "";
                        }
                    }
                    else
                    {
                        MessageBox.Show("File Does Not Exists!", "NonExisting File", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
                        tbUpload.Text = "";
                    }
                }
                else
                {
                    MessageBox.Show("Select File to Upload!", "File Upload", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
                    tbUpload.Text = "";
                }
            }
            catch (System.Exception ex)
            {
                VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "btnUpload_Click()/Microsoft Office", "UserControl1.xaml.cs");

                //try
                //{

                //    XComponentContext localContext = Bootstrap.bootstrap();

                //    XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)localContext.getServiceManager();

                //    XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");

                //    string[] strTemp = tbUpload.Text.Split('\\');

                //    diPPT = Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations\\" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                //    File.Copy(tbUpload.Text, diPPT.FullName + "\\" + str1 + ".ppt");

                //    DirectoryInfo diPPTNew = Directory.CreateDirectory(diPPT.FullName + "\\" + strTemp[strTemp.Length - 1].Split('.')[0]);
                //    File.Move(diPPT.FullName + "\\" + strTemp[strTemp.Length - 1], diPPTNew.FullName + "\\" + strTemp[strTemp.Length - 1]);


                //    string strpath = diPPTNew.FullName + "\\" + strTemp[strTemp.Length - 1];
                //    string newstr = strpath.Replace('\\', '/');
                //    XComponent xComponent = componentLoader.loadComponentFromURL("file:///" + newstr, "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[1] { MakePropertyValue("Hidden", new uno.Any(true)) });

                //    int newslide = ((unoidl.com.sun.star.drawing.XDrawPagesSupplier)xComponent).getDrawPages().getCount();

                //    int nHighestPageNumber = newslide - 1;

                //    DeleteAllPagesExcept(xComponent, 0);
                //    string path = diPPTNew.FullName.Replace('\\', '/');
                //    string cNewName = "file:///" + newstr;

                //    ((XStorable)xComponent).storeToURL(cNewName + ".html", new unoidl.com.sun.star.beans.PropertyValue[1] { MakePropertyValue("FilterName", new uno.Any("impress_html_Export")) });

                //    ((XCloseable)xComponent).close(true);

                //    xComponent.dispose();


                //    string[] strFiles = Directory.GetFiles(diPPTNew.FullName, "*.html");
                //    for (int j = 0; j < strFiles.Length; j++)
                //    {
                //        File.Delete(strFiles[j]);
                //    }

                //    string[] strJPG = Directory.GetFiles(diPPTNew.FullName, "*.JPG");

                //    for (int k = 0; k < strJPG.Length; k++)
                //    {

                //        FileInfo f = new FileInfo(strJPG[k]);
                //        string strName = "";
                //        string newstr1 = "";
                //        if (f.Name.Split('.')[0].Length < 5)
                //        {
                //            strName = f.Name.Replace("img", "Slide0");
                //            newstr1 = strJPG[k].Replace(f.Name, "");
                //            File.Move(strJPG[k], newstr1 + strName);
                //        }
                //        else
                //        {
                //            strName = f.Name.Replace("img", "Slide");
                //            newstr1 = strJPG[k].Replace(f.Name, "");
                //            File.Move(strJPG[k], newstr1 + strName);
                //        }
                //    }
                //    ListBoxItem lbi = new ListBoxItem();

                //    ContextMenu cntMenuCollMod = new ContextMenu();

                //    System.Windows.Controls.MenuItem mnu;
                //    mnu = new System.Windows.Controls.MenuItem();
                //    mnu.Header = "Remove";
                //    mnu.Click += new RoutedEventHandler(mnu_Click);
                //    cntMenuCollMod.Items.Add(mnu);

                //    //lbi.ContextMenu = mnu;

                //    lbi.Content = str1;
                //    lbi.ContextMenu = cntMenuCollMod;
                    
                //    listBox1.Items.Add(lbi);

                //    MessageBox.Show("File Uploaded");
                //    tbUpload.Text = "";
                //}
                //catch (System.Exception exp)
                //{
                //    VMuktiAPI.VMuktiHelper.ExceptionHandler(exp, "btnUpload_Click()/Open Office", "UserControl1.xaml.cs");
                //    MessageBox.Show("You need Open Office or Microsoft Office to upload the ppt, MS office 2007 for pptx. Make sure PPT is not open or corrupted.", "Upload PPT", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
                //}
            }
        }
Example #32
0
        /// <summary>
        /// Converts a PowerPoint document to PDF
        /// </summary>
        /// <param name="inputFile">The PowerPoint input file</param>
        /// <param name="outputFile">The PDF output file</param>
        /// <returns></returns>
        internal static void Convert(string inputFile, string outputFile)
        {
            DeleteAutoRecoveryFiles();

            PowerPointInterop.ApplicationClass powerPoint = null;
            PowerPointInterop.Presentation presentation = null;

            try
            {
                powerPoint = new PowerPointInterop.ApplicationClass
                {
                    DisplayAlerts = PowerPointInterop.PpAlertLevel.ppAlertsNone,
                    DisplayDocumentInformationPanel = false,
                    AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable
                };

                presentation = Open(powerPoint, inputFile, false);
                presentation.ExportAsFixedFormat(outputFile, PowerPointInterop.PpFixedFormatType.ppFixedFormatTypePDF);
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Saved = MsoTriState.msoFalse;
                    presentation.Close();
                    Marshal.ReleaseComObject(presentation);
                }

                if (powerPoint != null)
                {
                    powerPoint.Quit();
                    Marshal.ReleaseComObject(powerPoint);
                }
            }
        }
Example #33
0
        private void button2_Click(object sender, EventArgs e)
        {
            string path;                    //文件路径变量

            PowerPoint.Application  pptApp; //Excel应用程序变量
            PowerPoint.Presentation pptDoc; //Excel文档变量

            PowerPoint.Presentation pptDoctmp;



            path = @"C:\Users\ssor\Desktop\test.ppt";      //路径

            /*
             * pptApp = new PowerPoint.ApplicationClass(); //初始化
             *
             * //如果已存在,则删除
             * if (File.Exists((string)path))
             * {
             *  File.Delete((string)path);
             * }
             *
             * //由于使用的是COM库,因此有许多变量需要用Nothing代替
             * Object Nothing = Missing.Value;
             * pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
             * pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);
             *
             * string text = "示例文本";
             *
             * foreach (PowerPoint.Slide slide in pptDoc.Slides)
             * {
             *  foreach (PowerPoint.Shape shape in slide.Shapes)
             *  {
             *      shape.TextFrame.TextRange.InsertAfter(text);
             *  }
             * }
             *
             *
             * //WdSaveFormat为Excel文档的保存格式
             * PowerPoint.PpSaveAsFileType format = PowerPoint.PpSaveAsFileType.ppSaveAsDefault;
             *
             * //将excelDoc文档对象的内容保存为XLSX文档
             * pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
             *
             * //关闭excelDoc文档对象
             * pptDoc.Close();
             *
             * //关闭excelApp组件对象
             * pptApp.Quit();
             *
             * //Console.WriteLine(path + " 创建完毕!");
             *
             * //Console.ReadLine();
             *
             * return;
             * */

            string pathHtml = @"C:\Users\ssor\Desktop\MyPPT.html";

            PowerPoint.Application pa = new PowerPoint.ApplicationClass();

            pptDoctmp = pa.Presentations.Open(path, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            PowerPoint.PpSaveAsFileType formatTmp = PowerPoint.PpSaveAsFileType.ppSaveAsHTMLDual;
            pptDoctmp.SaveAs(pathHtml, formatTmp, Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoctmp.Close();
            pa.Quit();
            MessageBox.Show("创建完毕!");
            //Console.WriteLine(pathHtml + " 创建完毕!");
        }
Example #34
0
        private void Form1_Load(object sender, EventArgs e)
        {
            pptNS.ApplicationClass powerpointApplication = null;
            pptNS.Presentation     pptPresentation       = null;
            pptNS.Slide            pptSlide   = null;
            pptNS.ShapeRange       shapeRange = null;
            pptNS.Shape            oTxtShape  = null;
            pptNS.Shape            oShape     = null;
            pptNS.Shape            oPicShape  = null;

            xlNS.ApplicationClass excelApplication    = null;
            xlNS.Workbook         excelWorkBook       = null;
            xlNS.Worksheet        targetSheet         = null;
            xlNS.ChartObjects     chartObjects        = null;
            xlNS.ChartObject      existingChartObject = null;
            xlNS.Range            destRange           = null;

            string paramPresentationPath = @"D:\test\Test Slide.pptx";
            string paramWorkbookPath     = @"D:\test\NPS.xlsx";
            object paramMissing          = Type.Missing;


            try
            {
                // Create an instance of PowerPoint.
                powerpointApplication = new pptNS.ApplicationClass();

                // Create an instance Excel.
                excelApplication = new xlNS.ApplicationClass();

                // Open the Excel workbook containing the worksheet with the chart
                // data.
                excelWorkBook = excelApplication.Workbooks.Open(paramWorkbookPath,
                                                                paramMissing, paramMissing, paramMissing,
                                                                paramMissing, paramMissing, paramMissing,
                                                                paramMissing, paramMissing, paramMissing,
                                                                paramMissing, paramMissing, paramMissing,
                                                                paramMissing, paramMissing);

                // Get the worksheet that contains the chart.
                targetSheet =
                    (xlNS.Worksheet)(excelWorkBook.Worksheets["Spain"]);

                // Get the ChartObjects collection for the sheet.
                chartObjects =
                    (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));



                // Create a PowerPoint presentation.
                pptPresentation = powerpointApplication.Presentations.Add(
                    Microsoft.Office.Core.MsoTriState.msoTrue);

                // Add a blank slide to the presentation.
                pptSlide = pptPresentation.Slides.Add(1, pptNS.PpSlideLayout.ppLayoutBlank);


                // capture range
                //var writeRange = targetSheet.Range["A1:B15"];
                destRange = targetSheet.get_Range("A1:B21");
                oTxtShape = pptSlide.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, Left: 70, Top: 30, Width: 550, Height: 340);
                oTxtShape.TextFrame.TextRange.Text = "GB NPS 03/01/2017 to 26/01/2017";
                oTxtShape.TextEffect.FontName      = "Arial";
                oTxtShape.TextEffect.FontSize      = 32;
                oTxtShape.TextEffect.FontBold      = Microsoft.Office.Core.MsoTriState.msoTrue;
                oTxtShape.TextEffect.Alignment     = Microsoft.Office.Core.MsoTextEffectAlignment.msoTextEffectAlignmentCentered;

                System.Array myvalues = (System.Array)destRange.Cells.Value;
                List <Tuple <string, string> > cellData = GetData(myvalues);

                int iRows    = cellData.Count + 1;
                int iColumns = 2;
                int row      = 2;

                oShape = pptSlide.Shapes.AddTable(iRows, iColumns, 500, 110, 160, 120);
                oShape.Table.ApplyStyle("{5940675A-B579-460E-94D1-54222C63F5DA}");
                //oShape.Table.ApplyStyle("{0660B408-B3CF-4A94-85FC-2B1E0A45F4A2}");
                // table style guide https://msdn.microsoft.com/en-us/library/office/hh273476(v=office.14).aspx
                oShape.Table.Cell(1, 1).Merge(oShape.Table.Cell(1, 2));
                //oShape.Table.Cell(1, 1).Shape.TextFrame.TextRange.Text = "Spain Data 01/01/2017 to 20/01/2017";
                //oShape.Table.Cell(1, 1).Shape.TextFrame.TextRange.Font.Name = "Verdana";
                //oShape.Table.Cell(1, 1).Shape.TextFrame.TextRange.Font.Size = 8;

                foreach (Tuple <string, string> item in cellData)
                {
                    string strdate  = item.Item1;
                    string strValue = item.Item2;

                    oShape.Table.Cell(row, 1).Shape.TextFrame.TextRange.Text      = strdate;
                    oShape.Table.Cell(row, 1).Shape.TextFrame.TextRange.Font.Name = "Arial";
                    oShape.Table.Cell(row, 1).Shape.TextFrame.TextRange.Font.Size = 10;


                    oShape.Table.Cell(row, 2).Shape.TextFrame.TextRange.Text      = (strValue.StartsWith("0") ?  "0%" : (strValue + "0%"));
                    oShape.Table.Cell(row, 2).Shape.TextFrame.TextRange.Font.Name = "Arial";
                    oShape.Table.Cell(row, 2).Shape.TextFrame.TextRange.Font.Size = 10;

                    //if (row == 1)
                    //{
                    //    oShape.Table.Cell(row, 1).Shape.Fill.ForeColor.RGB = System.Drawing.Color.FromArgb(208, 208, 208).ToArgb();
                    //    oShape.Table.Cell(row, 1).Shape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

                    //    oShape.Table.Cell(row, 2).Shape.Fill.ForeColor.RGB = System.Drawing.Color.FromArgb(208, 208, 208).ToArgb();
                    //    oShape.Table.Cell(row, 2).Shape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

                    //}

                    row++;
                }

                oShape.Top  = 100;
                oShape.Left = 30;

                oPicShape = pptSlide.Shapes.AddPicture(@"D:\test\chart.png",
                                                       Microsoft.Office.Core.MsoTriState.msoFalse,
                                                       Microsoft.Office.Core.MsoTriState.msoTrue, 200, 100, 500, 300);

                //copy range
                //destRange.Copy();

                // Paste the chart into the PowerPoint presentation.
                //shapeRange = pptSlide.Shapes.Paste();

                //var table = pptSlide.Shapes.AddTable();
                // Position the chart on the slide.
                //shapeRange.Left = 60;
                //shapeRange.Top = 100;

                // Get or capture the chart to copy.
                //existingChartObject = (xlNS.ChartObject)(chartObjects.Item(1));


                // Copy the chart from the Excel worksheet to the clipboard.
                //existingChartObject.Copy();

                // Paste the chart into the PowerPoint presentation.
                //shapeRange = pptSlide.Shapes.Paste();
                //Position the chart on the slide.
                //shapeRange.Left = 90;
                //shapeRange.Top = 100;

                // Save the presentation.
                pptPresentation.SaveAs(paramPresentationPath,
                                       pptNS.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                                       Microsoft.Office.Core.MsoTriState.msoTrue);

                pptPresentation.SaveCopyAs(String.Format(@"D:\test\Export", "video_of_presentation"),
                                           pptNS.PpSaveAsFileType.ppSaveAsEMF,
                                           Microsoft.Office.Core.MsoTriState.msoCTrue);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Release the PowerPoint slide object.
                shapeRange = null;
                pptSlide   = null;

                // Close and release the Presentation object.
                if (pptPresentation != null)
                {
                    pptPresentation.Close();
                    pptPresentation = null;
                }

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

                // Release the Excel objects.
                targetSheet         = null;
                chartObjects        = null;
                existingChartObject = null;

                // Close and release the Excel Workbook object.
                if (excelWorkBook != null)
                {
                    excelWorkBook.Close(false, paramMissing, paramMissing);
                    excelWorkBook = null;
                }

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

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #35
0
        // http://support.microsoft.com/kb/303718/
        // http://msdn.microsoft.com/hi-in/magazine/cc163471(en-us).aspx


        static void Main(string[] args)
        {
            double bitmap_pixels_per_inch = 96.0;


            double slide_points_per_inch = 72.0;
            double scale = 1.0; // 1.0 = 100% - pixel to pixel
            // WORKITEM: FOrce scale between 0>scale<=1.0

            double bitmap_w_in_pixels = 1280;
            double bitmap_h_in_pixels = 1024;
            double h_excess = 0.3;
            double v_excess = 0.1;

            double bitmap_w_in_inches = scale * (bitmap_w_in_pixels / bitmap_pixels_per_inch);
            double bitmap_h_in_inches = scale * (bitmap_h_in_pixels / bitmap_pixels_per_inch);

            double excess_w_in_points = (h_excess * bitmap_w_in_inches)* slide_points_per_inch;
            double excess_h_in_points = (v_excess * bitmap_w_in_inches) * slide_points_per_inch;

            double excess_w_in_inches = excess_w_in_points / slide_points_per_inch;
            double excess_h_in_inches = excess_h_in_points / slide_points_per_inch;

            double slide_w_in_inches = (bitmap_w_in_inches) + excess_w_in_inches;
            double slide_h_in_inches = (bitmap_h_in_inches) + excess_h_in_inches;


            int placeholder_width_points = (int)System.Math.Round(bitmap_w_in_inches * slide_points_per_inch, 0) ;
            int placeholder_height_points = (int)System.Math.Round(bitmap_h_in_inches * slide_points_per_inch, 0);

            int pic_left = (int)(excess_w_in_points);
            int pic_top = 0;
            int text_width = (int)(excess_w_in_points);
            int text_height = (int) (bitmap_h_in_inches * slide_points_per_inch);

            
            var app = new PP.ApplicationClass();
            app.Visible = MOC.MsoTriState.msoTrue;
            var presentation = app.Presentations.Add(MOC.MsoTriState.msoTrue);
            presentation.PageSetup.SlideWidth = (int)(slide_w_in_inches * slide_points_per_inch);
            presentation.PageSetup.SlideHeight = (int)(slide_h_in_inches * slide_points_per_inch);
            
            string input_folder = System.IO.Path.GetFullPath(args[0]);

            Console.WriteLine("PATH {0}",input_folder);
            var files = System.IO.Directory.GetFiles(input_folder, "*.png");

            string custom_layout_name = "ScreenShot";
            
            var customlayout = presentation.SlideMaster.CustomLayouts.Add(presentation.SlideMaster.CustomLayouts.Count + 1);
            customlayout.Name = custom_layout_name;
            var s1  = customlayout.Shapes[1];
            s1.Delete();


            var comment_shape = customlayout.Shapes.AddPlaceholder(Microsoft.Office.Interop.PowerPoint.PpPlaceholderType.ppPlaceholderBody, 0, 0, text_width, text_height);
            var pic_shape = customlayout.Shapes.AddPlaceholder(Microsoft.Office.Interop.PowerPoint.PpPlaceholderType.ppPlaceholderBitmap, pic_left, pic_top, placeholder_width_points, placeholder_height_points);

            int? debug_slide_limit = 3;

            var files_for_slides = files.AsEnumerable();
            if (debug_slide_limit.HasValue)
            {
                files_for_slides = files_for_slides.Take(debug_slide_limit.Value);
                
            }

            foreach (var file in files_for_slides)
            {

                var slide = presentation.Slides.AddNew(customlayout);
                var linktofile = MOC.MsoTriState.msoFalse; 
                var savewithdocument = MOC.MsoTriState.msoTrue;
                var bitmap_shape = slide.Shapes.AddPicture(file, linktofile, savewithdocument, pic_left, pic_top, placeholder_width_points, placeholder_height_points);
                bitmap_shape.ScaleHeight( (float)scale, MOC.MsoTriState.msoTrue, MOC.MsoScaleFrom.msoScaleFromTopLeft);
                bitmap_shape.ScaleWidth((float)scale, MOC.MsoTriState.msoTrue, MOC.MsoScaleFrom.msoScaleFromTopLeft);

                PP.Shape ns = null;
                if (slide.NotesPage.Shapes.Count < 1)
                {
                    //ns = slide.NotesPage.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeRectangle, 0, 0, 0, 0);
                }
                else
                {
                    //ns = slide.NotesPage.Shapes[1];
                }

            }


        }
Example #36
0
 public ppt2pdfConverter()
 {
     pptApplication = null;
     presentation   = null;
 }