Ejemplo n.º 1
0
        private static void SearchFile(string folder)
        {
            Microsoft.Office.Interop.PowerPoint.Application app = null;
            try
            {
                //Fileオブジェクトを作る
                FileInfo target = new FileInfo(folder);

                //PowerPointの新しいインスタンスを作成する
                app = new Microsoft.Office.Interop.PowerPoint.Application();

                //最小化状態で表示する
                app.Visible     = MsoTriState.msoTrue;
                app.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMinimized;

                GetPowerPointData(
                    app.Presentations.Open(target.FullName, MsoTriState.msoFalse,
                                           MsoTriState.msoFalse,
                                           MsoTriState.msoFalse));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                //PowerPointを終了する
                if (app != null)
                {
                    app.Quit();
                }
            }
        }
Ejemplo n.º 2
0
        private void btnConvertAll_Click(object sender, EventArgs e)
        {
            progressBar1.Visible = true;
            progressBar1.Maximum = listBoxFiles.Items.Count;
            progressBar1.Step    = 1;
            Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
            foreach (object logListItem in listBoxFiles.Items)
            {
                progressBar1.PerformStep();
                this.Refresh();

                string strLogName      = logListItem.ToString();
                string strFullFilePath = textBoxFolder.Text + "\\" + strLogName;

                if (File.Exists(strFullFilePath + ".ppt"))
                {
                    Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = pptApp.Presentations.Open(strFullFilePath + ".ppt", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                    pptPresentation.SaveAs(strFullFilePath + ".pptx", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPicturePresentation);
                    pptPresentation.Close();
                }
            }
            pptApp.Quit();
            progressBar1.Visible = false;
        }
Ejemplo n.º 3
0
        public static void PptToHtmlFile(string PptFilePath)
        {
            //获得html文件名

            string htmlFileName = PptFilePath.Substring(0, PptFilePath.LastIndexOf(".")) + ".html";

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

            Microsoft.Office.Interop.PowerPoint.Presentation pptFile = null;

            try
            {
                //打开一个ppt文件

                pptFile = ppt.Presentations.Open(PptFilePath, Microsoft.Office.Core.MsoTriState.msoTrue,

                                                 Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoFalse);

                //转换成html格式

                pptFile.SaveAs(htmlFileName, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML,

                               Microsoft.Office.Core.MsoTriState.msoCTrue);
            }

            finally
            {
                if (pptFile != null)
                {
                    pptFile.Close();
                }
                ppt.Quit();
                GC.Collect();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 调用office的Com组件
        /// </summary>
        /// <param name="pptPath"></param>
        /// <returns></returns>
        private int PPTToImgCom(string pptPath, string imgName)
        {
            var    app         = new Microsoft.Office.Interop.PowerPoint.Application();
            string paramSource = Server.MapPath("~/file/ppt/") + pptPath;
            string imgPath     = "~/file/img/" + imgName;

            CheckDirect(Server.MapPath(imgPath));
            string paramTarget = Server.MapPath(imgPath);
            var    ppt         = app.Presentations.Open(paramSource, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            var    index       = 0;
            var    fileName    = System.IO.Path.GetFileNameWithoutExtension(pptPath);

            foreach (Microsoft.Office.Interop.PowerPoint.Slide slid in ppt.Slides)
            {
                ++index;
                //设置图片大小
                slid.Export(Path.Combine(paramTarget, string.Format("{0}.jpg", index)), "jpg", 800, 600);

                //根据屏幕尺寸。设置图片大小
                //slid.Export(imgPath+string.Format("page{0}.jpg",index.ToString()), "jpg", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            }
            //释放资源
            ppt.Close();
            app.Quit();
            GC.Collect();
            return(index);
        }
Ejemplo n.º 5
0
        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)
                {
                }
            }
        }
Ejemplo n.º 6
0
        static void ppt2pdf(string inputPath, string outputPath)
        {
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException(string.Format("The specified file {0} does not exist.", inputPath), inputPath);
            }

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

                app.Presentations.Open(
                    inputPath,
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    Microsoft.Office.Core.MsoTriState.msoFalse)
                .SaveAs(
                    outputPath,
                    Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF);
                app.Quit();
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Unable to convert {0} to {1}", inputPath, outputPath), e);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// PPT转成Html
        /// </summary>
        /// <param name="physicalPath">文件物理路径 绝对路径</param>
        /// <param name="serverPath">文件服务器路径 相对路径</param>
        /// <returns></returns>
        public static OfficeResult PPTToHtml(string physicalPath, string serverPath)
        {
            OfficeResult res = new OfficeResult();

            try
            {
                //-------------------------------------------------
                Microsoft.Office.Interop.PowerPoint.Application  ppApp   = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(physicalPath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
                string htmlName   = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
                string outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
                prsPres.SaveAs(outputFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
                prsPres.Close();
                ppApp.Quit();
                //---------------------------------------------------------------
                //return Path.GetDirectoryName(System.Web.HttpContext.Current.Server.UrlDecode(url)) + "\\" + htmlName;
                string previewFile = Path.GetDirectoryName(serverPath) + "\\" + htmlName;
                res.code    = 1;
                res.message = previewFile;
                return(res);
            }
            catch (Exception ex)
            {
                res.code    = 0;
                res.message = ex.Message;
                return(res);
            }
        }
        /// <summary>
        ///     The convert to pptx.
        /// </summary>
        /// <param name="fullPath">The full path.</param>
        /// <param name="targetLanguage">The target language.</param>
        /// <returns>
        ///     The System.String.
        /// </returns>
        private static string ConvertToPptx(string fullPath, string targetLanguage)
        {
            LoggingManager.LogMessage("Converting the document " + fullPath + " from ppt to pptx.");

            object file2 = GetOutputDocumentFullName(fullPath, targetLanguage);

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

            try
            {
                Microsoft.Office.Interop.PowerPoint.Presentation presentation =
                    powerPointApp.Presentations.Open(
                        fullPath,
                        MsoTriState.msoFalse,
                        MsoTriState.msoFalse,
                        MsoTriState.msoFalse);

                presentation.SaveAs(
                    file2.ToString(),
                    Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault,
                    MsoTriState.msoTriStateMixed);
                presentation.Close();
            }
            finally
            {
                powerPointApp.Quit();
            }

            LoggingManager.LogMessage("Converted the document " + fullPath + " from ppt to pptx.");
            return(file2.ToString());
        }
Ejemplo n.º 9
0
        /// <summary>把Word文件转换成为PDF格式文件</summary>   
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool PowerPointToHtml(string sourcePath, string targetPath)
        {
            bool result = false;

            try
            {
                //Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType targetFileType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.;
                Microsoft.Office.Interop.PowerPoint.Application ppt = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Core.MsoTriState m1 = new MsoTriState();
                Microsoft.Office.Core.MsoTriState m2 = new MsoTriState();
                Microsoft.Office.Core.MsoTriState m3 = new MsoTriState();
                Microsoft.Office.Interop.PowerPoint.Presentation pp = ppt.Presentations.Open(sourcePath, m1, m2, m3);
                pp.SaveAs(targetPath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, Microsoft.Office.Core.MsoTriState.msoTriStateMixed);
                pp.Close();
                ppt.Quit();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return(false);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Reads PPT and PPTX file types and extracts the words in each file
        /// Requires: The file path is in ppt or pptx format only
        /// </summary>
        /// <param name="filenameWithPath">path of PPT and PPTX document including filename</param>
        /// <exception cref="PlatformNotSupportedException">Thrown when the file to read is not of supported
        /// presentation format. </exception>
        /// <returns>
        /// A Dictionary where the Key contains the filename and the Value contains the entire wordlist
        /// </returns>
        private static Dictionary <string, List <string> > readPPTFiles(string filenameWithPath)
        {
            Contract.Requires <PlatformNotSupportedException>(System.IO.Path.GetExtension(filenameWithPath).Equals(".ppt") ||
                                                              System.IO.Path.GetExtension(filenameWithPath).Equals(".pptx"));

            List <string> result = new List <string>();
            Dictionary <string, List <string> > listresult = new Dictionary <string, List <string> >();

            Microsoft.Office.Interop.PowerPoint.Application   PowerPoint_App      = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            Microsoft.Office.Interop.PowerPoint.Presentation  presentation        = multi_presentations.Open(filenameWithPath);
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (var item in presentation.Slides[i + 1].Shapes)
                {
                    var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var    textRange = shape.TextFrame.TextRange;
                            string text      = textRange.Text.ToLower().Trim().ToString();
                            result.AddRange(text.Split(new char[] { ' ', '\n', '\t', '\r' }));
                        }
                    }
                }
            }
            PowerPoint_App.Quit();
            listresult.Add(filenameWithPath, result);
            return(listresult);
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         pp.Quit();
         Marshal.FinalReleaseComObject(pp);
     }
 }
 public void SaveAs(string filename)
 {
     if (File.Exists(filename))
     {
         File.Delete(filename);
     }
     _presentation.SaveAs(filename);
     _presentation.Close();
     _powerPoint.Quit();
 }
Ejemplo n.º 13
0
 private void freePowerPoint()
 {
     if (avaPoawrPoint)
     {
         if (pptPres != null)
         {
             pptPres = null;
         }
         pptApp.Quit();
     }
 }
Ejemplo n.º 14
0
        /// <summary>
           /// ppt convert to html
           /// </summary>
           /// <param name="path">要转换的文档的路径</param>
           /// <param name="savePath">转换成的html的保存路径</param>
           /// <param name="wordFileName">转换后html文件的名字</param>
        public static void PPTToHtml(string path, string savePath, string wordFileName)
        {
            Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
            string strSourceFile      = path;
            string strDestinationFile = savePath + wordFileName + ".html";

            Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(strSourceFile, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
            prsPres.Close();
            ppApp.Quit();
        }
Ejemplo n.º 15
0
        private async Task <string> ConvertPPTToPDFAsync(string inputFile, string outputFile)
        {
            try
            {
                await Task.Delay(500);

                await Task.Factory.StartNew(() =>
                {
                    var app        = new Microsoft.Office.Interop.PowerPoint.Application();
                    var retryCount = 3;
                    while (retryCount <= 3 && retryCount > 0)
                    {
                        try
                        {
                            var presentations = app.Presentations;
                            var presentation  = presentations.Open(inputFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                            presentation.ExportAsFixedFormat(outputFile, Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen);
                            retryCount++;

                            app.Quit();
                        }
                        catch (Exception error)
                        {
                            retryCount--;
                            //App.Current.Dispatcher.Invoke(() =>
                            // {
                            //     MessageBoxX.Show("Office转换文件失败,请检查Office是否正确安装", "错误");
                            // });

                            Analytics.TrackEvent("OfficeError", new Dictionary <string, string>
                            {
                                ["message"] = error.ToString()
                            });
                        }
                    }
                });

                if (File.Exists(outputFile))
                {
                    return(outputFile);
                }
            }
            catch (Exception ex)
            {
                Analytics.TrackEvent("PDFError", new Dictionary <string, string>
                {
                    ["message"] = ex.ToString()
                });
            }

            return(string.Empty);
        }
Ejemplo n.º 16
0
        private void ConvertFile(string strFilePath)
        {
            if (File.Exists(strFilePath + ".ppt"))
            {
                Microsoft.Office.Interop.PowerPoint.Application  pptApp          = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = pptApp.Presentations.Open(strFilePath + ".ppt", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                pptPresentation.SaveAs(strFilePath + ".pptx", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPicturePresentation);
                pptPresentation.Close();

                pptApp.Quit();
            }
        }
Ejemplo n.º 17
0
        public override void PostParse()
        {
            base.PostParse();

            Microsoft.Office.Interop.PowerPoint.Application powerpoint = powerpointTL.Value;
            if (powerpoint != null)
            {
                powerpointTL.Value = null;

                powerpoint.Quit();
                powerpoint = null;
            }
        }
Ejemplo n.º 18
0
 public static void SafeClose(this Microsoft.Office.Interop.PowerPoint.Application app)
 {
     try
     {
         GetWindowThreadProcessId(new IntPtr(app.HWND), out var processId);
         app.Quit();//try safe quit, then kill.
         KillProcess(processId);
     }
     catch (Exception ex)
     {
         Logger.WarnFormat(ex, "Unable to Safe close PowerPoint - {0}", ex.Message);
     }
 }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            string strPath =
                System.AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/");

            // Instantiate Object
            APServer.Server server = new APServer.Server();

            // Path and filename of output
            server.NewDocumentName = "Server.PowerPointPrinting.pdf";
            server.OutputDirectory = strPath;

            // Start the print job
            ServerDK.Results.ServerResult result = server.BeginPrintToPDF();
            if (result.ServerStatus == ServerDK.Results.ServerStatus.Success)
            {
                // Automate PowerPoint to print a document to activePDF Server
                // NOTE: You must add the 'Microsoft PowerPoint
                // <<version number>> Object Library' COM object as a reference
                // to your .NET application to access the PowerPoint Object.
                Microsoft.Office.Interop.PowerPoint._Application oPPT =
                    new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentation oPRES =
                    oPPT.Presentations.Open(
                        $"{strPath}Server.PowerPoint.Input.pptx",
                        Microsoft.Office.Core.MsoTriState.msoTrue,
                        Microsoft.Office.Core.MsoTriState.msoFalse,
                        Microsoft.Office.Core.MsoTriState.msoFalse);
                Microsoft.Office.Interop.PowerPoint.PrintOptions objOptions =
                    oPRES.PrintOptions;
                objOptions.ActivePrinter     = server.NewPrinterName;
                objOptions.PrintInBackground = 0;
                oPRES.PrintOut(1, 9999, "", 1, 0);
                oPRES.Saved = Microsoft.Office.Core.MsoTriState.msoTrue;
                oPRES.Close();
                oPPT.Quit();

                // Wait(seconds) for job to complete
                result = server.EndPrintToPDF(waitTime: 30);
            }

            // Output result
            WriteResult(result);

            // Process Complete
            Console.WriteLine("Done!");
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
 public void ClosePowerPoint()
 {
     if (powerpoint != null)
     {
         // Reenable Office Assisant, if it was on:
         if (bAssistantOn)
         {
             powerpoint.Assistant.On      = true;
             powerpoint.Assistant.Visible = false;
         }
         powerpoint.Quit();
         presentationSet = null;
         powerpoint      = null;
     }
 }
Ejemplo n.º 21
0
 public override void Dispose()
 {
     try
     {
         if (officePowerPoint != null)
         {
             officePowerPoint.Quit();
         }
         Marshal.FinalReleaseComObject(officePowerPoint);
         officePowerPoint = null;
         if (KillApplicationOnClose)
         {
             Utility.KillProcessesByName(OfficePowerPointExe);
         }
     }
     catch { }
 }
        public static void PrintFileAsXps(string path, int index, int total)
        {
            // Avoid Quit if already running.
            bool appAlreadyRunning = System.Diagnostics.Process.GetProcessesByName("powerpnt").Length > 0;

            // Create/get instance of MS PowerPoint.
            // Do it once per file to avoid out-of-memory issues or crashes to due memory fragmentation, etc.
            Console.WriteLine("Starting MS PowerPoint ...");
            var app = new MSOInterop.PowerPoint.Application();

            // Open presentation.
            MSOInterop.PowerPoint._Presentation pptFile;

            var fileInfo = new FileInfo(path);
            Console.WriteLine($"Opening {Path.GetFileName(path)} ({(double)fileInfo.Length / 1024 / 1024:0.##} MB) {index}/{total} ...");
            pptFile = app.Presentations.Open(path,
                                             WithWindow: MSOCore.MsoTriState.msoFalse); // Don't show window.

            // Set options.
            SetPrintOptions(pptFile);

            // Delete if exists.
            DeleteIfExists(pptFile);

            // Print.
            Console.WriteLine($"Printing ...");
            pptFile.PrintOut(PrintToFile: pptFile.FullName.Replace(".pptx", ".xps"));

            // Close file.
            pptFile.Close();
            Marshal.ReleaseComObject(pptFile);
            pptFile = null;

            // Quit app.
            if (!appAlreadyRunning)
            {
                app.Quit();
            }

            // Force process to exit.
            Marshal.ReleaseComObject(app);
            app = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// ppt convert to pdf
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool PPTConvertToPDF(string sourcePath, string targetPath)

        {
            bool result;

            //保存为pdf
            Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType targetFileType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;

            Microsoft.Office.Interop.PowerPoint.Application  application  = null;
            Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
            try
            {
                application  = new Microsoft.Office.Interop.PowerPoint.Application();
                presentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                presentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return(result);
        }
Ejemplo n.º 24
0
        private Boolean ConvertPowerpoint(string path, string newpath)
        {
            Boolean returnB = true;

            Microsoft.Office.Interop.PowerPoint.Application  pptApplication  = null;
            Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = null;

            object unknownType = Type.Missing;

            pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
            try
            {
                pptPresentation = pptApplication.Presentations.Open(path,
                                                                    Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue,
                                                                    Microsoft.Office.Core.MsoTriState.msoFalse);

                pptPresentation.ExportAsFixedFormat(newpath,
                                                    Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
                                                    Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
                                                    MsoTriState.msoFalse, Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                                                    Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null,
                                                    Microsoft.Office.Interop.PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty, true, true, true,
                                                    true, false, unknownType);

                if (pptPresentation == null)
                {
                    MainForm.error = String.Format("Filename {0} - Unexpected error at ConvertPowerpoint \r\n", Path.GetFileName(path));
                    returnB        = false;
                }
            }
            catch (Exception ex)
            {
                MainForm.error = String.Format("Filename {0} - {1} at ConvertPowerpoint \r\n", Path.GetFileName(path), ex.Message);
                returnB        = false;
            }
            pptPresentation.Close();
            pptPresentation = null;
            pptApplication.Quit();
            pptApplication = null;
            return(returnB);
        }
Ejemplo n.º 25
0
        private void btnChuyendoi_Click(object sender, EventArgs e)
        {
            //check xem file đưa vào là gì?
            var filename = txtFile_start.Text;

            if (Path.GetExtension(filename) == ".docx")
            {
                var wordApp      = new Microsoft.Office.Interop.Word.Application();
                var wordDocument = wordApp.Documents.Open(filename);
                wordDocument.ExportAsFixedFormat(txtFile_end.Text, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

                wordDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat, false);
                wordApp.Quit();

                File_Moi = txtFile_end.Text;

                this.Close();
            }
            else if (Path.GetExtension(filename) == ".xlsx")
            {
                var excelApp      = new Microsoft.Office.Interop.Excel.Application();
                var excelDocument = excelApp.Workbooks.Open(filename);
                excelDocument.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, txtFile_end.Text);
                excelDocument.Close(false, "", false);
                excelApp.Quit();
            }
            else if (Path.GetExtension(filename) == ".pptx")
            {
                var powerpointApp      = new Microsoft.Office.Interop.PowerPoint.Application();
                var powerpointDocument = powerpointApp.Presentations.Open(filename,
                                                                          Microsoft.Office.Core.MsoTriState.msoTrue,   //ReadOnly
                                                                          Microsoft.Office.Core.MsoTriState.msoFalse,  //Untitled
                                                                          Microsoft.Office.Core.MsoTriState.msoFalse); //Window not visible during converting
                powerpointDocument.ExportAsFixedFormat(txtFile_end.Text,
                                                       Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);

                powerpointDocument.Close(); //Close document
                powerpointApp.Quit();       //Important: When you forget this PowerPoint keeps running in the background
            }
        }
Ejemplo n.º 26
0
        public bool ExportPptFileToPdf(string workbookPath, string outputPath)
        {
            Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = null;

            Microsoft.Office.Interop.PowerPoint.Application appWord = new Microsoft.Office.Interop.PowerPoint.Application();
            try
            {
                pptPresentation = appWord.Presentations.Open(workbookPath,
                                                             Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue,
                                                             Microsoft.Office.Core.MsoTriState.msoFalse);
                pptPresentation.ExportAsFixedFormat(outputPath,
                                                    Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
                                                    Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
                                                    MsoTriState.msoFalse, Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
                                                    Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null,
                                                    Microsoft.Office.Interop.PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty, true, true, true,
                                                    true, false);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                // Close and release the Document object.
                if (pptPresentation != null)
                {
                    pptPresentation.Close();
                    pptPresentation = null;
                }

                // Quit PowerPoint and release the ApplicationClass object.
                if (appWord != null)
                {
                    appWord.Quit();
                    appWord = null;
                }
            }
        }
        private static string GetPPTContent(string path)
        {
            string fileExtension = Path.GetExtension(path).ToLower();

            if (fileExtension.Contains("pptx"))
            {
                StringBuilder        sb   = new StringBuilder();
                PresentationDocument pptx = PresentationDocument.Open(path, false);
                foreach (SlidePart slide in pptx.PresentationPart.SlideParts)
                {
                    sb.Append(slide.Slide.InnerText).Append(Environment.NewLine);
                }
                return(sb.ToString());
            }
            else
            {
                Microsoft.Office.Interop.PowerPoint.Application   PowerPoint_App      = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
                Microsoft.Office.Interop.PowerPoint.Presentation  presentation        = multi_presentations.Open(path, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
                string presentation_text = "";
                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;
                        if (shape.HasTextFrame == Microsoft.Office.Core.MsoTriState.msoTrue)
                        {
                            if (shape.TextFrame.HasText == Microsoft.Office.Core.MsoTriState.msoTrue)
                            {
                                var textRange = shape.TextFrame.TextRange;
                                var text      = textRange.Text;
                                presentation_text += text + " ";
                            }
                        }
                    }
                }
                PowerPoint_App.Quit();
                return(presentation_text);
            }
        }
Ejemplo n.º 28
0
            public static void savePowerPoint()
            {
                try
                {
                    //saving powerpoint
                    objPres.SaveAs(path + fileName, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault);

                    ppApp.Quit();

                    //release memory
                    releaseObject(objTextRng);
                    releaseObject(objSlide);
                    releaseObject(objSlides);
                    releaseObject(objPres);
                    releaseObject(ppPresens);
                    releaseObject(ppApp);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error saving " + fileName);
                }
            }
Ejemplo n.º 29
0
        // <summary>
        //  Method to convert a given Microsoft PowerPoint presentation (.ppt or .pptx) to PDF
        //  using the Microsoft.Office.Interop.PowerPoint library
        // </summary>
        private static void ConvertPPT(FileInfo file)
        {
            // Initialize Interop PowerPoint Application
            var app = new Microsoft.Office.Interop.PowerPoint.Application();

            // Open the PPT file
            var ppt = app.Presentations.Open(file.FullName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);

            // Export the file as PDF
            var outfile = file.FullName.Replace(file.Extension, ".pdf");

            ppt.SaveAs(outfile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);

            // Close everything
            ppt.Close();
            ppt = null;

            app.Quit();
            app = null;

            // Delete the original file since it's not needed anymore after conversion
            System.IO.File.Delete(file.FullName);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// ppt转成Html
        /// </summary>
        /// <param name="excelPath">要转换的文档的路径</param>
        /// <param name="htmlPath">转换成html的保存路径</param>
        /// <returns>是否成功</returns>
        public static bool PptToHtml(string filePath, string htmlPath = null)
        {
            var flg = false;

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

            string strDestinationFile = htmlPath ?? System.IO.Path.ChangeExtension(filePath, ".html");

            Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(filePath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
            try
            {
                prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
                flg = true;
            }
            catch (Exception ex) { throw ex; }
            try
            {
                prsPres.Close();
                ppApp.Quit();
            }
            catch { }
            return(flg);
        }
        //==================================
        public string ConvertHtmlToPpt(int projectId)
        {
            string pptFileName = string.Empty;
            try
            {
                ProjectSummaryDetailModel objSummaryModel = new ProjectSummaryDetailModel();
                objSummaryModel = ProjectSummary.GetProjectSummaryDetail(projectId);

                string pptFilePath = string.Empty;
                string htmlFilePath = string.Empty;

                StringWriter sw = new StringWriter();

                // Create new PPTX file for the attachment purposes.

                pptFileName = projectId + "ProjectName" + Guid.NewGuid().ToString().Substring(0, 6);
                pptFilePath = Server.MapPath("~/Temp/" + pptFileName);

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

                // VPS 28-10-2015

                powerPointApp.Visible = MsoTriState.msoTrue;
                Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
                Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
                Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(Server.MapPath("~/Temp/Template/Slide_Template.pptx"), MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                // Copy The Master presentation to the New presentation

                // Now open this new presentation slide and alter this with dynamic data

                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;
                        if (shape.HasTable == MsoTriState.msoTrue)
                        {
                            int columnCount = shape.Table.Columns.Count;
                            if (columnCount == 13) // Detect if this is the duration Table
                            {
                                if (objSummaryModel.ProjectDurationList != null && objSummaryModel.ProjectDurationList.Count > 0)
                                {
                                    // Find single column Width
                                    var column1 = shape.Table.Columns[1];
                                    float column1Width = column1.Width;
                                    float tableHeight = shape.Height;
                                    // Calculate Table Width [Multiply with 7 as initial 7 columns have proper design]
                                    float tableWidth = column1Width * 13;

                                    // Get Total Records
                                    int recordsCount = objSummaryModel.ProjectDurationList.Count;
                                    if (recordsCount < 13)
                                    {
                                        for (int lastColIndex = columnCount; lastColIndex >= recordsCount + 1; lastColIndex--)
                                        {
                                            var colToDelete = shape.Table.Columns[lastColIndex];
                                            colToDelete.Delete();
                                        }
                                    }
                                    // Get new Width of Each Columns;
                                    float newColsWidth = tableWidth / recordsCount;

                                    for (int rec = 0; rec <= recordsCount - 1; rec++)
                                    {
                                        //shape.Table.Columns.Add(-1);
                                        var column = shape.Table.Columns[rec + 1];//[1];
                                        column.Width = newColsWidth;
                                        var cell = shape.Table.Cell(1, rec + 1);//shape.Table.Columns.Count);
                                        var projectDuration = objSummaryModel.ProjectDurationList.ElementAt(rec);
                                        cell.Shape.TextFrame.TextRange.Text = projectDuration.Title;
                                    }
                                    // Delete the default column
                                    //column1.Delete();
                                    shape.Width = tableWidth;
                                    shape.Height = tableHeight;
                                }
                            }
                        }

                        if (shape.HasTextFrame == MsoTriState.msoTrue)
                        {
                            if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                            {
                                var textRange = shape.TextFrame.TextRange;
                                var text = textRange.Text;

                                if (text.IndexOf("Color_O") != -1)
                                {
                                    shape.TextFrame.TextRange.Replace("Color_O", "");//objSummaryModel.OverallStatusId.ToString());
                                    FillShapeColor(shape, objSummaryModel.OverallStatusId);
                                }

                                if (text.IndexOf("Color_Sp") != -1)
                                {
                                    shape.TextFrame.TextRange.Replace("Color_Sp", "");//objSummaryModel.ScopeId.ToString());
                                    FillShapeColor(shape, objSummaryModel.ScopeId);
                                }

                                if (text.IndexOf("Color_Sc") != -1)
                                {
                                    shape.TextFrame.TextRange.Replace("Color_Sc", "");//objSummaryModel.ScheduleId.ToString());
                                    FillShapeColor(shape, objSummaryModel.ScheduleId);
                                }

                                if (text.IndexOf("Color_R") != -1)
                                {
                                    shape.TextFrame.TextRange.Replace("Color_R", "");//objSummaryModel.ResourceId.ToString());
                                    FillShapeColor(shape, objSummaryModel.ResourceId);
                                }

                                if (text.IndexOf("Color_F") != -1)
                                {
                                    shape.TextFrame.TextRange.Replace("Color_F", "");//objSummaryModel.FinancialId.ToString());
                                    FillShapeColor(shape, objSummaryModel.FinancialId);
                                }

                                if (text.IndexOf("Slide_date") != -1)
                                    shape.TextFrame.TextRange.Replace("Slide_date", DateTime.Now.ToString("MM/dd/yyyy"));

                                if (text.IndexOf("Project_Title") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_Title", objSummaryModel.ProjectName);

                                if (text.IndexOf("Project_Owner") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_Owner", objSummaryModel.AnthemOwner);

                                if (text.IndexOf("Project_CoOwner") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_CoOwner", objSummaryModel.PartnerName);

                                if (text.IndexOf("start_Date") != -1)
                                    shape.TextFrame.TextRange.Replace("start_Date", objSummaryModel.ProjectStartDateString);

                                if (text.IndexOf("end_Date") != -1)
                                    shape.TextFrame.TextRange.Replace("end_Date", objSummaryModel.ProjectEndDateString);

                                if (text.IndexOf("perc_Completed") != -1)
                                    shape.TextFrame.TextRange.Replace("perc_Completed", Convert.ToString(objSummaryModel.ProjectComplete));

                                if (text.IndexOf("project_desc_And_Buss_Value") != -1)
                                    shape.TextFrame.TextRange.Replace("project_desc_And_Buss_Value", (!String.IsNullOrEmpty(objSummaryModel.ProjectDescription) ? ReplaceHtmlTags(objSummaryModel.ProjectDescription) : ""));

                                if (text.IndexOf("Project_ExecutionSummary") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_ExecutionSummary", (!String.IsNullOrEmpty(objSummaryModel.ProjectExecutiveSummary) ? ReplaceHtmlTags(objSummaryModel.ProjectExecutiveSummary) : ""));//"The Server Standard Platforms Program provides standard server specifications and pricing in support of:\n Technology Strategies and Planning roadmaps\nInfrastructure Lifecycle Management objectives\nIT Finance Cost Recovery goals\nDemand Management targets\nData Center Services platform Build best practices\nData Center Services platform Run fault isolation/problem determination processes\n\nEssential in providing this support is the Standard Platforms Offerings Quick Reference Guide (SPO QRG). This set of documentation maps  server, operating system, middleware, and storage speculations to costs.");

                                if (text.IndexOf("Project_accomplishments") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_accomplishments", (!String.IsNullOrEmpty(objSummaryModel.ProjectAccomplishments) ? ReplaceHtmlTags(objSummaryModel.ProjectAccomplishments) : ""));//"SPO QRG V09.02.20 published on schedule\n Updated IBM Contract Rates\nEnhanced SPO Cost Codes with OS & Middleware version\nRe-designed Engineering Extract for “One Way Ordering\"");

                                if (text.IndexOf("Project_Issues") != -1)
                                    shape.TextFrame.TextRange.Replace("Project_Issues", (!String.IsNullOrEmpty(objSummaryModel.ProjectKeyRiskIssues) ? ReplaceHtmlTags(objSummaryModel.ProjectKeyRiskIssues) : ""));// "Current documentation tool (Excel) may not be adequate to manage future requirements:\nIBM/ANTM 2015 contract added Harrisonburg and Virginia Beach to data center  options\nIBM/ANTM 2015 contract added IBM hosted cloud based services options\nService Now catalog integration requirements may be difficult to implement and maintain\nServer automated configuration tools integration requirements may be difficult to implement and maintain");

                                if (text.IndexOf("Funding_Ask") != -1)
                                    shape.TextFrame.TextRange.Replace("Funding_Ask", (!String.IsNullOrEmpty(objSummaryModel.ProjectFundingAsk) ? ReplaceHtmlTags(objSummaryModel.ProjectFundingAsk) : ""));// "Capital");

                                if (text.IndexOf("direction_Needed") != -1)
                                    shape.TextFrame.TextRange.Replace("direction_Needed", (!String.IsNullOrEmpty(objSummaryModel.ProjectDirection) ? ReplaceHtmlTags(objSummaryModel.ProjectDirection) : ""));// "Approval to develop a database SPO Catalog tool to replace the SPO Quick Reference Guide Excel workbook.");
                            }
                        }
                    }
                }

                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;

                        if (shape.HasTextFrame == MsoTriState.msoTrue)
                        {
                            if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                            {
                                var textRange = shape.TextFrame.TextRange;
                                var text = textRange.Text;

                                if (objSummaryModel.ProjectDurationList != null && objSummaryModel.ProjectDurationList.Count > 0)
                                {
                                    int recordsCount = objSummaryModel.ProjectDurationList.Count;
                                    for (int rec = 0; rec <= recordsCount - 1; rec++)
                                    {
                                        var projectDuration = objSummaryModel.ProjectDurationList.ElementAt(rec);
                                        if (projectDuration.MileStoneList != null && projectDuration.MileStoneList.Count > 0)
                                        {
                                            int j = 0;
                                            foreach (var milestone in projectDuration.MileStoneList)
                                            {
                                                if (text == "_" + Convert.ToString(rec) + Convert.ToString(j) + "dsc")
                                                {
                                                    Microsoft.Office.Interop.PowerPoint.Slide slide = presentation.Slides[1];
                                                    switch (milestone.MilestoneStatus)
                                                    {
                                                        case 1:
                                                            {
                                                                Microsoft.Office.Interop.PowerPoint.Shape pic = slide.Shapes.AddPicture(Server.MapPath("~/Temp/Template/1.jpg"), Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top, 10, 10);
                                                                break;
                                                            }
                                                        case 2:
                                                            {

                                                                Microsoft.Office.Interop.PowerPoint.Shape pic = slide.Shapes.AddPicture(Server.MapPath("~/Temp/Template/2.jpg"), Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top, 10, 10);
                                                                break;
                                                            }
                                                        case 3:
                                                            {
                                                                Microsoft.Office.Interop.PowerPoint.Shape pic = slide.Shapes.AddPicture(Server.MapPath("~/Temp/Template/3.jpg"), Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top, 10, 10);
                                                                break;
                                                            }
                                                    }
                                                    textRange.Text = "  " + milestone.Title;
                                                }
                                                j++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Remove all unused shapes
                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;

                        if (shape.HasTextFrame == MsoTriState.msoTrue)
                        {
                            if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                            {
                                var textRange = shape.TextFrame.TextRange;
                                var text = textRange.Text;

                                if (text.IndexOf("dsc") != -1)
                                {
                                    shape.TextFrame.DeleteText();
                                }
                            }
                        }
                    }
                }

                presentation.SaveAs(pptFilePath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, MsoTriState.msoTrue);
                presentation.Close();
                PowerPoint_App.Quit();
                // VPS Code Ends Here

            }

            catch (Exception ex)
            {
                pptFileName = string.Empty;
            }
            return pptFileName;
        }
Ejemplo n.º 32
0
        public void TestCleanToWithPPTApp()
        {
            return;

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

            try
            {
                AppCountMonitor monitor = new AppCountMonitor("powerpnt");
                string testDoc = TestUtils.TestFileUtils.MakeRootPathAbsolute(@"Projects\Workshare.API\Workshare.API.Tests\TestDocs\test.ppt");
                using (TempFile tf = new TempFile(testDoc))
                {
                    using (TempFile dest = new TempFile())
                    {
                        File.Delete(dest.FilePath);
                        string initialHash = tf.MD5Sum;
                        IOfficeCleaner c = new OfficeCleaner();
                        c.CleanFileTo(tf.FilePath, dest.FilePath, app);
                        Assert.IsTrue(File.Exists(dest.FilePath), "We expected the dest file to be created");
                        string newHash = dest.MD5Sum;
                        Assert.AreNotEqual(initialHash, newHash, "We expected the Cleanion to change the file contents");
                    }
                }
                Assert.IsFalse(monitor.SeenMoreInstances(), "Additional instances of PowerPoint were created during the test run - that means it didn't use the provided instance");
            }
            finally
            {
                object oFalse = false;
                app.Quit();
				Marshal.ReleaseComObject(app);
            }
        }
Ejemplo n.º 33
0
        public static void PrintDiscountCoupon(string companyName, string discountProductName, string discountValueOnProduct)
        {
            int copiesToPrint = 1;
            string printTemplateFileName = @"\Assets\Docs\PrinterReceipt.pptx";
            string qrCodeImageName = @"\Assets\Images\QREncode.jpg";
            string printFileName = @"\Assets\Docs\printReceipt.pptx";
            string printTemplateFilePath = Helper.GetAssetURI(printTemplateFileName);
            string qrCodeImagepath = Helper.GetAssetURI(qrCodeImageName);
            string printReceiptFilePath = Helper.GetAssetURI(printFileName);
            Microsoft.Office.Interop.PowerPoint.Presentation work = null;
            Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();

            try
            {
                if (File.Exists(printReceiptFilePath))
                {
                    File.Delete(printReceiptFilePath);
                }
                if (File.Exists(qrCodeImagepath))
                {
                    File.Delete(qrCodeImagepath);
                }

                Microsoft.Office.Interop.PowerPoint.Presentations presprint = app.Presentations;
                work = presprint.Open(printTemplateFilePath, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
                work.PrintOptions.PrintInBackground = Microsoft.Office.Core.MsoTriState.msoFalse;
                Microsoft.Office.Interop.PowerPoint.Slide slide = work.Slides[1];
                foreach (var item in slide.Shapes)
                {
                    var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item;

                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            var text = textRange.Text;
                            if (text.Contains("10%"))
                            {
                                text = text.Replace("10", discountValueOnProduct);
                                shape.TextFrame.TextRange.Text = text;
                            }
                            else if (text.Contains("Microsoft"))
                            {
                                text = text.Replace("Microsoft", companyName);
                                shape.TextFrame.TextRange.Text = text;
                            }
                            else if (text.Contains("Windows Phone 8"))
                            {
                                text = text.Replace("Windows Phone 8", discountProductName);
                                shape.TextFrame.TextRange.Text = text;
                            }

                        }
                    }
                    else
                    {
                        if (shape.Name.ToString() == "Picture 2")
                        {
                            shape.Delete();
                            //Add QRCode to print
                            RippleCommonUtilities.HelperMethods.GenerateQRCode("http://projectripple.azurewebsites.net/Ripple.aspx", qrCodeImagepath);
                            slide.Shapes.AddPicture(qrCodeImagepath, MsoTriState.msoFalse, MsoTriState.msoTrue, 560, 90, 80, 80);
                        }
                    }
                }

                work.SaveAs(printReceiptFilePath);
                work.PrintOut();
                work.Close();
                app.Quit();

                //delete the PrintReceipt File
                File.Delete(printReceiptFilePath);
                //Delete the QRCOde image
                File.Delete(qrCodeImagepath);
            }
            catch (System.Exception ex)
            {
                work.Close();
                app.Quit();
                //delete the PrintReceipt File
                File.Delete(printReceiptFilePath);
                //Delete the QRCOde image
                File.Delete(qrCodeImagepath);
                RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in  Print Discount Coupon at Screen side: {0}", ex.Message);
            }
        }
Ejemplo n.º 34
0
        public static void PptToHtmlFile(string PptFilePath)
        {
            //获得html文件名

            string htmlFileName = PptFilePath.Substring(0, PptFilePath.LastIndexOf(".")) + ".html";

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

            Microsoft.Office.Interop.PowerPoint.Presentation pptFile = null;

            try
            {

                //打开一个ppt文件

                pptFile = ppt.Presentations.Open(PptFilePath, Microsoft.Office.Core.MsoTriState.msoTrue,

                    Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoFalse);

                //转换成html格式

                pptFile.SaveAs(htmlFileName, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML,

                    Microsoft.Office.Core.MsoTriState.msoCTrue);

            }

            finally
            {

                if (pptFile != null)
                {

                    pptFile.Close();

                }
                ppt.Quit();
                GC.Collect();
            }
        }
Ejemplo n.º 35
0
    /// <summary>
    /// スライドを読み込む
    /// </summary>
    /// <param name="action">読み込みが完了した際のアクション</param>
    public void Init(Action <SlideDataRaw[]> action)
    {
        if (string.IsNullOrEmpty(slidePath) || string.IsNullOrEmpty(temporaryFilePath))
        {
            Debug.LogError("[SlideLoader] Invalid file path.");
            return;
        }
        if (!File.Exists(slidePath) || !Directory.Exists(temporaryFilePath))
        {
            Debug.LogError("[SlideLoader] File not found.");
            return;
        }
        var extension = Path.GetExtension(slidePath);

        if (!(extension == ".pptx" || extension == ".ppt"))
        {
            Debug.LogError("[SlideLoader] File format must be \".ppt\" or \".pptx\"");
            return;
        }

        Debug.Log("[SlideLoader] Load Slide.");
        slides = null;
        Microsoft.Office.Interop.PowerPoint.Application  app = null;
        Microsoft.Office.Interop.PowerPoint.Presentation ppt = null;

        Task.Run(() =>
        {
            try
            {
                app = new Microsoft.Office.Interop.PowerPoint.Application();

                // スライドを開く
                ppt = app.Presentations.Open(slidePath, MsoTriState.msoTrue, MsoTriState.msoFalse,
                                             MsoTriState.msoFalse);

                var width  = (int)ppt.PageSetup.SlideWidth;
                var height = (int)ppt.PageSetup.SlideHeight;

                var slideList = new List <SlideDataRaw>();

                for (var i = 1; i <= ppt.Slides.Count; i++)
                {
                    // 非表示スライドは無視
                    if (ppt.Slides[i].SlideShowTransition.Hidden == MsoTriState.msoTrue)
                    {
                        continue;
                    }

                    // コメント
                    var note = ppt.Slides[i].NotesPage.Shapes.Placeholders[2].TextFrame.TextRange.Text;
                    if (note == "")
                    {
                        continue;
                    }

                    // JPEGとして保存
                    var file = temporaryFilePath + $"/slide{i:0000}.jpg";
                    ppt.Slides[i].Export(file, "jpg", width, height);

                    slideList.Add(new SlideDataRaw()
                    {
                        note = note, imageFilePath = file
                    });
                }

                slides = slideList.ToArray();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
            finally
            {
                ppt?.Close();
                app?.Quit();
            }
        }).ContinueWith(_ =>
        {
            Debug.Log("[SlideLoader] Load completed.");
            action.Invoke(slides);
        });
    }