/// <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(); }
/// <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); } } }
public override void Dispose() { _presentation.Close(); Marshal.ReleaseComObject(_presentation); _application.Quit(); Marshal.ReleaseComObject(_application); }
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(); }
/// <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(); }
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) { } }
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); }
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(); }
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(); }
/// <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); }
//将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); }
/// <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); }
/// <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); }
/// <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 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); } }
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); } }
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; }
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); }
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 + " 创建完毕!"); }
/// <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); } } }
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 + " 创建完毕!"); }
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(); } }
/// <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; }