public ResponseModel ConvertPptToPdf(string fileLocation, string outLocation) { Microsoft.Office.Interop.PowerPoint.Application app = null; Presentations presentations = null; Presentation presentation = null; try { if (!File.Exists(outLocation)) { app = new Microsoft.Office.Interop.PowerPoint.Application { Visible = MsoTriState.msoTrue }; presentations = app.Presentations; presentation = presentations.Open(fileLocation, ReadOnly: MsoTriState.msoCTrue); presentation.ExportAsFixedFormat(outLocation, PpFixedFormatType.ppFixedFormatTypePDF); Marshal.ReleaseComObject(presentations); presentation.Close(); Marshal.ReleaseComObject(presentation); app.Quit(); Marshal.ReleaseComObject(app); } else { return(new ResponseModel { IsSucceed = false, ErrorMessage = outLocation + " file-ı artıq mövcuddur." }); } if (!File.Exists(outLocation)) { return(new ResponseModel { IsSucceed = false, ErrorMessage = outLocation + " file-ı tapılmadı." }); } return(new ResponseModel { Data = outLocation, IsSucceed = true, ErrorMessage = string.Empty }); } catch (Exception e) { Marshal.ReleaseComObject(presentations); presentation.Close(); Marshal.ReleaseComObject(presentation); app.Quit(); Marshal.ReleaseComObject(app); return(new ResponseModel { IsSucceed = false, ErrorMessage = "File convert oluna bilmədi: " + e.Message }); } }
public void Hightlight() { try { var app = new Microsoft.Office.Interop.PowerPoint.Application(); var pres = app.Presentations; Presentation file = pres.Open(fileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); //Presentation presentation = Globals.ThisAddIn.Application.ActivePresentation; // file.SaveCopyAs(copyFileName, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue); try { int slideCount = file.Slides.Count; for (int i = 1; i <= slideCount; i++) { Slide slide = file.Slides[i]; slide.FollowMasterBackground = MsoTriState.msoFalse; foreach (var item in slide.Shapes) { var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item; if (shape.HasTextFrame == MsoTriState.msoTrue) { //shape.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToWin32(Color.Red); var textRange = shape.TextFrame.TextRange; var text = textRange.Text; Console.WriteLine("text:" + text); int index = text.IndexOf(textToFind); if (index >= 0) { Console.WriteLine("found"); shape.TextFrame.TextRange.Font.Color.RGB = BGR(Color.Green); } } } } file.Save(); file.SaveAs(@"C:\Users\xlian\MyPapers\Simmons\tested.pptx", PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue); file.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); file.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
void PresenterInterface.StartPresintation() { Application ppApp = new Application(); ppApp.Visible = MsoTriState.msoTrue; Presentations ppPresens = ppApp.Presentations; Presentation objPres = ppPresens.Open(@"E:\\courseWork\\CourseProject\\CourseWork\\CourseWork\\exports\\presentation.pptx", MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue); Slides objSlides = objPres.Slides; int n = objSlides.Count; //получаю количество слайдов в показываемой презентации SlideShowWindows objSSWs; SlideShowSettings objSSS; objSSS = objPres.SlideShowSettings; objSSS.EndingSlide = n - 2; objSSS.Run(); objSSWs = ppApp.SlideShowWindows; Thread.Sleep(n * 5000);// пауза между слайдами так как 1 секунда переход 2 секунды слайд objPres.Close(); ppApp.Quit(); //закрываем потоки var processes = System.Diagnostics.Process.GetProcessesByName("POWERPNT"); foreach (var p in processes) { p.Kill(); } }
//Export a summary Presentation with all the pages present in a category //The summar is composed by an index (optional) and a slide for each page //the slide content will be detemined by the expDetail delegate public void ExportSummary(string expCat, string outFileName, string expIdxName, int expPaging, ExportProc expDetail, WikiMedia.ExportNotify expNotify) { Presentation pres = new Presentation(fTemplatePath); PageList pl = wiki.GetPages(expCat); if (expIdxName != null) { Index2Slide(pres, pl, expIdxName, expPaging); } foreach (Page page in pl) { string title = GetTitle(page); if (title == null) { continue; } if (expNotify != null) { expNotify(page.title); } page.LoadHTML(); Document doc = HTML2Model.Convert(page.text); expDetail(pres, doc, title); } pres.Save(fBasePath + outFileName); pres.Close(); }
public void quitPresentation(Presentation presentation) { //Reenable Office Assisant, if it was on: if (this.powerpoint == null) { return; } if (this.powerpoint.Presentations.Count == 0) { return; } if (presentation == null) { return; } //if (this.bAssistantOn) //{ // this.powerpoint.Assistant.On = true; // this.powerpoint.Assistant.Visible = false; //} presentation.Close(); if (presentation == this.presentation) { this.presentation = null; } }
private void Button_Split_Click(object sender, EventArgs e) { if (DialogResult.OK == ChooseFolder.ShowDialog()) { Cursor = Cursors.WaitCursor; Microsoft.Office.Interop.PowerPoint.Application A = new Microsoft.Office.Interop.PowerPoint.Application(); foreach (string file in MyFiles) { FileInfo F = new FileInfo(file); string Name = F.Name; Presentation P = A.Presentations.Open(file, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); for (int i = 1; i <= P.Slides.Count; i++) { P.Slides[i].Copy(); Presentation P1 = A.Presentations.Add(MsoTriState.msoFalse); P1.Slides.Paste(1); P1.Slides[1].FollowMasterBackground = MsoTriState.msoFalse; P1.SaveAs(ChooseFolder.SelectedPath + "\\" + i.ToString() + "_" + Name, PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoFalse); P1.Close(); } P.Close(); } Cursor = Cursors.Default; } }
public void createFile(string filepath) { if (filepath.EndsWith(".xlsx")) { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook ExcelWorkBook = null; ExcelApp.Visible = false; ExcelApp.DisplayAlerts = false; ExcelWorkBook = ExcelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); ExcelWorkBook.SaveAs(filepath); ExcelWorkBook.Close(); ExcelApp.Quit(); } else if (filepath.EndsWith(".pptx")) { Application pptApplication = new Application(); // Create the Presentation File Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue); Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText]; Microsoft.Office.Interop.PowerPoint.Slides slides = pptPresentation.Slides; Microsoft.Office.Interop.PowerPoint.Slide slide = slides.AddSlide(1, customLayout); pptPresentation.SaveAs(filepath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue); pptPresentation.Close(); pptApplication.Quit(); } else { File.Create(filepath).Close(); } }
private void OutputImageFiles(string fileName) { Directory.CreateDirectory(OutputPath); Microsoft.Office.Interop.PowerPoint.Application app = null; Presentation ppt = null; try { app = new Microsoft.Office.Interop.PowerPoint.Application(); ppt = app.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); int width = DefaultWidth * 2; int height = DefaultHeight * 2; totalSlideNum = ppt.Slides.Count; for (int i = 1; i <= totalSlideNum; i++) { string output = OutputPath + String.Format("/slide{0:0000}.jpg", i - 1); ppt.Slides[i].Export(output, "jpg", width, height); } } finally { if (ppt != null) { ppt.Close(); } if (app != null) { app.Quit(); app = null; } } }
public static void Convert(String file, String safeFile) { Powerpoint.Application PP; Powerpoint.Presentation Presentation; PP = new Powerpoint.ApplicationClass(); // ... var presentations = PP.Presentations; Presentation = presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue); // Voor elke slide, exporteren // ... // 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 void PPTAs(string infile, string outfile, PpSaveAsFileType targetFileType) { object missing = Type.Missing; Presentation persentation = null; PowerPoint.Application pptApp = null; try { pptApp = new PowerPoint.Application(); persentation = pptApp.Presentations.Open(infile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); persentation.SaveAs(outfile, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue); } catch (Exception ex) { log.ErrorFormat("PPT {0} 转换出错,异常信息: {1}", infile, ex.Message); } finally { if (persentation != null) { persentation.Close(); persentation = null; } if (pptApp != null) { pptApp.Quit(); pptApp = null; } } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); }
/************************** FINAL PPT-to-Image ***************************** * http://www.free-power-point-templates.com/articles/c-code-to-convert-powerpoint-to-image/ */ public void ppt2Image(string pptfilePath, string exportPath, string prefix) { Console.WriteLine("PPT File Location:" + pptfilePath); Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application(); Presentation pptPresentation = pptApplication.Presentations .Open(pptfilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); int pageWidth = 800; int pageHeight = (int)(pageWidth / pptPresentation.PageSetup.SlideWidth * pptPresentation.PageSetup.SlideHeight); Console.WriteLine("w/H" + pageWidth + ":" + pageHeight); //slides to image int slide_count = pptPresentation.Slides.Count; Console.Write("count=" + slide_count); for (int i = 1; i <= slide_count; ++i) { /* full HD*/ pptPresentation.Slides[i].Export(exportPath + @"\" + "slide" + i + ".png", "png", pageWidth, pageHeight); /* Thumbnail*/ pptPresentation.Slides[i].Export(exportPath + @"\" + "thumb.slide" + i + ".png", "png", pageWidth / 2, pageHeight / 2); } ppt2ContentImages(pptPresentation, exportPath.Replace(@"\ppt-img", @"\" + "content-img")); pptPresentation.Close(); }
private void StripSheets(Presentation curCopy, List <int> sheetNumbers, string department) { List <Slide> doNotDelete = new List <Slide>(); foreach (int number in sheetNumbers) { var slide = curCopy.Slides[number]; doNotDelete.Add(slide); } List <Slide> SlidesToDelete = new List <Slide>(); for (int i = 1; i < curCopy.Slides.Count + 1; i++) { Slide cur = curCopy.Slides[i]; if (!doNotDelete.Contains(cur)) { SlidesToDelete.Add(cur); } } SlidesToDelete.ForEach(s => s.Delete()); curCopy.SaveAs(department + ".pptx"); curCopy.Close(); //File.Delete(department + "_raw.pptx"); }
//Export all the pages in a Wiki category into a index presentation, each page //will contain up to expPagining summaries. A summary will be composed up to //descSize characters taken from the first Header of the Page public void ExportIndex(string expCat, string outFileName, int expPaging, int descSize, WikiMedia.ExportNotify expNotify) { Microsoft.Office.Interop.PowerPoint.Slide slide = null; Microsoft.Office.Interop.PowerPoint.TextRange textRange = null; Presentation pres = new Presentation(fTemplatePath); PageList pl = wiki.GetPages(expCat); int cnt = 0; foreach (Page page in pl) { string title = GetTitle(page); if (title == null) { continue; } cnt++; if ((cnt % expPaging) == 1) { slide = pres.Add(Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText, GetTitleName(expCat)); textRange = slide.Shapes[2].TextFrame.TextRange; } if (expNotify != null) { expNotify(page.title); } page.LoadHTML(); Document doc = HTML2Model.Convert(page.text); AddFirstHeader(textRange, doc, page, title, descSize); } pres.Save(fBasePath + outFileName); pres.Close(); }
public static String ConvertToIMAGE(String filePath, String destPath) { Application app = new Application(); Presentation presentation = app.Presentations.Open2007(filePath, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoFalse , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse); presentation.SaveAs(destPath, PpSaveAsFileType.ppSaveAsJPG); presentation.Close(); app.Quit(); // rename List <String> list = new List <string>(); String[] fileNames = Directory.GetFiles(destPath); Regex regex = new Regex("\\d+"); foreach (var fileName in fileNames) { String newFileName = Path.Combine(Path.GetDirectoryName(fileName), regex.Match(Path.GetFileNameWithoutExtension(fileName)).Value + Path.GetExtension(fileName).ToLower()); File.Move(fileName, newFileName); Console.WriteLine(newFileName); list.Add(newFileName); } return(destPath); }
/// <summary> /// 清理资源 /// </summary> /// <param name="applicationObject"></param> /// <param name="presentationObject"></param> private void Dispose(object applicationObject, object presentationObject) { Application app = (Application)applicationObject; Presentation pp = (Presentation)presentationObject; try { if (pp != null) { pp.Close(); Marshal.ReleaseComObject(pp); } if (app != null) { app.Quit(); Marshal.ReleaseComObject(app); } } catch (Exception ex) { // 当 app or pp 带着异常进入时,这里可能再次抛出异常。 // 如:上文中的 -2147467262 异常。 Trace.WriteLine($"ppttoenbx:Error When Dispose. 异常信息可能是重复的-{ex.Message}"); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); }
/************************** FINAL PPT- Content Images - Extract ***************************** * //slide extract image content * // https://stackoverflow.com/questions/4990825/export-movies-from-powerpoint-to-file-in-c-sharp * //https://stackoverflow.com/questions/42442659/c-sharp-save-ppt-shape-msopicture-as-image-w-office-interop */ public void pptContentExtract(string src_pptfilePath, string exportPath, string prefix) { Console.WriteLine("PPT File Location:" + src_pptfilePath); Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application(); Presentation pptPresentation = pptApplication.Presentations .Open(src_pptfilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); foreach (PowerPoint.Slide slide in pptPresentation.Slides) { PowerPoint.Shapes slideShapes = slide.Shapes; int count = 0; foreach (PowerPoint.Shape shape in slideShapes) { if (shape.Type == MsoShapeType.msoPicture) { //LinkFormat.SourceFullName contains the movie path //get the path like this shape.Export(exportPath + @"\" + "content" + slide.SlideNumber + "_" + count++ + ".png", Microsoft.Office.Interop.PowerPoint.PpShapeFormat.ppShapeFormatPNG); Console.WriteLine("Exported" + exportPath + @"\" + "content" + slide.SlideNumber + "_" + count++ + ".png"); //System.IO.File.Copy(shape.LinkFormat.SourceFullName, path + imageBase + @"\" + "content" + slide.SlideNumber + "_"+ count++ + ".png"); } } } pptPresentation.Close(); }
public override List <Item> ExtractLinks(object file) { List <Item> results = null; Application app = null; Presentation presentation = null; try { app = new Application(); presentation = app.Presentations.Open(file.ToString(), MsoTriState.msoCTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); results = ParseSlides(presentation); } catch (Exception ex) { ColorConsole.WriteLine(ex.Message.White().OnRed()); } finally { presentation?.Close(); presentation?.NAR(); app?.Quit(); app?.NAR(); } ColorConsole.WriteLine(Environment.NewLine); return(results); }
/// <summary>生成PDF文件</summary> public override bool Execute(string sourceFile, string destFile) { ApplicationClass application = null; Presentation persentation = null; try { application = new ApplicationClass(); persentation = application.Presentations.Open(sourceFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); persentation.ExportAsFixedFormat(destFile, PpFixedFormatType.ppFixedFormatTypePDF); //persentation.SaveAs(destFile, PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue); } finally { if (persentation != null) { persentation.Close(); Marshal.ReleaseComObject(persentation); } if (application != null) { application.Quit(); Marshal.ReleaseComObject(application); } } return(true); }
private void Button_Save_Click(object sender, EventArgs e) { string[] files = Text_InputFiles.Text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string file in files) { FileInfo F = new FileInfo(file); if (!F.Exists) { MessageBox.Show("File does not exist " + file, "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (F.Extension.ToLower() != ".ppt" && F.Extension.ToLower() != ".pptx") { MessageBox.Show("This is not a ppt/pptx " + file, "Not PPT/PPTX", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if (DialogResult.OK == SaveFile.ShowDialog()) { Cursor.Current = Cursors.WaitCursor; mi_Pres1 = (Presentation)mi_App.Presentations.Add(MsoTriState.msoFalse); foreach (string file in files) { AppendFile(file); } mi_Pres1.SaveAs(SaveFile.FileName, PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoFalse); mi_Pres1.Close(); Cursor.Current = Cursors.Default; } }
public static void ExecuteExtraction(string sourceFileName, string destFileName) { Application _application = new Microsoft.Office.Interop.PowerPoint.Application(); var pres = _application.Presentations; Presentation pptFile = pres.Open(sourceFileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); string storeContent = ""; int slideCount = pptFile.Slides.Count; for (int i = 1; i <= slideCount; i++) { Slide slide = pptFile.Slides[i]; slide.FollowMasterBackground = MsoTriState.msoFalse; foreach (var item in slide.Shapes) { var shape = (Microsoft.Office.Interop.PowerPoint.Shape)item; if (shape.HasTextFrame == MsoTriState.msoTrue) { //shape.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToWin32(Color.Red); var textRange = shape.TextFrame.TextRange; var text = textRange.Text; storeContent += text + " "; } } } FileOperators.FileWrite(destFileName, storeContent); pptFile.Close(); _application.Quit(); }
public List <ISlideData> FetchPresentationData(string pathToPresentation) { Presentation presentation = App.Presentations.Open(pathToPresentation, WithWindow: MsoTriState.msoFalse); List <ISlideData> slideData = presentation.Slides.Cast <Slide>().Select(SlideData.FromSlide).ToList(); presentation.Close(); return(slideData); }
private void savePresentation(Presentation presentation) { string fileName = string.Format(@"C:\temp\newsletter-{0}.pptx", DateTime.Now.ToString("yyyyMMdd-mmHH")); presentation.SaveAs(fileName, PpSaveAsFileType.ppSaveAsOpenXMLPresentation, MsoTriState.msoTriStateMixed); presentation.Close(); }
public static void CloseReport(string outputFile, int slideIndex = 1) { pptPresentation.Slides[slideIndex].Delete(); //pptPresentation.SaveCopyAs(outputFile, PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue); pptPresentation.Save(); pptPresentation.Close(); pptApplication.Quit(); //Marshal.FinalReleaseComObject(pptApplication); }
/// <summary> /// Close Powerpoint process /// </summary> public void ClosePowerPoint() { try { oSlideShowView.Exit(); objPres.Close(); oPPT.Quit(); } catch (Exception) { } }
public Generate_PPT(string Title, string text, string FullOutputPath, string[] imageLinks) { //Initialize variables Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application(); Microsoft.Office.Interop.PowerPoint.Slides slides; Microsoft.Office.Interop.PowerPoint._Slide slide; Microsoft.Office.Interop.PowerPoint.TextRange objText; // Create the Presentation File - msoFalse to hide presentation Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoFalse); Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText]; // Create new Slide slides = pptPresentation.Slides; slide = slides.AddSlide(1, customLayout); // Add title objText = slide.Shapes[1].TextFrame.TextRange; objText.Text = Title; objText.Font.Name = "Arial"; objText.Font.Size = 32; // Add text Clipboard.SetData(DataFormats.Rtf, text); Microsoft.Office.Interop.PowerPoint.TextFrame tf = slide.Shapes[2].TextFrame; Microsoft.Office.Interop.PowerPoint.TextRange tr = tf.TextRange; tr.PasteSpecial(PpPasteDataType.ppPasteRTF); //Add images Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2]; int i = 1; foreach (string image in imageLinks) { if (i == 1) { slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left + (shape.Width / 2), shape.Top, shape.Width / 2, shape.Height / 2); } else if (i == 2) { slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left, shape.Top + (shape.Height / 2), shape.Width / 2, shape.Height / 2); } else if (i == 3) { slide.Shapes.AddPicture(image, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, shape.Left + (shape.Width / 2), shape.Top + (shape.Height / 2), shape.Width / 2, shape.Height / 2); } i++; } //save PPT and close pptPresentation.SaveAs(FullOutputPath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue); pptPresentation.Close(); pptApplication.Quit(); }
private void SaveAsPptx(string strFolder) { var files = Directory.GetFiles(strFolder).Where(f => f.EndsWith(".doc") && !f.Contains("~$")).ToArray(); foreach (string file in files) { Presentation pres = _application.Presentations.Open(file); pres.SaveAs(file.Replace(".ppt", ".pptx")); pres.Close(); } }
private void Close(Presentation doc) { try { doc.Close(); } catch (Exception ex) { _logger.ErrorFormat(ex, "Unable to close presentation {0}", ex.Message); } }
public void Stop() { if (_presentation != null) { _presentation.Close(); } if (_pptApp != null) { _pptApp.Quit(); } }
/// <summary> /// 转换ppt文档成Html文档 /// </summary> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> /// <returns></returns> public static ConvertResult PptToHtml(string sourcePath, string targetPath) { try { #region 先转换为图片,再由图片组成Html页面 var sourceFile = new FileInfo(sourcePath); var powerPoint = new Microsoft.Office.Interop.PowerPoint.Application(); Presentation open = powerPoint.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); //注意:有些版本的PowerPoint(如:Office 2013 Professional)不能保存为Html, //所以,先保存为图片,再由图片组成一个Html页面来预览 open.SaveAs(targetPath, PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue); var targetDirPath = new DirectoryInfo(string.Format("{0}\\{1}", Path.GetDirectoryName(targetPath), sourceFile.Name)); const string template = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <meta http-equiv=Content-Type content='text/html; charset=gbk'> {0} <head> <title>{1}</title> </head> <body> <div class='file_content'> {2} </div> </body> </html>"; var images = new StringBuilder(); foreach (FileInfo file in targetDirPath.GetFiles()) { images.AppendFormat("<p class='images'><img class='pptImages' src='{0}/{1}' /></p>{2}", targetDirPath.Name, file.Name, Environment.NewLine); } WriteFile(targetPath, string.Format(template, CommonFileInclude, sourceFile, images)); open.Close(); powerPoint.Quit(); return(new ConvertResult { IsSuccess = true, Message = targetPath }); #endregion } catch (Exception ex) { Log("转换PPT文档成Html文档时异常", ex.Message + ex.StackTrace); return(new ConvertResult { IsSuccess = false, Message = ex.Message + ex.StackTrace }); } }
private static void ConvertToPdfIfNeeded(XmlCastReport arguments, ref string reportPath, string tmpReportFile) { // convert docx or pptx to pdf if (reportPath.Contains(".pdf")) { if (tmpReportFile.Contains(".docx")) { try { Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); Document wordDocument = appWord.Documents.Open(tmpReportFile); wordDocument.ExportAsFixedFormat(reportPath, WdExportFormat.wdExportFormatPDF); wordDocument.Close(); appWord.Quit(); } catch (Exception e) { // Error if office not installed, then do not save as pdf LogHelper.Instance.LogWarn("Report cannot be saved as pdf : " + e.Message); reportPath = reportPath.Replace(".pdf", Path.GetExtension(arguments.Template.Name)); File.Copy(tmpReportFile, reportPath, true); } } else if (tmpReportFile.Contains(".pptx")) { try { Microsoft.Office.Interop.PowerPoint.Application appPowerpoint = new Microsoft.Office.Interop.PowerPoint.Application(); Presentation appPres = appPowerpoint.Presentations.Open(tmpReportFile); appPres.ExportAsFixedFormat(reportPath, PpFixedFormatType.ppFixedFormatTypePDF); appPres.Close(); appPowerpoint.Quit(); } catch (Exception e) { // Error if office not installed, then do not save as pdf LogHelper.Instance.LogWarn("Report cannot be saved as pdf : " + e.Message); reportPath = reportPath.Replace(".pdf", Path.GetExtension(arguments.Template.Name)); File.Copy(tmpReportFile, reportPath, true); } } else { string report = reportPath.Replace(".pdf", Path.GetExtension(arguments.Template.Name)); File.Copy(tmpReportFile, report, true); } } else { //Copy report file to the selected destination File.Copy(tmpReportFile, reportPath, true); } }
/* private void TestAppend() { mi_App = new Microsoft.Office.Interop.PowerPoint.Application(); mi_Pres1 = mi_App.Presentations.Open(@"D:\Visual Studio 2008\Projects\JoinPPT\JoinPPT\bin\Debug\File1.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); mi_Pres2 = mi_App.Presentations.Open(@"D:\Visual Studio 2008\Projects\JoinPPT\JoinPPT\bin\Debug\File2.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); for (int i = 1; i <= mi_Pres2.Slides.Count; i++) { mi_Pres2.Slides[i].Copy(); mi_Pres1.Slides.Paste(mi_Pres1.Slides.Count+1); mi_Pres1.Slides[mi_Pres1.Slides.Count].FollowMasterBackground = MsoTriState.msoFalse; } mi_Pres1.SaveAs(@"D:\Visual Studio 2008\Projects\JoinPPT\JoinPPT\bin\Debug\File3.pptx", PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue); mi_Pres1.Close(); mi_Pres2.Close(); } */ private void AppendFile(string file) { mi_Pres2 = mi_App.Presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); for (int i = 1; i <= mi_Pres2.Slides.Count; i++) { mi_Pres2.Slides[i].Copy(); mi_Pres1.Slides.Paste(mi_Pres1.Slides.Count + 1); mi_Pres1.Slides[mi_Pres1.Slides.Count].FollowMasterBackground = MsoTriState.msoFalse; } mi_Pres2.Close(); }
public void quitPresentation(Presentation presentation) { //Reenable Office Assisant, if it was on: if (this.powerpoint == null) return; if (this.powerpoint.Presentations.Count == 0) return; if (presentation == null) return; //if (this.bAssistantOn) //{ // this.powerpoint.Assistant.On = true; // this.powerpoint.Assistant.Visible = false; //} presentation.Close(); if (presentation == this.presentation) this.presentation = null; }