예제 #1
0
        private void GetShapeVisualProperties(SlidePart slidePart, Picture picture)
        {
            base.VisualShapeProp = new PPTVisualPPTShapeProp();

            if (picture.ShapeProperties.Transform2D != null)
            {
                base.VisualShapeProp.Extents = picture.ShapeProperties.Transform2D.Extents;
                base.VisualShapeProp.Offset  = picture.ShapeProperties.Transform2D.Offset;
                string    rId       = picture.BlipFill.Blip.Embed.Value;
                ImagePart imagePart = (ImagePart)slidePart.GetPartById(rId);
                FileExtension = imagePart.Uri.OriginalString.Substring(imagePart.Uri.OriginalString.LastIndexOf(".") + 1).ToLower();
            }
            else
            {
                ShapeTree shapeTree =
                    slidePart.SlideLayoutPart.SlideLayout.CommonSlideData.ShapeTree;
                if (shapeTree != null)
                {
                    var layoutShape = shapeTree.GetFirstChild <Picture>();
                    if (layoutShape.ShapeProperties.Transform2D != null)
                    {
                        VisualShapeProp.Extents = layoutShape.ShapeProperties.Transform2D.Extents;
                        VisualShapeProp.Offset  = layoutShape.ShapeProperties.Transform2D.Offset;
                    }
                }
                //base.SetSlideLayoutVisualShapeProperties(slidePart,picture);
            }
            DocumentFormat.OpenXml.Drawing.EffectList effectList = picture.ShapeProperties.GetFirstChild <DocumentFormat.OpenXml.Drawing.EffectList>();
            if (effectList != null)
            {
                recalculatePropertiesWithEffect(effectList);
            }
        }
예제 #2
0
        private static ImagePart ExtractImage(Picture pic, SlidePart slide, out string extension)
        {
            // First, get relationship id of image
            string rId = pic.BlipFill.Blip.Embed.Value;

            ImagePart imagePart = (ImagePart)slide.GetPartById(rId);

            // Get the original file name.
            Debug.WriteLine("$$Image:" + imagePart.Uri.OriginalString);
            extension = "bmp";
            if (imagePart.ContentType.Contains("jpeg") || imagePart.ContentType.Contains("jpg"))
            {
                extension = "jpg";
            }
            else if (imagePart.ContentType.Contains("png"))
            {
                extension = "png";
            }
            return(imagePart);
        }
예제 #3
0
        private int ExtractPictureBulletImage(PPTRunProperties bulletProp, string embed,
                                              string realDir, SlidePart slidePart)
        {
            int imageSize = 0;

            try
            {
                OpenXmlPart masterPart = slide.SlideLayoutPart.SlideMasterPart.GetPartById(embed);
                if (masterPart != null)
                {
                    if (masterPart.ContentType.Equals("image/png"))
                    {
                        imageSize = CreateImage(bulletProp, embed, realDir, imageSize, masterPart);
                    }
                    else
                    {
                        OpenXmlPart sldPart = slidePart.GetPartById(embed);
                        if (sldPart != null)
                        {
                            if (sldPart.ContentType.Equals("image/png"))
                            {
                                imageSize = CreateImage(bulletProp, embed, realDir, imageSize, sldPart);
                            }
                        }
                    }
                }
            }
            catch (ArgumentOutOfRangeException aoex)
            {
                Console.WriteLine(aoex.Message);
            }
            catch (ArgumentException aex)
            {
                Console.WriteLine(aex.Message);
            }
            return(imageSize);
        }
예제 #4
0
        /// <summary>
        /// Parses the slide into one of our models.
        /// </summary>
        /// <param name="slidePart">The slide part.</param>
        /// <returns>The populated model.</returns>
        /// <exception cref="ArgumentNullException">slidePart</exception>
        private static Model.Slide ParseSlide(SlidePart slidePart)
        {
            // Verify that the slide part exists.
            if (slidePart?.Slide == null)
            {
                throw new ArgumentNullException("slidePart");
            }

            // If the slide exists...
            var parsedSlide = new Model.Slide();

            if (slidePart.Slide != null)
            {
                // Iterate through all the paragraphs in the slide.
                foreach (var entity in slidePart.Slide.Descendants <Shape>())
                {
                    var placeholderShape = entity.NonVisualShapeProperties.ApplicationNonVisualDrawingProperties.PlaceholderShape;
                    if (placeholderShape != null && placeholderShape.Type != PlaceholderValues.Body)
                    {
                        // Handle titles
                        switch ((PlaceholderValues)placeholderShape.Type)
                        {
                        case PlaceholderValues.Title:
                        case PlaceholderValues.CenteredTitle:
                            parsedSlide.Titles.Add(entity.GetFirstChild <TextBody>().InnerText);
                            break;

                        case PlaceholderValues.SubTitle:
                            parsedSlide.SubTitles.Add(entity.GetFirstChild <TextBody>().InnerText);
                            break;

                        default:
                            // Skip for now
                            break;
                        }
                    }
                    else
                    {
                        // Lets just assume this is a random text box and see what we can strip from it.
                        var paragraphs = entity.GetFirstChild <TextBody>().Descendants <DocumentFormat.OpenXml.Drawing.Paragraph>();
                        foreach (var paragraph in paragraphs)
                        {
                            parsedSlide.Bullets.Add(new Bullet()
                            {
                                Text  = paragraph.InnerText,
                                Level = paragraph.ParagraphProperties?.Level != null ?
                                        paragraph.ParagraphProperties.Level.Value : 0
                            });
                        }
                    }
                }
            }

            // Now strip the images.
            var pictures = slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>();

            foreach (var img in pictures)
            {
                var embed   = img.BlipFill.Blip.Embed.Value;
                var imgPart = slidePart.GetPartById(embed);
                parsedSlide.Images.Add(new Image()
                {
                    Filename    = imgPart.Uri.OriginalString,
                    ContentType = imgPart.ContentType,
                    Data        = System.Drawing.Image.FromStream(imgPart.GetStream())
                });
            }

            // Lastly, the speaker notes
            var notesPart = slidePart.NotesSlidePart;

            if (notesPart != null)
            {
                var noteShape = notesPart
                                .NotesSlide?
                                .CommonSlideData?
                                .ShapeTree?
                                .Descendants <Shape>()?
                                .FirstOrDefault(s =>
                                                s.NonVisualShapeProperties?
                                                .ApplicationNonVisualDrawingProperties?
                                                .PlaceholderShape?
                                                .Type == PlaceholderValues.Body);

                if (noteShape != null)
                {
                    parsedSlide.Notes = noteShape.TextBody.InnerText;
                }
            }

            return(parsedSlide);
        }
예제 #5
0
 private ImagePart GetImagePart()
 {
     return _imagePart ??= (ImagePart) _slidePart.GetPartById(_blipRelateId);
 }
예제 #6
0
 private ImagePart GetImagePart()
 {
     return(_imgPart ??= (ImagePart)_sldPart.GetPartById(_blipRelateId));
 }
예제 #7
0
        // Replace image in PPT shape.
        public void ReplaceFirstImageMatchingAltText(PresentationDocument presentationDocument, string newImage, string alternateTextToFind,
                                                     string newImagePath, List <string> LstShowPicture, List <string> LstShowText,
                                                     int SlideIndex, DataTable dtFieldActive, List <PPTXTemplateFields> PPTXAllparams)
        {
            try
            {
                int Idx = SlideIndex * 1000, Idz = 0, TextIndex = 0;
                OpenXmlElementList slideIds = presentationDocument.PresentationPart.Presentation.SlideIdList.ChildElements;

                foreach (SlideId sID in slideIds) // loop thru the SlideIDList
                {
                    if (Idz++ == SlideIndex)
                    {
                        string    relId = sID.RelationshipId;                                                  // get first slide relationship
                        SlidePart slide = (SlidePart)presentationDocument.PresentationPart.GetPartById(relId); // Get the slide part from the relationship ID.

                        var pictures = slide.Slide.Descendants <P.ShapeTree>().First().Descendants <P.Picture>().ToList();
                        foreach (var picture in pictures)
                        {
                            // get photo desc to see if it matches search text
                            var nonVisualPictureProperties = picture.Descendants <P.NonVisualPictureProperties>().FirstOrDefault();
                            if (nonVisualPictureProperties == null)
                            {
                                continue;
                            }
                            var nonVisualDrawingProperties99 = nonVisualPictureProperties.Descendants <P.NonVisualDrawingProperties>().FirstOrDefault();
                            if (nonVisualDrawingProperties99 == null)
                            {
                                continue;
                            }
                            var desc = nonVisualDrawingProperties99.Description;
                            //if (desc == null || desc.Value == null || !desc.Value.Contains(alternateTextToFind))
                            //    continue;

                            P.BlipFill blipFill = picture.Descendants <P.BlipFill>().First();
                            var        blip     = blipFill.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().First();
                            string     embedId  = blip.Embed; // now we need to find the embedded content and update it.

                            // find the content
                            ImagePart imagePart = (ImagePart)slide.GetPartById(embedId);
                            if (imagePart != null)
                            {
                                try
                                {
                                    using (FileStream fileStream = new FileStream(newImagePath + LstShowPicture[Convert.ToInt32(desc)], FileMode.Open))
                                    {
                                        imagePart.FeedData(fileStream);
                                        fileStream.Close();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    try
                                    {
                                        using (FileStream fileStream = new FileStream(newImagePath + newImage, FileMode.Open))
                                        {
                                            imagePart.FeedData(fileStream);
                                            fileStream.Close();
                                        }
                                    }
                                    catch (Exception ex1)
                                    {
                                    }
                                }
                            }
                        }

                        // String Text
                        foreach (string StringText in LstShowText)
                        {
                            string[] Value = StringText.Split(';');
                            List <DocumentFormat.OpenXml.Drawing.Text> textList = slide.Slide.Descendants <DocumentFormat.OpenXml.Drawing.Text>().ToList();
                            foreach (DocumentFormat.OpenXml.Drawing.Text txt in textList)
                            {
                                foreach (PPTXTemplateFields pptx in PPTXAllparams)
                                {
                                    string SelectedField = pptx.SelectedField.Trim().Substring(0, pptx.SelectedField.Trim().Length - 1);
                                    try
                                    {
                                        if (txt.Text.Contains(SelectedField + (TextIndex + 1).ToString()))
                                        {
                                            if (pptx.FieldDataType == "String" || pptx.FieldDataType == "Int")
                                            {
                                                int Index = FieldPosition(dtFieldActive, pptx.MappedFields);
                                                //if (Index != -1) txt.Text = txt.Text.Replace(SelectedField + (TextIndex + 1).ToString(), Value[Index]); else txt.Text = " ";
                                                if (Index != -1)
                                                {
                                                    txt.Text = txt.Text.SafeReplace(SelectedField + (TextIndex + 1).ToString(), Value[Index], true);
                                                }
                                                else
                                                {
                                                    txt.Text = " ";
                                                }
                                            }
                                            else if (pptx.FieldDataType == "Float")
                                            {
                                                int Index = FieldPosition(dtFieldActive, pptx.MappedFields);
                                                if (Index != -1)
                                                {
                                                    try
                                                    {
                                                        //txt.Text = txt.Text.Replace(SelectedField + (TextIndex + 1).ToString(), Convert.ToDecimal(Value[Index]).ToString("#,##0.00"));
                                                        txt.Text = txt.Text.SafeReplace(SelectedField + (TextIndex + 1).ToString(), Convert.ToDecimal(Value[Index]).ToString("#,##0.00"), true);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        txt.Text = " ";
                                                    }
                                                }
                                                else
                                                {
                                                    txt.Text = " ";
                                                }
                                            }
                                            else if (pptx.FieldDataType == "DateTime")
                                            {
                                                int Index = FieldPosition(dtFieldActive, pptx.MappedFields);
                                                if (Index != -1)
                                                {
                                                    //txt.Text = txt.Text.Replace(SelectedField + (TextIndex + 1).ToString(), Convert.ToDateTime(Value[Index]).ToString(pptx.FieldDataFormat, CultureInfo.InvariantCulture).ToString());
                                                    txt.Text = txt.Text.SafeReplace(SelectedField + (TextIndex + 1).ToString(), Convert.ToDateTime(Value[Index]).ToString(pptx.FieldDataFormat, CultureInfo.InvariantCulture).ToString(), true);
                                                }
                                                else
                                                {
                                                    txt.Text = " ";
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                }
                            }
                            TextIndex++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        public static void AddNote(string docName, int index)
        {
            try
            {
                string relId = "rId" + (index + 1);
                using (PresentationDocument ppt = PresentationDocument.Open(docName, false))
                {
                    PresentationPart   part     = ppt.PresentationPart;
                    OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements;

                    relId = (slideIds[index] as SlideId).RelationshipId;
                }
                using (PresentationDocument ppt = PresentationDocument.Open(docName, true))
                {
                    PresentationPart presentationPart1 = ppt.PresentationPart;
                    SlidePart        slidePart2        = (SlidePart)presentationPart1.GetPartById(relId);
                    NotesSlidePart   notesSlidePart1;
                    string           existingSlideNote = "";

                    if (slidePart2.NotesSlidePart != null)
                    {
                        //Appened new note to existing note.
                        existingSlideNote = slidePart2.NotesSlidePart.NotesSlide.InnerText + "\n";
                        var val = (NotesSlidePart)slidePart2.GetPartById(relId);
                        notesSlidePart1 = slidePart2.AddPart <NotesSlidePart>(val, relId);
                    }
                    else
                    {
                        //Add a new noteto a slide.
                        notesSlidePart1 = slidePart2.AddNewPart <NotesSlidePart>(relId);
                    }

                    NotesSlide notesSlide = new NotesSlide(
                        new CommonSlideData(new ShapeTree(
                                                new P.NonVisualGroupShapeProperties(
                                                    new P.NonVisualDrawingProperties()
                    {
                        Id = (UInt32Value)1U, Name = ""
                    },
                                                    new P.NonVisualGroupShapeDrawingProperties(),
                                                    new ApplicationNonVisualDrawingProperties()),
                                                new GroupShapeProperties(new A.TransformGroup()),
                                                new P.Shape(
                                                    new P.NonVisualShapeProperties(
                                                        new P.NonVisualDrawingProperties()
                    {
                        Id = (UInt32Value)2U, Name = "Slide Image Placeholder 1"
                    },
                                                        new P.NonVisualShapeDrawingProperties(new A.ShapeLocks()
                    {
                        NoGrouping = true, NoRotation = true, NoChangeAspect = true
                    }),
                                                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape()
                    {
                        Type = PlaceholderValues.SlideImage
                    })),
                                                    new P.ShapeProperties()),
                                                new P.Shape(
                                                    new P.NonVisualShapeProperties(
                                                        new P.NonVisualDrawingProperties()
                    {
                        Id = (UInt32Value)3U, Name = "Notes Placeholder 2"
                    },
                                                        new P.NonVisualShapeDrawingProperties(new A.ShapeLocks()
                    {
                        NoGrouping = true
                    }),
                                                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape()
                    {
                        Type = PlaceholderValues.Body, Index = (UInt32Value)1U
                    })),
                                                    new P.ShapeProperties(),
                                                    new P.TextBody(
                                                        new A.BodyProperties(),
                                                        new A.ListStyle(),
                                                        new A.Paragraph(
                                                            new A.Run(
                                                                new A.RunProperties()
                    {
                        Language = "en-US", Dirty = false
                    },
                                                                new A.Text()
                    {
                        Text = existingSlideNote + "Value Updated"
                    }),
                                                            new A.EndParagraphRunProperties()
                    {
                        Language = "en-US", Dirty = false
                    }))
                                                    ))),
                        new ColorMapOverride(new A.MasterColorMapping()));

                    notesSlidePart1.NotesSlide = notesSlide;
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
                Console.ReadLine();
            }
        }