/// <summary> /// Export a slide to the specified image format /// </summary> /// <param name="slide">PPT.Slide object instance</param> /// <param name="filePathAndName">File and Path name for the export target</param> /// <param name="exportFormat">Format to export to</param> /// <param name="scaleWidth">Scale with of the image</param> /// <param name="scaleHeight">Scale height of the image</param> public void Export( PPT.Slide slide, string filePathAndName, ImageFormats.Formats exportFormat, int scaleWidth = 1280, int scaleHeight = 1024) { slide.Export(filePathAndName, exportFormat.ToString(), scaleWidth, scaleHeight); }
/// <summary> /// Nhập đối tượng tài liệu PowerPoint /// </summary> /// <param name="_page"></param> /// <param name="_slide"></param> public void ObjectsInSlides(NormalPage _page, pp.Slide _slide, int count) { HelperClass helperClass = new HelperClass(); //----Hiệu ứng trang helperClass.GetTransition(_slide, _page); //---Chọn kiểu hiệu ứng trang và hướng chiếu //-- Thiết lập hình nền màu nền => quy ra ảnh nền object để lấy cả chủ đề, dải màu//loop: Tránh vòng lặp vô hạn int loop = 0; while (_slide.Shapes.Count > 0) { if (loop > 200) { loop = 0; goto BreakLoop; } else { _slide.Shapes[1].Delete(); loop++; } } BreakLoop: try { string PathBackground = Path.Combine((System.Windows.Application.Current as IAppGlobal).DocumentTempFolder, "Slide_" + DateTime.Now.Ticks.ToString() + ".png"); _slide.Export(PathBackground, "png"); if (File.Exists(PathBackground)) { ImageColor imgColor = new ImageColor(); imgColor.Source = new Image(); imgColor.Source.OpenFile(PathBackground, false); _page.MainLayer.Background = imgColor; } } catch (Exception ex) { } }
public async Task <string> captureWindow() { /* * Rectangle bounds = this.Bounds; * using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) * { * using (Graphics g = Graphics.FromImage(bitmap)) * { * g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); * } * bitmap.Save("C://test.jpg", ImageFormat.Jpeg); * } */ if (slide == null) { return(null); } String destDir = Path.GetTempPath(); String dest = Path.Combine(destDir, slide.SlideIndex + ".png"); slide.Export(dest, "png", 320, 240); logger.Debug("save ppt into " + dest); return(dest); }
public static void exportImg2(string path) { Log.Info("PPT.exportImg path=" + path); string name = Path.GetFileName(path); string dir = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (name.IndexOf("ppt") < 0 && name.IndexOf("PPT") < 0) { return; } string imgpath2 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + 2 + ".jpg"; string imgpath3 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + 3 + ".jpg"; if (File.Exists(imgpath2) && File.Exists(imgpath3)) { return; } POWERPOINT.Application app = null; POWERPOINT.Presentation pre = null; try { app = new POWERPOINT.Application(); #region check ppt or pptx try { pre = app.Presentations.Open(path, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse); } catch (Exception e1) { Log.Info("Presentations.Open exception. " + e1 + ", " + path); } #endregion POWERPOINT.Slides slides = pre.Slides; int pageTotal = pre.Slides.Count; IEnumerator e = slides.GetEnumerator(); int i = 0; while (e.MoveNext()) { i++; PPT.Slide slide = (PPT.Slide)e.Current; string imgpath = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + i + ".jpg"; slide.Export(imgpath, "jpg", 400, 300); } } catch (Exception e1) { Log.Info("exportImg1 exception: " + e1.Message); } finally { try { if (pre != null) { pre.Close(); pre = null; } } catch (Exception e2) { Log.Info("exportImg2 exception: " + e2.Message); } app = null; } Log.Info("PPT.exportImg over. name=" + name); }
public static void exportImg(string path) { Log.Info("PPT.exportImg path=" + path); string name = Path.GetFileName(path); string dir = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (name.IndexOf("ppt") < 0 && name.IndexOf("PPT") < 0) { return; } if (g_fileImgStatus.Contains(name)) { g_fileImgStatus.Remove(name); } g_fileImgStatus.Add(name, 0);//正在导入 POWERPOINT.Application app = null; POWERPOINT.Presentation pre = null; try { app = new POWERPOINT.Application(); #region check ppt or pptx try{ pre = app.Presentations.Open(path, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse); }catch (Exception e1) { Log.Info("Presentations.Open exception. " + e1 + "," + path); if (g_fileImgStatus.Contains(name)) { g_fileImgStatus.Remove(name); g_fileImgStatus.Add(name, 1); } Form1.DeleteFile(name); MessageBox.Show("打开" + path + "失败,请检查该文件!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); app = null; } #endregion Log.Info("Presentations.Open succeed. " + name); POWERPOINT.Slides slides = pre.Slides; int pageTotal = pre.Slides.Count; bool bOver = true; for (int k = 1; k <= pageTotal; k++) { string imgpath1 = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + k + ".jpg"; if (!File.Exists(imgpath1)) { bOver = false; } } if (bOver) { try { if (pre != null) { pre.Close(); pre = null; } } catch (Exception e2) { Log.Info("exportImg2 exception: " + e2.Message); } app = null; return; } IEnumerator e = slides.GetEnumerator(); int i = 0; while (e.MoveNext()) { i++; PPT.Slide slide = (PPT.Slide)e.Current; string imgpath = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + name + "_" + i + ".jpg"; slide.Export(imgpath, "jpg", 400, 300); } } catch (Exception e1) { Log.Info("exportImg1 exception: " + e1.Message); } finally { if (g_fileImgStatus.Contains(name)) { g_fileImgStatus.Remove(name); g_fileImgStatus.Add(name, 1); } try { if (pre != null) { pre.Close(); pre = null; } } catch (Exception e2) { Log.Info("exportImg2 exception: " + e2.Message); } app = null; } Log.Info("PPT.exportImg over. name=" + name); }
/// <summary> /// Scans pptx file starting slide with specified index /// <para>Can throw exceptions from inner calls.</para> /// </summary> /// <param name="pptPresentation"></param> /// <param name="startIndex"></param> /// <returns></returns> public List <IFileItem> UpdateIndex(PPT.Presentation pptPresentation, int startIndex) { PPT.Slide slide = null; dynamic addin = null; string tempIndexFile = null; List <string> tempFilesToDelete = new List <string>(); try { List <IFileItem> newItems = new List <IFileItem>(); string tempImgFile = null; addin = GetAddin(); tempIndexFile = Path.GetTempFileName(); using (FileStream zipFile = new FileStream(indexFileFullName, FileMode.Open)) { using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Update)) { ZipArchiveEntry indexFileEntry = zip.GetEntry(ZIPEntry_IndexFileName); indexFileEntry.ExtractToFile(tempIndexFile, true); PPT.Slides gSlides = pptPresentation.Slides; for (int idx = startIndex; idx <= gSlides.Count; idx++) { slide = gSlides[idx]; bool isShapeItem = slide.Tags[ShapeTag.Tag] != ""; #region Collect Item Data string title = ""; StringBuilder sbKeyWords = new StringBuilder(); StringBuilder sbChartType = new StringBuilder(); StringBuilder sbDescr = new StringBuilder(); int chartsCount = 0; if (isShapeItem) { try { PPT.Shape shape = slide.Shapes[1]; //If it is the Shape we expect it to be the only shape on this slide if (addin?.IsExcelChart(shape) ?? false) { chartsCount++; #region Get Chart Description string[] str = addin.GetChartDescription(shape); } #endregion Get MG Chart Description else { //TODO: Get something from non chart shape title = shape.Title.Replace("\n", " ").Replace(" ", " "); sbKeyWords.Append(shape.Name); } } catch (Exception ex) { } } else { //Slide foreach (PPT.Shape shape in slide.Shapes) { try { if (shape.Name == "Title 1" && title == "") { PPT.TextFrame frame = shape.TextFrame; PPT.TextRange txt = frame.TextRange; title = txt.Text.Replace("\n", " ").Replace(" ", " "); txt = null; frame = null; } if (addin?.IsExceloChart(shape) ?? false) { chartsCount++; } } catch { } } } sbKeyWords.Append(title); sbKeyWords.Append(" "); tempImgFile = Path.GetTempFileName(); float ratio = pptPresentation.PageSetup.SlideHeight / pptPresentation.PageSetup.SlideWidth; slide.Export(tempImgFile, "png", ThumbnailWidth, (int)(ThumbnailWidth * ratio)); zip.CreateEntryFromFile(tempImgFile, ZIPEntry_ImagesFolder + idx + ".png"); Bitmap img = null; using (var fs = new System.IO.FileStream(tempImgFile, System.IO.FileMode.Open)) { img = new Bitmap(fs); } sbChartType.Replace("\n", " "); #endregion IFileItem item = LibraryFile.CreateItem(idx); { item.Image = img; item.Type = ( (Func <ItemType>)(() => { if (isShapeItem) { return(chartsCount == 0 ? ItemType.Shape : ItemType.Chart); } else { // if (mgChartsCount == 0) { return(ItemType.Slide); } // else // { // return mgChartsCount > 1 ? ItemType.SlideWithMultipleCharts : ItemType.SlideWithChart; // } } }) )(); item.ShapesCount = chartsCount; item.Title = title; item.Description = sbDescr.ToString(); item.Keywords = sbKeyWords.ToString(); //TODO: item.ChartType = sbChartType.ToString(); } newItems.Add(item); slide = null; } items.AddRange(newItems); Save(newItems, tempIndexFile); indexFileEntry.Delete(); zip.CreateEntryFromFile(tempIndexFile, ZIPEntry_IndexFileName); } //using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Update)) } //using (FileStream zipFile = new FileStream(indexFilePath, FileMode.Open)) return(newItems); } finally { addin = null; slide.ReleaseCOM(); slide = null; pptPresentation = null; try { if (tempIndexFile != null) { File.Delete(tempIndexFile); } foreach (string path in tempFilesToDelete) { File.Delete(path); } } catch { } } }
// 感谢ok群群友 yuanyilvhua(QQ:4570848**)提供测试电脑,以修复之前存在的高分屏下的bug :-) private void button2_Click(object sender, EventArgs e) { PowerPoint.Selection sel = app.ActiveWindow.Selection; if (sel.Type == PowerPoint.PpSelectionType.ppSelectionSlides && sel.SlideRange.Count > 1) { PowerPoint.Slides slides = app.ActivePresentation.Slides; PowerPoint.SlideRange srange = sel.SlideRange; int scount = srange.Count; float wp = app.ActivePresentation.PageSetup.SlideWidth; float hp = app.ActivePresentation.PageSetup.SlideHeight; int pw = Properties.Settings.Default.pwidth; int h2 = (int)(pw * hp / wp); string name = app.ActivePresentation.Name; if (name.Contains(".pptx")) { name = name.Replace(".pptx", ""); } if (name.Contains(".ppt")) { name = name.Replace(".ppt", ""); } string cPath = app.ActivePresentation.Path + @"\" + name + @" 的GIF图\"; if (!Directory.Exists(cPath)) { Directory.CreateDirectory(cPath); } System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(cPath); int k = dir.GetFiles().Length + 1; string gpath = cPath + name + "_" + k + ".gif"; int time = int.Parse(textBox1.Text.Trim()); int[] index = new int[srange.Count]; for (int i = 1; i <= srange.Count; i++) { index[i - 1] = srange[i].SlideIndex; } if (index[0] > index[1]) { Array.Sort(index); } sel.Unselect(); slides.Range(index).Select(); List <string> path = new List <string>(); for (int i = 1; i <= scount; i++) { PowerPoint.Slide nslide = slides[index[i - 1]]; string cPath2 = cPath + name + "_" + k + ".jpg"; nslide.Export(cPath2, "jpg"); path.Add(cPath2); k = k + 1; } AnimatedGifEncoder gif = new AnimatedGifEncoder(); gif.Start(gpath); gif.SetDelay(time); if (checkBox1.Checked) { gif.SetRepeat(0); } else { gif.SetRepeat(-1); } Bitmap bmp = null; Graphics g = null; for (int j = 0; j < scount; j++) { Image spic = Image.FromFile(path[j]); if (j == 0) { bmp = new Bitmap(spic.Width, spic.Height); bmp.SetResolution(spic.HorizontalResolution, spic.VerticalResolution); g = Graphics.FromImage(bmp); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; } g.Clear(panel1.BackColor); g.DrawImage(spic, 0, 0); gif.AddFrame(bmp); spic.Dispose(); File.Delete(path[j]); } gif.Finish(); g.Dispose(); bmp.Dispose(); if (!checkBox2.Checked) { System.Diagnostics.Process.Start("Explorer.exe", cPath); } else { int n = srange[1].SlideNumber; PowerPoint.Shape nshape = slides[n].Shapes.AddPicture(gpath, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue, -pw, 0, pw, h2); if (pw > app.ActivePresentation.PageSetup.SlideWidth) { nshape.LockAspectRatio = Office.MsoTriState.msoTrue; nshape.Width = app.ActivePresentation.PageSetup.SlideWidth; nshape.Left = 0; nshape.Top = 0; } nshape.Select(); File.Delete(gpath); if (dir.GetFiles().Length == 0) { Directory.Delete(cPath, true); } } } else if (sel.Type == PowerPoint.PpSelectionType.ppSelectionShapes) { PowerPoint.Slide slide = app.ActiveWindow.View.Slide; PowerPoint.ShapeRange range = sel.ShapeRange; if (sel.HasChildShapeRange) { range = sel.ChildShapeRange; } int count = range.Count; if (count > 1) { string name = app.ActivePresentation.Name; if (name.Contains(".pptx")) { name = name.Replace(".pptx", ""); } if (name.Contains(".ppt")) { name = name.Replace(".ppt", ""); } string cPath = app.ActivePresentation.Path + @"\" + name + @" 的GIF图\"; if (!Directory.Exists(cPath)) { Directory.CreateDirectory(cPath); } System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(cPath); int k = dir.GetFiles().Length + 1; int time = int.Parse(textBox1.Text.Trim()); string gpath = cPath + name + "_" + k + ".gif"; List <int> w = new List <int>(); List <int> h = new List <int>(); List <string> path = new List <string>(); Bitmap spic = null; float xs = 0; float ys = 0; for (int i = 1; i <= count; i++) { PowerPoint.Shape pic = range[i]; pic.Export(cPath + name + "_" + k + ".png", PowerPoint.PpShapeFormat.ppShapeFormatPNG); spic = new Bitmap(cPath + name + "_" + k + ".png"); w.Add(spic.Width); h.Add(spic.Height); if (xs == 0) { xs = spic.HorizontalResolution; ys = spic.VerticalResolution; } spic.Dispose(); path.Add(cPath + name + "_" + k + ".png"); k = k + 1; } int wmax = w.Max(); int hmax = h.Max(); Bitmap bmp = new Bitmap(wmax, hmax); bmp.SetResolution(xs, ys); Graphics g = Graphics.FromImage(bmp); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; AnimatedGifEncoder gif = new AnimatedGifEncoder(); gif.Start(gpath); gif.SetDelay(time); if (checkBox1.Checked) { gif.SetRepeat(0); } else { gif.SetRepeat(-1); } if (checkBox4.Checked) { gif.SetQuality(300); gif.SetTransparent(panel1.BackColor); } for (int j = 0; j < count; j++) { spic = new Bitmap(path[j]); g.Clear(panel1.BackColor); g.DrawImage(spic, (bmp.Width - spic.Width) / 2, (bmp.Height - spic.Height) / 2); gif.AddFrame(bmp); spic.Dispose(); File.Delete(path[j]); } gif.Finish(); g.Dispose(); bmp.Dispose(); if (!checkBox2.Checked) { System.Diagnostics.Process.Start("Explorer.exe", cPath); } else { PowerPoint.Shape nshape = slide.Shapes.AddPicture(gpath, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue, -wmax, 0, wmax, hmax); nshape.Select(); //File.Delete(cPath + name + "_" + k + ".gif"); //if (dir.GetFiles().Length == 0) //{ // Directory.Delete(cPath, true); //} } } else { MessageBox.Show("请选中多张图片"); } } else { MessageBox.Show("请选中多张图片或幻灯片页面"); } }
private void button1_Click(object sender, EventArgs e) { PowerPoint.Slide slide = app.ActiveWindow.View.Slide; PowerPoint.Slides slides = app.ActivePresentation.Slides; PowerPoint.Selection sel = app.ActiveWindow.Selection; if (sel.Type == PowerPoint.PpSelectionType.ppSelectionNone) { forms.MessageBox.Show("请选中要导出的幻灯片"); } else if (sel.Type == PowerPoint.PpSelectionType.ppSelectionSlides) { int wresolution = int.Parse(textBox1.Text.Trim()); int prow = int.Parse(textBox2.Text.Trim()); int pspac = int.Parse(textBox3.Text.Trim()); int pspac2 = int.Parse(textBox4.Text.Trim()); String[] arr = textBox5.Text.Trim().Split(char.Parse(","), char.Parse(" "), char.Parse(",")).ToArray(); if (wresolution <= 0 || prow <= 0 || pspac < 0 || pspac2 < 0 || arr.Count() <= 0) { MessageBox.Show("水平宽度/列数必须是正整数,间隔大小必须是非负整数,大图设置中的页码不能为空"); } else { PowerPoint.SlideRange srange = sel.SlideRange; int count = srange.Count; int[] index = new int[count]; //index数组用于将页面的选择顺序强制从前到后 for (int i = 1; i <= count; i++) { index[i - 1] = srange[i].SlideIndex; } Array.Reverse(index); Array.Sort(index); sel.Unselect(); slides.Range(index).Select(); int[,] arrnew = new int[index.Count(), 2]; //arrnew用于初始化,arrnew[i,0]是所有页面的序号,arrnew[i,1]默认是小图 for (int i = 0; i < index.Count(); i++) { arrnew[i, 0] = index[i]; arrnew[i, 1] = 0; } if (arr.Count() > 1) //将arr数组中的“n”替换为选择的最后一页的页码 { for (int i = 0; i < arr.Count(); i++) { if (arr[i] == "n") { arr[i] = count.ToString(); } } } else if (arr[0] == "n") { arr[0] = count.ToString(); } int arrprow1 = 0; for (int i = 0; i < arrnew.Length / 2; i++) //根据数组arr标记arrnew[i,1]中哪些页面是大图 { if (prow == 1) { arrnew[i, 1] = 1; arrprow1 += 1; } else { for (int j = 0; j < arr.Count(); j++) { if (arrnew[i, 0] == int.Parse(arr[j])) { arrnew[i, 1] = 1; arrprow1 += 1; } } } } int wlarge = wresolution - pspac2 * 2; //根据用户设置的分辨率,计算大图和小图的宽度和高度 int hlarge = (int)(wlarge * h / w); int wsmall = (int)((wlarge - (prow - 1) * pspac) / prow); int hsmall = (int)(wsmall * h / w); int arrcount = arrnew.Length / 2; int[,] narr = new int[arrcount, 2]; //narr[0,0]是大图小图标识、narr[0,1]是水平序号 int wcount = 0; //wcount是水平序号、hcount是垂直序号、hscount是垂直方向上小图的行数、hscan是小图是否重新起一行 int hcount = 0; int hscount = 0; int hscan = 0; for (int i = 0; i < arrcount; i++) { if (arrnew[i, 1] == 1) { narr[i, 0] = 1; hcount += 1; wcount = 0; hscan = 0; } else { narr[i, 0] = 0; if (wcount == 0) { if (hscan == 0) { narr[i, 1] = wcount; wcount += 1; hscount += 1; hcount += 1; } else { wcount += 1; narr[i, 1] = wcount; wcount += 1; } } else { if (wcount < prow) { narr[i, 1] = wcount; wcount += 1; } else { wcount = 0; narr[i, 1] = wcount; hscount += 1; hcount += 1; hscan = 1; } } } } Bitmap bmp0 = new Bitmap(wresolution, hlarge * arrprow1 + hsmall * hscount + pspac * (hcount - 1) + pspac2 * 2); //计算长图的尺寸、设置长图的分辨率 float dpi = Properties.Settings.Default.dpi; bmp0.SetResolution(dpi, dpi); string name = app.ActivePresentation.Name; //根据演示文稿的文件名创建长图文件夹 if (name.Contains(".pptx")) { name = name.Replace(".pptx", ""); } else if (name.Contains(".ppt")) { name = name.Replace(".ppt", ""); } string cPath = app.ActivePresentation.Path + @"\" + name + @" 的幻灯片\"; if (!Directory.Exists(cPath)) { Directory.CreateDirectory(cPath); } for (int i = 1; i <= sel.SlideRange.Count; i++) //导出所选的页面为图片 { PowerPoint.Slide nslide = sel.SlideRange[i]; string shname = name + "_临时_" + i; nslide.Export(cPath + shname + ".jpg", "jpg", wresolution, (int)(wresolution * h / w)); } Graphics g = Graphics.FromImage(bmp0); if (!checkBox3.Checked) //设置长图的底色 { SolidBrush br = new SolidBrush(panel1.BackColor); g.FillRectangle(br, 0, 0, bmp0.Width, bmp0.Height); } int ny = pspac2; int sc = 1; for (int i = 1; i <= count; i++) //读取之前导出的临时图片,根据之前的narr数组计算该图片所在的位置和尺寸 { string shname2 = name + "_临时_" + i; Bitmap bmp1 = new Bitmap(cPath + shname2 + ".jpg"); int x = 0; int y = 0; int wd = 0; int ht = 0; if (narr[i - 1, 0] == 1) { wd = wlarge; ht = hlarge; x = pspac2; y = y + ny; ny = ny + ht + pspac; } else { wd = wsmall; ht = hsmall; x = pspac2 + narr[i - 1, 1] * (wd + pspac); y = y + ny; if (sc < prow) { if (i < count && narr[i, 0] == 1) { sc = 1; ny = ny + ht + pspac; } else { sc += 1; } } else { sc = 1; ny = ny + ht + pspac; } } g.DrawImage(bmp1, x, y, wd, ht); //在长图中进行绘制 bmp1.Dispose(); File.Delete(cPath + shname2 + ".jpg"); } System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(cPath); //保存长图为png或jpg int k = dir.GetFiles().Length + 1; if (checkBox3.Checked) { bmp0.Save(cPath + name + "_" + k + ".png", ImageFormat.Png); } else { bmp0.Save(cPath + name + "_" + k + ".jpg", ImageFormat.Jpeg); } bmp0.Dispose(); System.Diagnostics.Process.Start("Explorer.exe", cPath); //完成后,打开长图所在文件夹 } } else { MessageBox.Show("请选中至少1张幻灯片"); } }