private void RemoveSlider() { sliderHead = GetShapeByName(TimerLabConstants.TimerSliderHeadId); sliderBody = GetShapeByName(TimerLabConstants.TimerSliderBodyId); sliderHead.Delete(); sliderBody.Delete(); }
private Bitmap[] ShapeTypesToBitmaps(Array types, string shapeType) { Shapes shapes = SyncFormatUtil.GetTemplateShapes(); Bitmap[] bitmaps = new Bitmap[types.Length]; for (int i = 0; i < types.Length; i++) { if (!((MsoAutoShapeType)types.GetValue(i)).ToString().Contains(shapeType)) { continue; } try { Shape shape = shapes.AddShape( (MsoAutoShapeType)types.GetValue(i), 0, 0, TooltipsLabConstants.DisplayImageSize.Width, TooltipsLabConstants.DisplayImageSize.Height); ShapeUtil.FormatCalloutToDefaultStyle(shape); bitmaps[i] = new Bitmap(GraphicsUtil.ShapeToBitmap(shape)); shape.Delete(); } catch { } } return(bitmaps); }
//Return zoomed version of cropped slide picture to be used for zoom out animation private void GetShapeToZoomWithBackground(PowerPoint.Shape zoomShape) { PowerPoint.Shape referenceShape = GetReferenceShape(zoomShape); float finalWidthMagnify = referenceShape.Width; float initialWidthMagnify = zoomShape.Width; float finalHeightMagnify = referenceShape.Height; float initialHeightMagnify = zoomShape.Height; zoomShape.Copy(); PowerPoint.Shape zoomShapeCopy = _slide.Shapes.Paste()[1]; LegacyShapeUtil.CopyShapeAttributes(zoomShape, ref zoomShapeCopy); Globals.ThisAddIn.Application.ActiveWindow.View.GotoSlide(_slide.SlideIndex); zoomSlideCroppedShapes.Select(); zoomShapeCopy.Visible = Office.MsoTriState.msoTrue; zoomShapeCopy.Select(Office.MsoTriState.msoFalse); PowerPoint.ShapeRange selection = Globals.ThisAddIn.Application.ActiveWindow.Selection.ShapeRange; PowerPoint.Shape groupShape = selection.Group(); groupShape.Width *= (finalWidthMagnify / initialWidthMagnify); groupShape.Height *= (finalHeightMagnify / initialHeightMagnify); groupShape.Ungroup(); zoomSlideCroppedShapes.Left += (referenceShape.Left - zoomShapeCopy.Left); zoomSlideCroppedShapes.Top += (referenceShape.Top - zoomShapeCopy.Top); zoomShapeCopy.Delete(); referenceShape.Delete(); }
/// <summary> /// To avoid corrupted shape. /// Corrupted shape is produced when delete or cut a shape programmatically, but then users undo it. /// After that, most of operations on corrupted shapes will throw an exception. /// One solution for this is to re-allocate its memory: simply cut/copy and paste before using its property. /// </summary> /// <param name="shape"> Shape to be corrected </param> /// <returns> The corrected shape </returns> public static Shape CorruptionCorrection(Shape shape, PowerPointSlide ownerSlide) { Shape correctedShape = null; // Utilises deprecated PowerPointPresentation class as ShapeUtil does not utilise ActionFramework PowerPointPresentation pres = PowerPointPresentation.Current; // While doing corruption correction, we don't want to affect the clipboard ClipboardUtil.RestoreClipboardAfterAction(() => { correctedShape = ownerSlide.CopyShapeToSlide(shape); // Success return(correctedShape); }, pres, ownerSlide); if (correctedShape != null) { shape.Delete(); return(correctedShape); } else { // There were problems with the copying of the shape to the slide (could be a placeholder) thus we just return the original shape return(shape); } }
/// <summary> /// 替换幻灯片的首张图片 /// </summary> /// <param name="sindex">幻灯片索引</param> /// <param name="imgpath">新的图片路径</param> /// <returns>替换是否成功返回</returns> public bool ExchangeImg(int sindex, string imgpath, MsoZOrderCmd layoutType = MsoZOrderCmd.msoSendToBack) { try { if (GoToSlide(sindex)) { for (int i = 1; i <= m_CurSlide.Shapes.Count; ++i) { POWERPOINT.Shape s = m_CurSlide.Shapes[i]; if (s != null && s.Type == MsoShapeType.msoPicture) { //POWERPOINT.TextFrame pic = s.Width; float width = s.Width; float left = s.Left; float top = s.Top; float height = s.Height; s.Delete(); s = m_CurSlide.Shapes.AddPicture(imgpath, MsoTriState.msoFalse, MsoTriState.msoCTrue, left, top, width, height); s.ZOrder(layoutType); } } return(true); } } catch { return(false); } return(false); }
private static void UpdateSectionImage(PowerPointSlide refSlide, AgendaSection section, Shape previousImageShape) { var snapshotShape = CreateSectionImage(refSlide, section); Graphics.SyncShape(previousImageShape, snapshotShape, pickupShapeFormat: true, pickupTextContent: false, pickupTextFormat: false); previousImageShape.Delete(); }
public void AddZoomToAreaAnimation(PowerPoint.Shape zoomShape) { PrepareForZoomToArea(zoomShape); PowerPoint.Shape shapeToZoom = null, referenceShape = null; if (!ZoomLabSettings.BackgroundZoomChecked) { shapeToZoom = GetShapeToZoom(zoomShape); referenceShape = GetReferenceShape(shapeToZoom); DefaultMotionAnimation.AddDefaultMotionAnimation(this, shapeToZoom, referenceShape, 0.5f, PowerPoint.MsoAnimTriggerType.msoAnimTriggerAfterPrevious); } else { shapeToZoom = zoomSlideCroppedShapes.Duplicate()[1]; DeleteShapeAnimations(shapeToZoom); LegacyShapeUtil.CopyShapePosition(zoomSlideCroppedShapes, ref shapeToZoom); referenceShape = GetReferenceShape(zoomShape); DefaultMotionAnimation.AddZoomToAreaMotionAnimation(this, shapeToZoom, zoomShape, referenceShape, 0.5f, PowerPoint.MsoAnimTriggerType.msoAnimTriggerAfterPrevious); } shapeToZoom.Name = "PPTLabsMagnifyAreaSlide" + DateTime.Now.ToString("yyyyMMddHHmmssffff"); referenceShape.Delete(); zoomSlideCroppedShapes.Visible = Office.MsoTriState.msoFalse; indicatorShape.ZOrder(Office.MsoZOrderCmd.msoBringToFront); }
private static PowerPoint.Shape createHeaderLine(PowerPoint.DocumentWindow window, PowerPoint.Shape shape) { PowerPoint.Shape conn = null; try { // starting x and y values float x = shape.Left + shape.Width; float y = shape.Top + shape.Height / 2; // add the connector line // from http://msdn.microsoft.com/en-us/library/ff744679(v=office.14).aspx // AddConnector(Type, BeginX, BeginY, EndX, EndY) conn = window.View.Slide.Shapes. AddConnector(Office.MsoConnectorType.msoConnectorStraight, x, y, x + 100, y); // connect it to the shape conn.ConnectorFormat.BeginConnect(shape, 4); // set height to 0 (need to make sure end is disconnected first) conn.ConnectorFormat.EndDisconnect(); conn.Height = 0f; } catch (Exception) { if (conn != null) { conn.Delete(); } throw; } // return the created header line return(conn); }
private static PowerPoint.Shape FillInShapeWithScreenshot(PowerPoint.Shape shape, double magnifyRatio = 1.0) { if (shape.Type != Office.MsoShapeType.msoGroup) { CreateFillInBackgroundForShape(shape, magnifyRatio); shape.Fill.UserPicture(FillInBackgroundPicture); } else { using (var slideImage = (Bitmap)Image.FromFile(SlidePicture)) { foreach (var shapeGroupItem in (from PowerPoint.Shape sh in shape.GroupItems select sh)) { CreateFillInBackground(shapeGroupItem, slideImage); shapeGroupItem.Fill.UserPicture(FillInBackgroundPicture); } } } shape.Line.Visible = Office.MsoTriState.msoFalse; shape.Copy(); var shapeToReturn = PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.Paste()[1]; shape.Delete(); return(shapeToReturn); }
private void DelBut_Click(object sender, EventArgs e) { //iteruje przez slajdy kasując obiekty zawierające nazwę "Generator_" taAplikacja = Globals.ThisAddIn.Application; //granice działania int odslajdu = 1, doslajdu = taAplikacja.ActivePresentation.Slides.Count; if (Controls["slajdmin"].Text != "") { Int32.TryParse(Controls["slajdmin"].Text, out odslajdu); } if (Controls["slajdmax"].Text != "") { Int32.TryParse(Controls["slajdmax"].Text, out doslajdu); } int slajdpoczatkowy = taAplikacja.ActiveWindow.View.Slide.SlideIndex; for (int slajd = odslajdu; slajd <= doslajdu; slajd++) { taAplikacja.ActiveWindow.View.GotoSlide(slajd); int obiekty = taAplikacja.ActiveWindow.View.Slide.Shapes.Count(); while (obiekty > 0) { PowerPoint.Shape kszt = taAplikacja.ActiveWindow.View.Slide.Shapes(obiekty); if (kszt.Name.Contains("Generator_")) { kszt.Delete(); } obiekty--; } } taAplikacja.ActiveWindow.View.GotoSlide(slajdpoczatkowy); }
/// <summary> /// A better version of SyncShape, but cannot do a partial sync like SyncShape can. /// SyncShape cannot operate on Groups and Charts. If those are detected, SyncWholeShape resorts to deleting /// candidateShape and replacing it with a copy of refShape instead of syncing. /// </summary> public static void SyncWholeShape(Shape refShape, ref Shape candidateShape, PowerPointSlide candidateSlide) { bool succeeded = true; try { SyncShape(refShape, candidateShape); } catch (UnauthorizedAccessException) { succeeded = false; } catch (ArgumentException) { succeeded = false; } catch (COMException) { succeeded = false; } if (succeeded) { return; } candidateShape.Delete(); refShape.Copy(); candidateShape = candidateSlide.Shapes.Paste()[1]; candidateShape.Name = refShape.Name; }
private static void ConvertToPictureForShape(PowerPoint.Shape shape) { float rotation = 0; try { rotation = shape.Rotation; shape.Rotation = 0; } catch (Exception e) { PowerPointLabsGlobals.LogException(e, "Chart cannot be rotated."); } shape.Copy(); float x = shape.Left; float y = shape.Top; float width = shape.Width; float height = shape.Height; shape.Delete(); var pic = PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.PasteSpecial(PowerPoint.PpPasteDataType.ppPastePNG)[1]; pic.Left = x + (width - pic.Width) / 2; pic.Top = y + (height - pic.Height) / 2; pic.Rotation = rotation; pic.Select(); }
// TODO: This could be an extension method of shape. public static bool HasDefaultName(Shape shape) { Shape copy = shape.Duplicate()[1]; bool hasDefaultName = copy.Name != shape.Name; copy.Delete(); return(hasDefaultName); }
public static Shape CorruptionCorrection(Shape shape, PowerPointSlide ownerSlide) { // in case of random corruption of shape, cut-paste a shape before using its property Shape correctedShape = ownerSlide.CopyShapeToSlide(shape); shape.Delete(); return(correctedShape); }
public void AddOrUpdateExcelShape(String excelFilePath, int reportOid, PowerPoint.Shape shape = null) { PowerPoint.Slide activeSlide = (PowerPoint.Slide)GetActiveSlide(); if (activeSlide == null) { return; } if (shape == null) { shape = GetActiveShape(); } if (shape == null || shape.Type != MsoShapeType.msoEmbeddedOLEObject || !shape.OLEFormat.ProgID.StartsWith("Excel.Sheet.")) { try { shape = activeSlide.Shapes.AddOLEObject(100, 100, -1f, -1f, "", excelFilePath, Core.MsoTriState.msoFalse, "", 0, "", Core.MsoTriState.msoFalse); shape.Name = "" + reportOid; if (ShapeAdded != null) { ShapeAdded(activeSlide.SlideNumber, activeSlide.Name, shape.Id, "" + reportOid, SlideItemType.REPORT, ""); } } catch (Exception) { MessageDisplayer.DisplayError("Insert Report", "Problem while adding report"); } } else { float left = shape.Left; float top = shape.Top; float width = -1f; float height = -1f; String name = shape.Name; int position = shape.Id; shape.Delete(); if (ShapeDeleted != null) { ShapeDeleted(activeSlide.SlideNumber, name, position, "" + reportOid, SlideItemType.REPORT, ""); } shape = activeSlide.Shapes.AddOLEObject(left, top, width, height, "", excelFilePath, Core.MsoTriState.msoFalse, "", 0, "", Core.MsoTriState.msoFalse); shape.Name = "" + reportOid; if (ShapeAdded != null) { ShapeAdded(activeSlide.SlideNumber, activeSlide.Name, shape.Id, "" + reportOid, SlideItemType.REPORT, ""); } } }
private static void RemoveShapesForUngroupAll(PowerPoint.Shape shape, List <string> ungroupedShapes, Queue <PowerPoint.Shape> queue) { shape.Delete(); if (ungroupedShapes.Count > 0) { PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.Range(ungroupedShapes.ToArray()).Delete(); } while (queue.Count != 0) { queue.Dequeue().Delete(); } }
public static bool CanCopyMsoPlaceHolder(Shape placeholder, Shapes shapesSource) { var emptyArray = new Format[0]; Shape copyAttempt = CopyMsoPlaceHolder(emptyArray, placeholder, shapesSource); if (copyAttempt == null) { return(false); } copyAttempt.Delete(); return(true); }
private void button3_Click(object sender, EventArgs e) { PowerPoint.Slide slide = app.ActiveWindow.View.Slide; int count = slide.Shapes.Count; for (int i = count; i >= 1; i--) { PowerPoint.Shape line = slide.Shapes[i]; if (line.Name == "lines1" || line.Name == "lines2") { line.Delete(); } } }
public static Shape CompressImageInShape(Shape targetShape, PowerPointSlide currentSlide) { // Specify the temp location to be saved. Must be cleared before each new access to that location string fileName = CommonText.TemporaryCompressedImageStorageFileName; string tempFileStoragePath = Path.Combine(Path.GetTempPath(), fileName); // Export the shape to extract the image within it targetShape.Export(tempFileStoragePath, PpShapeFormat.ppShapeFormatJPG); // Check if the image is acceptable in terms of size FileInfo tempFile = new FileInfo(tempFileStoragePath); tempFile.Refresh(); long fileLength = tempFile.Length; if (fileLength < fileSizeLimit) { // Delete the file as it is not needed anymore DeleteSpecificFilePath(tempFileStoragePath); // Return the original shape return(targetShape); } // Create a new bitmap from the image representing the exported shape Image img = Image.FromFile(tempFileStoragePath); Bitmap imgBitMap = new Bitmap(img); // Releases resources held by image object and delete temp file img.Dispose(); DeleteSpecificFilePath(tempFileStoragePath); // Compresses and save the bitmap based on the specified level of compression (0 -> lowest quality, 100 -> highest quality) SaveJpg(imgBitMap, tempFileStoragePath, targetCompression); // Retrieve the compressed image and return a shape representing the image Shape compressedImgShape = currentSlide.Shapes.AddPicture(tempFileStoragePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, targetShape.Left, targetShape.Top); // Delete temp file again to return to original empty state DeleteSpecificFilePath(tempFileStoragePath); // Delete targetShape to prevent duplication targetShape.Delete(); return(compressedImgShape); }
/// <summary> /// Useful when shape has text with more than one color /// Getting color in that case without a workabout will return black /// Assumes that shape has a TextRange /// </summary> /// <param name="shape">RGB color, seems to be the color of the last character</param> /// <returns></returns> public static int GuessTextColor(Shape shape) { // clear the text, to clear presence of more than 1 color // TextRange.Font.Color.RGB then returns the same color of as new text that is added to the shape // // Unsuccessful workabouts: // Taking a sub TextRange of the shape // Trimming text to the first character Shape duplicate = shape.Duplicate()[1]; duplicate.TextFrame.TextRange.Text = ""; int color = duplicate.TextFrame.TextRange.Font.Color.RGB; duplicate.Delete(); return(color); }
private static void RecreateCorruptedShape(PowerPoint.Shape s) { s.Copy(); PowerPoint.Shape newShape = PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.Paste()[1]; newShape.Select(); newShape.Name = s.Name; newShape.Left = s.Left; newShape.Top = s.Top; while (newShape.ZOrderPosition > s.ZOrderPosition) { newShape.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendBackward); } s.Delete(); }
static void FixSectionTitleSlides(Presentation presentation) { Console.WriteLine("Fixing broken section title slides..."); var sectionTitleSlides = presentation.Slides.Cast <Slide>() .Where(slide => slide.CustomLayout.Name == "Section Title Slide"); foreach (Slide slide in sectionTitleSlides) { // Collect the texts from the slide (expecting title and subtitle) List <string> slideTexts = new List <string>(); foreach (Shape shape in slide.Shapes) { try { if (shape.HasTextFrame == MsoTriState.msoTrue && (shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderTitle || shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderSubtitle || shape.PlaceholderFormat.Type == PpPlaceholderType.ppPlaceholderBody) && shape.TextFrame.TextRange.Text != "") { slideTexts.Add(shape.TextFrame.TextRange.Text); shape.Delete(); } } catch (Exception) { // Silently ignore --> the shape is not a placeholder } } // Put the slide texts into the placeholders (and delete the empty placeholders) for (int i = 0; i < slide.Shapes.Placeholders.Count; i++) { Shape placeholder = slide.Shapes.Placeholders[i + 1]; if (i < slideTexts.Count) { placeholder.TextFrame.TextRange.Text = slideTexts[i]; } else { placeholder.Delete(); } } Console.WriteLine($" Fixed slide #{slide.SlideNumber}: {slideTexts.FirstOrDefault()}"); } }
//Return picture copy of next slide where shapes with exit animations have been deleted private static PowerPoint.Shape GetNextSlidePictureWithoutBackground(PowerPointSlide currentSlide, PowerPointSlide nextSlide, out PowerPoint.Shape pictureOnNextSlide) { Globals.ThisAddIn.Application.ActiveWindow.Selection.Unselect(); Globals.ThisAddIn.Application.ActiveWindow.View.GotoSlide(nextSlide.Index); List <PowerPoint.Shape> shapesOnNextSlide = new List <PowerPoint.Shape>(); foreach (PowerPoint.Shape sh in nextSlide.Shapes) { if (!nextSlide.HasEntryAnimation(sh) && !ShapeUtil.IsHidden(sh)) { shapesOnNextSlide.Add(sh); } } var copiedShapes = new List <PowerPoint.Shape>(); foreach (PowerPoint.Shape sh in shapesOnNextSlide) { sh.Copy(); var shapeCopy = nextSlide.Shapes.Paste()[1]; LegacyShapeUtil.CopyShapeAttributes(sh, ref shapeCopy); copiedShapes.Add(shapeCopy); } SelectAllShape(copiedShapes); PowerPoint.Selection sel = Globals.ThisAddIn.Application.ActiveWindow.Selection; PowerPoint.Shape shapeGroup = null; if (sel.ShapeRange.Count > 1) { shapeGroup = sel.ShapeRange.Group(); } else { shapeGroup = sel.ShapeRange[1]; } shapeGroup.Copy(); pictureOnNextSlide = nextSlide.Shapes.PasteSpecial(PowerPoint.PpPasteDataType.ppPastePNG)[1]; LegacyShapeUtil.CopyShapePosition(shapeGroup, ref pictureOnNextSlide); shapeGroup.Delete(); pictureOnNextSlide.Copy(); PowerPoint.Shape slidePicture = currentSlide.Shapes.PasteSpecial(PowerPoint.PpPasteDataType.ppPastePNG)[1]; return(slidePicture); }
public async Task <bool> WriteDataFor100(String strID) { try { JObject jsonData = await RequestData.GetWxPPTData("164"); if (jsonData.Value <String>("code").Equals("200") && jsonData.Value <JObject>("data") != null) { JObject dataObj = jsonData["data"].ToObject <JObject>(); string pptdata = dataObj.Value <String>("pptdata"); JArray pptdataArr = JsonConvert.DeserializeObject <JArray>(pptdata); foreach (JObject jObject in pptdataArr) { string picUrl = jObject.Value <String>("picurl"); string content = jObject.Value <String>("content"); int index = (int)decimal.Parse(jObject.Value <string>("index")); PowerPoint.Shapes shapes = Globals.ThisAddIn.Application.ActivePresentation.Slides[index].Shapes; PowerPoint.Shape shape = PPTAPI.getShape(shapes, "pic_1"); if (shape != null) { if (!String.IsNullOrEmpty(picUrl)) { string strPath = Request.HttpDownload(picUrl).Result; shapes.AddPicture(strPath, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoCTrue, shape.Left, shape.Top, shape.Width, shape.Height); shape.Delete(); } } shape = PPTAPI.getShape(shapes, "text_1"); if (shape != null) { shape.TextFrame.TextRange.Text = jObject.Value <String>("content"); } } } else { return(false); } } catch { } return(true); }
private void RecreateSlider() { int sliderColor = SliderColor(); // remove current Slider if (sliderHead != null) { sliderColor = sliderHead.Fill.ForeColor.RGB; sliderHead.Delete(); } if (sliderBody != null) { sliderColor = sliderBody.Fill.ForeColor.RGB; sliderBody.Delete(); } AddSlider(Duration(), timerBody.Width, timerBody.Height, sliderColor, SlideWidth()); }
public static PowerPoint.Shape FillInShapeWithImage(string imageFile, PowerPoint.Shape shape, bool isInPlace = false) { CreateFillInBackgroundForShape(imageFile, shape); shape.Fill.UserPicture(FillInBackgroundPicture); shape.Line.Visible = Office.MsoTriState.msoFalse; if (isInPlace) { return(shape); } shape.Copy(); var shapeToReturn = PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.Paste()[1]; shape.Delete(); return(shapeToReturn); }
/// <summary> /// Export formatted spotlight picture as a new picture, /// then use the new pic to replace the formatted one. /// Thus when it's displayed, no need to render the effect (which's very slow) /// </summary> /// <param name="spotlightPicture"></param> private void RenderSpotlightPicture(PowerPoint.Shape spotlightPicture) { string dirOfRenderedPicture = Path.GetTempPath() + @"\rendered_" + spotlightPicture.Name; //Render process: //export formatted spotlight picture to a temp folder spotlightPicture.Export(dirOfRenderedPicture, PowerPoint.PpShapeFormat.ppShapeFormatPNG); //then add the exported new picture back PowerPoint.Shape renderedPicture = PowerPointCurrentPresentationInfo.CurrentSlide.Shapes.AddPicture( dirOfRenderedPicture, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue, spotlightPicture.Left, spotlightPicture.Top, spotlightPicture.Width, spotlightPicture.Height); renderedPicture.Name = spotlightPicture.Name + "_rendered"; //get rid of extra padding CropSpotlightPictureToSlide(ref renderedPicture); spotlightPicture.Delete(); }
/// <summary> /// Within the slide, for all sections that have been "passed", replace their visual agenda image shape with /// an image of the end slide of the section. /// </summary> private static void ReplaceVisualImagesWithAfterZoomOutImages(PowerPointSlide slide, int sectionIndex) { Dictionary <int, Shape> indexedShapes = new Dictionary <int, Shape>(); slide.Shapes.Cast <Shape>() .Where(AgendaShape.WithPurpose(ShapePurpose.VisualAgendaImage)) .ToList() .ForEach(shape => indexedShapes.Add(AgendaShape.Decode(shape).Section.Index, shape)); for (int i = 2; i < sectionIndex; ++i) { Shape imageShape = indexedShapes[i]; PowerPointSlide sectionEndSlide = FindSectionLastNonAgendaSlide(i); Shape snapshotShape = slide.InsertExitSnapshotOfSlide(sectionEndSlide); snapshotShape.Name = imageShape.Name; ShapeUtil.SyncShape(imageShape, snapshotShape, pickupShapeFormat: true, pickupTextContent: false, pickupTextFormat: false); imageShape.Delete(); } }
private static Shape ImportPictureToSlide(Shape shapeToAdd, Slide targetSlide, string tempFilePath) { // The AccessViolationException is no longer catchable if (!FileDir.IsFileReadable(tempFilePath)) { return(PPLClipboard.Instance.LockAndRelease(() => { shapeToAdd.Cut(); return targetSlide.Shapes.PasteSpecial(PpPasteDataType.ppPastePNG)[1]; })); } else { shapeToAdd.Delete(); return(targetSlide.Shapes.AddPicture2(tempFilePath, MsoTriState.msoFalse, MsoTriState.msoTrue, 0, 0)); } }
//Stores slide-size crop of the current slide as a global variable private void AddZoomSlideCroppedPicture(float magnifyRatio = 1.0f) { PowerPointSlide zoomSlideCopy = this.Duplicate(); Globals.ThisAddIn.Application.ActiveWindow.View.GotoSlide(zoomSlideCopy.Index); PowerPoint.Shape cropShape = zoomSlideCopy.Shapes.AddShape(Office.MsoAutoShapeType.msoShapeRectangle, 0, 0, PowerPointPresentation.Current.SlideWidth - 0.01f, PowerPointPresentation.Current.SlideHeight - 0.01f); cropShape.Select(); PowerPoint.Selection sel = Globals.ThisAddIn.Application.ActiveWindow.Selection; PowerPoint.Shape croppedShape = CropToShape.Crop(zoomSlideCopy, sel, magnifyRatio: magnifyRatio); try { string tempFilePath = FileDir.GetTemporaryPngFilePath(); Utils.GraphicsUtil.ExportShape(croppedShape, tempFilePath); zoomSlideCroppedShapes = _slide.Shapes.AddPicture2(tempFilePath, Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue, 0, 0); croppedShape.Delete(); try { FileDir.DeleteFile(tempFilePath); } catch (Exception) { // If the file cannot be deleted, we continue without deletion. } } catch (Exception) { // Revert to normal copy and pasting if unable to create file. croppedShape.Cut(); zoomSlideCroppedShapes = _slide.Shapes.PasteSpecial(PowerPoint.PpPasteDataType.ppPastePNG)[1]; } zoomSlideCroppedShapes.Name = "PPTLabsMagnifyAreaGroup" + DateTime.Now.ToString("yyyyMMddHHmmssffff"); Utils.ShapeUtil.FitShapeToSlide(ref zoomSlideCroppedShapes); zoomSlideCopy.Delete(); }
/// <summary> /// A better version of SyncShape, but cannot do a partial sync like SyncShape can. /// SyncShape cannot operate on Groups and Charts. If those are detected, SyncWholeShape resorts to deleting /// candidateShape and replacing it with a copy of refShape instead of syncing. /// </summary> public static void SyncWholeShape(Shape refShape, ref Shape candidateShape, PowerPointSlide candidateSlide) { bool succeeded = true; try { SyncShape(refShape, candidateShape); } catch (UnauthorizedAccessException) { succeeded = false; } catch (ArgumentException) { succeeded = false; } catch (COMException) { succeeded = false; } if (succeeded) return; candidateShape.Delete(); refShape.Copy(); candidateShape = candidateSlide.Shapes.Paste()[1]; candidateShape.Name = refShape.Name; }