WPF 将PPT,Word转成图片
在Office下,PowerPoint可以直接把每张幻灯片转成图片,而Word不能直接保存图片。所以只能通过先转换成xps文件,然后再转成图片。
一、PPT 保存为图片
/// <summary> /// 将ppt转成图片 /// </summary> /// <param name="fileName"></param> private void SaveToImages(string fileName) { var presentation = _application.Presentations.Open(fileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); presentation.SaveAs(_path, PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoTrue); }
二、Word转成图片
/// <summary> /// Word转xps /// </summary> public string ConvertDocToXps(string filePath) { var application = new Microsoft.Office.Interop.Word.Application(); application.Documents.Add(filePath); var name = System.IO.Path.GetFileNameWithoutExtension(filePath) + ".xps"; var path = System.IO.Path.Combine(_path, name); try { application.ActiveDocument.ExportAsFixedFormat(path, WdExportFormat.wdExportFormatXPS); } catch (Exception) { return string.Empty; } finally { application.Documents.Close(); application.Quit(); } return filePath; }
/// <summary> /// xps 转jpg图片 /// </summary> /// <param name="path"></param> /// <param name="dirPath"></param> /// <returns></returns> public bool XpsToImages(string path, string dirPath) { if (string.IsNullOrEmpty(dirPath)) return false; if (dirPath[dirPath.Length - 1] != \'\\\') dirPath += "\\"; if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); var xpsDocument = new XpsDocument(path, FileAccess.Read); FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence(); MemoryStream[] streams = null; try { int pageCount = document.DocumentPaginator.PageCount; DocumentPage[] pages = new DocumentPage[pageCount]; for (int i = 0; i < pageCount; i++) pages[i] = document.DocumentPaginator.GetPage(i); streams = new MemoryStream[pages.Count()]; for (int i = 0; i < pages.Count(); i++) { DocumentPage source = pages[i]; streams[i] = new MemoryStream(); RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)source.Size.Width, (int)source.Size.Height, 96d, 96d, PixelFormats.Default); renderTarget.Render(source.Visual); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 100; encoder.Frames.Add(BitmapFrame.Create(renderTarget)); encoder.Save(streams[i]); FileStream file = new FileStream(dirPath + "Page_" + (i + 1) + ".jpg", FileMode.Create); file.Write(streams[i].GetBuffer(), 0, (int)streams[i].Length); file.Close(); streams[i].Position = 0; } } catch (Exception e1) { return false; } finally { if (streams != null) { foreach (MemoryStream stream in streams) { stream.Close(); stream.Dispose(); } } } return true; }