Exemple #1
0
        private void ShapeIsPicture(PageLayer _page, pp.Shape _shape, EAnimation _animation, string _idShape)
        {
            EImageContent eImage = new EImageContent();

            eImage.Name       = "Image";
            eImage.ID         = _idShape;
            eImage.Width      = _shape.Width * Utils.tlw;
            eImage.Height     = _shape.Height * Utils.tlh;
            eImage.Top        = _shape.Top * Utils.tlh;
            eImage.Left       = _shape.Left * Utils.tlw;
            eImage.Angle      = _shape.Rotation;
            eImage.ZOder      = (int)_shape.ZOrderPosition;
            eImage.Animations = _animation;
            eImage.RectCrop   = new ESuperPoint();
            var lstPic = Utils.slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);

            P.Picture picTag    = GetPictureTag(lstPic, _shape.Id.ToString());
            string    rID       = picTag.BlipFill.Blip.Embed.Value;
            ImagePart part      = (ImagePart)Utils.slidePart.GetPartById(rID);
            string    pathImage = Path.Combine((System.Windows.Application.Current as IAppGlobal).DocumentTempFolder, ObjectElementsHelper.RandomString(13) + Path.GetExtension(part.Uri.ToString()));

            Utils.CopyStream(part.GetStream(), pathImage);
            eImage.Image      = new Image();
            eImage.Image.Path = pathImage;
            _page.Children.Add(eImage);
        }
        private static void GenerateImagePart1Content(ImagePart imagePart1)
        {
            var data = GetBinaryDataStream(_imagePart1Data);

            imagePart1.FeedData(data);
            data.Close();
        }
Exemple #3
0
    public static ImageInfo Create(MainDocumentPart documentPart, ImagePart image)
    {
        String    id = documentPart.GetIdOfPart(image);
        ImageInfo r  = new ImageInfo(image, id);

        return(r);
    }
Exemple #4
0
 protected override void OnMouseMove(MouseEventArgs e)
 {
     base.OnMouseMove(e);
     GetCurrInfo(e.X, e.Y);
     if (e.Button != MouseButtons.Left && CurrImagePart != null)
     {
         if (!_showToolTip || _oldPart != CurrImagePart)
         {
             var pindex = GetIndexAtPoint(new Point(e.X, e.Y));
             var rec    = GetImageBounds(pindex);
             _oldPart = CurrImagePart;
             var s = _oldPart.Description;
             var n = s.Split('\n').Length;
             var t = 20 * (n + 1);
             var h =
                 Height - rec.Bottom > t ?
                 rec.Bottom :
                 rec.Top - t;
             toolTip1.Show(s, this, rec.X, h);
             _showToolTip = true;
         }
     }
     else
     {
         HideToolTip();
     }
 }
Exemple #5
0
        public void Rename(ImagePart part, string newName)
        {
            var index = part.Index;

            if (Folder.PartIndexs.Contains(index))
            {
                if (Database.ImagePartTable[index.DictionaryName].Has(newName))
                {
                    MessageBox.Show(
                        string.Format("无法重命名\"{0}\":与现有元件重名", newName),
                        "重命名时出错");
                }
                else
                {
                    SymbolIndex oldid = part.Index;
                    SymbolIndex newid = new SymbolIndex(newName, part.Standard, part.No);
                    if (!index.Equals(newid))
                    {
                        Database.ImagePartTable.Redirect(part, newid);
                        Folder.Redirect(oldid, newid);
                    }
                    part.Rename(newName);
                }
            }
        }
        /// <summary>
        /// Clones this slide.
        /// </summary>
        /// <returns>The clone.</returns>
        /// <remarks>
        /// <see href="http://blogs.msdn.com/b/brian_jones/archive/2009/08/13/adding-repeating-data-to-powerpoint.aspx">Adding Repeating Data to PowerPoint</see>
        /// <see href="http://startbigthinksmall.wordpress.com/2011/05/17/cloning-a-slide-using-open-xml-sdk-2-0/">Cloning a Slide using Open Xml SDK 2.0</see>
        /// <see href="http://www.exsilio.com/blog/post/2011/03/21/Cloning-Slides-including-Images-and-Charts-in-PowerPoint-presentations-Using-Open-XML-SDK-20-Productivity-Tool.aspx">See Cloning Slides including Images and Charts in PowerPoint presentations and Using Open XML SDK 2.0 Productivity Tool</see>
        /// </remarks>
        public PptxSlide Clone()
        {
            SlidePart slideTemplate = this.slidePart;

            // Clone slide contents
            SlidePart slidePartClone = this.presentationPart.AddNewPart <SlidePart>();

            using (var templateStream = slideTemplate.GetStream(FileMode.Open))
            {
                slidePartClone.FeedData(templateStream);
            }

            // Copy layout part
            slidePartClone.AddPart(slideTemplate.SlideLayoutPart);

            // Copy the image parts
            foreach (ImagePart image in slideTemplate.ImageParts)
            {
                ImagePart imageClone = slidePartClone.AddImagePart(image.ContentType, slideTemplate.GetIdOfPart(image));
                using (var imageStream = image.GetStream())
                {
                    imageClone.FeedData(imageStream);
                }
            }

            return(new PptxSlide(this.presentationPart, slidePartClone));
        }
        public void DisplayImage(ImagePart ip)
        {
            try
            {
                Stream stream = ip.GetStream();

                if (ip.Uri.ToString().EndsWith(".svg"))
                {
                    MessageBox.Show("Format not currently supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pbImage.Image    = pbImage.ErrorImage;
                    pbImage.SizeMode = PictureBoxSizeMode.CenterImage;
                }
                else
                {
                    Image imgStream = Image.FromStream(stream);
                    pbImage.Image = imgStream;

                    if (imgStream.Height > pbImage.Size.Height || imgStream.Width > pbImage.Size.Width)
                    {
                        pbImage.SizeMode = PictureBoxSizeMode.Zoom;
                    }
                    else
                    {
                        pbImage.SizeMode = PictureBoxSizeMode.CenterImage;
                    }
                }

                pbImage.Visible = true;
            }
            catch (Exception ex)
            {
                LoggingHelper.Log("ViewImages::UnableToDisplayImage : " + ex.Message);
            }
        }
        /// <summary>
        /// Replaces a picture by another inside the slide.
        /// </summary>
        /// <param name="tag">The tag associated with the original picture so it can be found, if null or empty do nothing.</param>
        /// <param name="newPicture">The new picture (as a byte array) to replace the original picture with, if null do nothing.</param>
        /// <param name="contentType">The picture content type: image/png, image/jpeg...</param>
        /// <remarks>
        /// <see href="http://stackoverflow.com/questions/7070074/how-can-i-retrieve-images-from-a-pptx-file-using-ms-open-xml-sdk">How can I retrieve images from a .pptx file using MS Open XML SDK?</see>
        /// <see href="http://stackoverflow.com/questions/7137144/how-can-i-retrieve-some-image-data-and-format-using-ms-open-xml-sdk">How can I retrieve some image data and format using MS Open XML SDK?</see>
        /// <see href="http://msdn.microsoft.com/en-us/library/office/bb497430.aspx">How to: Insert a Picture into a Word Processing Document</see>
        /// </remarks>
        public void ReplacePicture(string tag, byte[] newPicture, string contentType)
        {
            if (string.IsNullOrEmpty(tag))
            {
                return;
            }

            if (newPicture == null)
            {
                return;
            }

            ImagePart imagePart = this.AddPicture(newPicture, contentType);

            foreach (Picture pic in this.slidePart.Slide.Descendants <Picture>())
            {
                var cNvPr = pic.NonVisualPictureProperties.NonVisualDrawingProperties;
                if (cNvPr.Title != null)
                {
                    string title = cNvPr.Title.Value;
                    if (title.Contains(tag))
                    {
                        // Gets the relationship ID of the part
                        string rId = this.slidePart.GetIdOfPart(imagePart);

                        pic.BlipFill.Blip.Embed.Value = rId;
                    }
                }
            }

            // Need to save the slide otherwise the relashionship is not saved.
            // Example: <a:blip r:embed="rId2">
            // r:embed is not updated with the right rId
            this.Save();
        }
        public override Run ObtainRun(WordprocessingDocument package)
        {
            ImagePart imagePart = package.MainDocumentPart.AddImagePart(ImagePartType.Bmp);

            imagePart.FeedData(new MemoryStream(m_Image));
            return(new Run(CreateImage(package.MainDocumentPart.GetIdOfPart(imagePart), m_Size)));
        }
        /// <summary>
        /// Sets the document theme
        /// </summary>
        /// <param name="theme">Theme package</param>
        public static OpenXmlPowerToolsDocument SetTheme(WmlDocument doc, OpenXmlPowerToolsDocument themeDoc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    using (OpenXmlMemoryStreamDocument themeStream = new OpenXmlMemoryStreamDocument(themeDoc))
                        using (Package theme = themeStream.GetPackage())
                        {
                            // Gets the theme manager part
                            PackageRelationship themeManagerRelationship =
                                theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault();
                            if (themeManagerRelationship != null)
                            {
                                PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri);

                                // Gets the theme main part
                                PackageRelationship themeRelationship =
                                    themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault();
                                if (themeRelationship != null)
                                {
                                    PackagePart themePart        = theme.GetPart(themeRelationship.TargetUri);
                                    XDocument   newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read)));

                                    // Removes existing theme part from document
                                    if (document.MainDocumentPart.ThemePart != null)
                                    {
                                        document.MainDocumentPart.DeletePart(document.MainDocumentPart.ThemePart);
                                    }

                                    // Creates a new theme part
                                    ThemePart documentThemePart = document.MainDocumentPart.AddNewPart <ThemePart>();

                                    var embeddedItems =
                                        newThemeDocument
                                        .Descendants()
                                        .Attributes(relationshipns + "embed");
                                    foreach (PackageRelationship imageRelationship in themePart.GetRelationships())
                                    {
                                        // Adds an image part to the theme part and stores contents inside
                                        PackagePart imagePart    = theme.GetPart(imageRelationship.TargetUri);
                                        ImagePart   newImagePart =
                                            documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType));
                                        newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read));

                                        // Updates relationship references into the theme XDocument
                                        XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id);
                                        if (relationshipAttribute != null)
                                        {
                                            relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart);
                                        }
                                    }
                                    documentThemePart.PutXDocument(newThemeDocument);
                                }
                            }
                        }
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Exemple #11
0
        /// <param name="titleOrDescription">
        /// Replaces a placeholder-image with multiple images by comparing title/description
        ///
        /// Word Image -> Right Click -> Format Picture -> Alt Text -> Title
        /// </param>
        public static void ReplaceMultipleImages(WordprocessingDocument doc, string titleOrDescription, Bitmap[] bitmaps, string newImagePartId, bool adaptSize = false, ImagePartType imagePartType = ImagePartType.Png)
        {
            Blip[] blips = FindAllBlips(doc, d => d.Title == titleOrDescription || d.Description == titleOrDescription);

            if (blips.Count() != bitmaps.Length)
            {
                throw new ApplicationException("Images count does not match the images count in word");
            }

            if (adaptSize && !AvoidAdaptSize)
            {
                bitmaps = bitmaps.Select(bitmap =>
                {
                    var part = doc.MainDocumentPart.GetPartById(blips.First().Embed);

                    using (var stream = part.GetStream())
                    {
                        Bitmap oldBmp = (Bitmap)Bitmap.FromStream(stream);
                        return(ImageResizer.Resize(bitmap, oldBmp.Width, oldBmp.Height));
                    }
                }).ToArray();
            }

            doc.MainDocumentPart.DeletePart(blips.First().Embed);

            var i           = 0;
            var bitmapStack = new Stack <Bitmap>(bitmaps.Reverse());

            foreach (var blip in blips)
            {
                ImagePart img = CreateImagePart(doc, bitmapStack.Pop(), newImagePartId + i, imagePartType);
                blip.Embed = doc.MainDocumentPart.GetIdOfPart(img);
                i++;
            }
        }
Exemple #12
0
        private static string RenderImageDataWithLinkAndAltMacro(string input, FloatAlignment alignment, Func <string, string> encode)
        {
            string    format = alignment == FloatAlignment.None ? ImageLinkAndAlt : ImageLinkAndAltWithStyle;
            ImagePart parts  = Utility.ExtractImageParts(input, ImagePartExtras.ContainsLink | ImagePartExtras.ContainsText | ImagePartExtras.ContainsData, false);

            return(string.Format(format, alignment.GetStyle(), alignment.GetPadding(), encode(parts.LinkUrl), encode(parts.ImageUrl), encode(parts.Text), parts.Dimensions));
        }
Exemple #13
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);
            }
        }
Exemple #14
0
        private static string RenderImageWithAltMacro(string input, FloatAlignment alignment, Func <string, string> encode)
        {
            string    format = ImageNoLinkAndAlt;
            ImagePart parts  = Utility.ExtractImageParts(input, ImagePartExtras.ContainsText);

            return(string.Format(format, alignment.GetStyle(), alignment.GetPadding(), encode(parts.ImageUrl), encode(parts.Text), parts.Dimensions));
        }
Exemple #15
0
        public static void InsertAPicture(string fileName, string document, string bookmark)
        {
            OpenSettings openSettings = new OpenSettings();

            // Add the MarkupCompatibilityProcessSettings
            openSettings.MarkupCompatibilityProcessSettings =
                new MarkupCompatibilityProcessSettings(
                    MarkupCompatibilityProcessMode.ProcessAllParts,
                    FileFormatVersions.Office2007);

            //   string document = @"E:\**项目\**文书\108.docx";
            //   document = @"F:\Project_Code\SVNProject\SDHS_SZCG_ZCCG\SZZF\SZZFWord\xcjckyyszj.docx";
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Open(document, true))
            {
                MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                using (FileStream stream = new FileStream(fileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }



                AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), bookmark);
            }
        }
        public static void GenerateImagePart2Content(ImagePart imagePart2)
        {
            var data = GetBinaryDataStream(ImagePart2Data);

            imagePart2.FeedData(data);
            data.Close();
        }
        /// <summary>
        /// Add ImagePart to the document.
        /// </summary>
        string AddImagePart(FileInfo newImg)
        {
            ImagePartType type = ImagePartType.Bmp;

            switch (newImg.Extension.ToLower())
            {
            case ".jpeg":
            case ".jpg":
                type = ImagePartType.Jpeg;
                break;

            case ".png":
                type = ImagePartType.Png;
                break;

            default:
                type = ImagePartType.Bmp;
                break;
            }

            ImagePart newImgPart = Document.MainDocumentPart.AddImagePart(type);

            using (FileStream stream = newImg.OpenRead())
            {
                newImgPart.FeedData(stream);
            }

            string rId = Document.MainDocumentPart.GetIdOfPart(newImgPart);

            return(rId);
        }
Exemple #18
0
        private static string RenderImageNoLinkMacro(string input, FloatAlignment alignment, Func <string, string> encode)
        {
            string    format = alignment == FloatAlignment.None ? ImageNoLink : ImageNoLinkWithStyle;
            ImagePart parts  = Utility.ExtractImageParts(input, ImagePartExtras.None);

            return(string.Format(format, alignment.GetStyle(), alignment.GetPadding(), encode(parts.ImageUrl), parts.Dimensions));
        }
        /// <summary>
        /// Sets a background picture for a table cell (a:tc).
        /// </summary>
        /// <remarks>
        /// <![CDATA[
        /// <a:tc>
        ///  <a:txBody>
        ///   <a:bodyPr/>
        ///   <a:lstStyle/>
        ///   <a:p>
        ///    <a:endParaRPr lang="fr-FR" dirty="0"/>
        ///   </a:p>
        ///  </a:txBody>
        ///  <a:tcPr> (TableCellProperties)
        ///   <a:blipFill dpi="0" rotWithShape="1">
        ///    <a:blip r:embed="rId2"/>
        ///    <a:srcRect/>
        ///    <a:stretch>
        ///     <a:fillRect b="12000" r="90000" t="14000"/>
        ///    </a:stretch>
        ///   </a:blipFill>
        ///  </a:tcPr>
        /// </a:tc>
        /// ]]>
        /// </remarks>
        private static void SetTableCellPropertiesWithBackgroundPicture(PowerpointSlide slide, A.TableCellProperties tcPr, Cell.BackgroundPicture backgroundPicture)
        {
            if (backgroundPicture.Content == null)
            {
                return;
            }

            ImagePart imagePart = slide.AddPicture(backgroundPicture.Content, backgroundPicture.ContentType);

            A.BlipFill blipFill = new A.BlipFill();
            A.Blip     blip     = new A.Blip()
            {
                Embed = slide.GetIdOfImagePart(imagePart)
            };
            A.SourceRectangle srcRect  = new A.SourceRectangle();
            A.Stretch         stretch  = new A.Stretch();
            A.FillRectangle   fillRect = new A.FillRectangle()
            {
                Top    = backgroundPicture.Top,
                Right  = backgroundPicture.Right,
                Bottom = backgroundPicture.Bottom,
                Left   = backgroundPicture.Left
            };
            stretch.AppendChild(fillRect);
            blipFill.AppendChild(blip);
            blipFill.AppendChild(srcRect);
            blipFill.AppendChild(stretch);
            tcPr.AppendChild(blipFill);
        }
        public static void AddImagePart(SlidePart slidePart, ImagePartType imagePartType, string id, Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            ImagePart imagePart = slidePart.AddImagePart(imagePartType, id);

            imagePart.FeedData(stream);
        }
Exemple #21
0
        /// <summary>
        /// Add an image to the body by its stream
        /// </summary>
        /// <param name="image"></param>
        public void AddImage(Stream image)
        {
            ImagePart imagePart = _mainDocumentPart.AddImagePart("image/png");

            imagePart.FeedData(image);
            AddImageToBody(_package, _mainDocumentPart.GetIdOfPart(imagePart));
        }
        public void Render()
        {
            ImagePart imagePart = WordDocument.MainDocumentPart.AddImagePart(ImagePartType.Png);

            using (var ms = new MemoryStream(ParagraphImage.Source))
            {
                imagePart.FeedData(ms);
            }

            WordParagraph       p  = new WordParagraph();
            ParagraphProperties pp = new ParagraphProperties()
            {
                Indentation = new Indentation()
                {
                    Left = (500 * Depth).ToString()
                }
            };

            p.Append(pp);
            Run run = new Run(GetDrawing(WordDocument.MainDocumentPart.GetIdOfPart(imagePart)));

            p.Append(run);

            WordDocument.MainDocumentPart.Document.Body.AppendChild(p);
            WordDocument.MainDocumentPart.Document.Body.AppendChild(GetParagraphImageTitle());
        }
Exemple #23
0
        /// <summary>
        /// 遍历docx文档 寻找有draw子节点的段落 将找到的图片根据doi存储起来 并返回图片信息集合
        /// </summary>
        /// <param name="docxfilepath">docx文件路径</param>
        /// <param name="DOI">文章doi</param>
        /// <returns>返回图片信息集合</returns>
        public List <PictureModel> OperateDrawing(string docxfilepath, string DOI)
        {
            List <PictureModel> dmList = new List <PictureModel>();

            //读取word文档 获得word文档
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docxfilepath, true))
            {
                var mainpart = doc.MainDocumentPart;
                var body     = doc.MainDocumentPart.Document.Body;
                //拿到段落中存在Drawing的 段落列表
                var paragraphes = body.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Where(t => t.Descendants <Drawing>().Count() > 0).ToList();//DocumentFormat.OpenXml.Wordprocessing.Paragraph
                if (paragraphes.Count() > 0)
                {
                    for (int i = 0; i < paragraphes.Count(); i++)
                    {
                        var blip = paragraphes[i].Descendants <Blip>().FirstOrDefault();
                        if (null != blip)
                        {
                            PictureModel pm = new PictureModel();
                            //获取blip标签下面的Embed属性
                            pm.TheEmbed = blip.Embed;
                            //根据Embed属性所代表的id 找到所代表的ImagePart
                            ImagePart imgpart = mainpart.GetPartById(blip.Embed) as ImagePart;
                            //Image img=Image.FromStream(imgpart.GetStream());
                            //根据所找到的Imagepart  找到里面的流
                            string contentType = imgpart.ContentType;
                            pm.PicturePath = SaveImage(DOI, contentType, i + 1, imgpart);
                            dmList.Add(pm);
                        }
                    }
                }
            }
            return(dmList);
        }
Exemple #24
0
        /// <summary>
        /// 按书签插入图片
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="picPath"></param>
        /// <param name="bm"></param>
        /// <param name="x">宽度厘米</param>
        /// <param name="y">高度厘米</param>
        /// <param name="type"></param>
        public static void InsertBMPicture(string filePath, string picPath, string bm, long x, long y, ImagePartType type)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;

                BookmarkStart bmStart = findBookMarkStart(doc, bm);
                if (bmStart == null)
                {
                    return;
                }

                ImagePart imagePart = mainPart.AddImagePart(type);

                using (FileStream stream = new FileStream(picPath, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
                long cx = 360000L * x;//360000L = 1厘米
                long cy = 360000L * y;
                Run  r  = AddImageToBody(doc, mainPart.GetIdOfPart(imagePart), cx, cy);
                bmStart.Parent.InsertAfter <Run>(r, bmStart);
                mainPart.Document.Save();
            }
        }
Exemple #25
0
        public bool ReplaceImageInSlide(SlidePart slidePart, string imageFileLocation)
        {
            this.Logger.Log("Trying to replace image in slide Part");
            var       mySlideLayoutPart = slidePart.SlideLayoutPart;
            ImagePart imagePart         = slidePart.AddImagePart("image/png");
            var       imgRelId          = slidePart.GetIdOfPart(imagePart);

            FileStream stream = new FileStream(imageFileLocation, FileMode.Open);

            imagePart.FeedData(stream);

            stream.Close();


            // https://blogs.msdn.microsoft.com/brian_jones/2008/11/18/creating-a-presentation-report-based-on-data/

            // Find the first image element and replace
            try
            {
                Drawing.Blip blip = slidePart.Slide.Descendants <Blip>().First();
                blip.Embed = imgRelId;
                this.Logger.Log("Saving slide Part");
                slidePart.Slide.Save();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #26
0
        static void Main(string[] args)
        {
            String wordPath   = @"C:\Users\dxw\Desktop\123";  //word在哪里
            String jpgPathPro = @"C:\Users\dxw\Desktop\jpg\"; //jpg放哪里
            var    files      = Directory.GetFiles(wordPath, "*.docx");

            //在当前文件夹中遍历所有文档
            foreach (var file in files)
            {
                WordprocessingDocument docx = WordprocessingDocument.Open(file, true);
                foreach (var image in docx.MainDocumentPart.Document.Body.Descendants <ImageData>())
                {
                    ImagePart p      = docx.MainDocumentPart.GetPartById(image.RelationshipId) as ImagePart;
                    int       hash   = p.GetHashCode();
                    Stream    stream = p.GetStream();
                    byte[]    bytes  = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    stream.Seek(0, SeekOrigin.Begin);
                    string       jpgPath = jpgPathPro + hash + ".wmf";
                    FileStream   fs      = new FileStream(jpgPath, FileMode.Create);
                    BinaryWriter bw      = new BinaryWriter(fs);
                    bw.Write(bytes);
                    bw.Close();
                    fs.Close();
                }
            }
        }
        internal int SaveImageSection(ImagePart imageSection)
        {
            int imageSectionId = 0;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SaveImageSection";
                    cmd.Parameters.Add("@OriginalImageId", SqlDbType.Int).Value     = imageSection.OriginalImageId;
                    cmd.Parameters.Add("@ImagePartName", SqlDbType.VarChar).Value   = imageSection.ImagePartName;
                    cmd.Parameters.Add("@ImagePartByte", SqlDbType.VarBinary).Value = imageSection.ImagePartByte;
                    cmd.Parameters.Add("@CoordX1", SqlDbType.Int).Value             = imageSection.X1;
                    cmd.Parameters.Add("@CoordX2", SqlDbType.Int).Value             = imageSection.X2;
                    cmd.Parameters.Add("@CoordY1", SqlDbType.Int).Value             = imageSection.Y1;
                    cmd.Parameters.Add("@CoordY2", SqlDbType.Int).Value             = imageSection.Y2;
                    cmd.Parameters.Add("@Width", SqlDbType.Int).Value  = imageSection.Width;
                    cmd.Parameters.Add("@Height", SqlDbType.Int).Value = imageSection.Height;


                    cmd.Parameters.Add("@ImageSectionId", SqlDbType.Int);
                    cmd.Parameters["@ImageSectionId"].Direction = ParameterDirection.Output;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    imageSectionId = Convert.ToInt32(cmd.Parameters["@ImageSectionId"].Value);
                    conn.Close();
                }
            }
            return(imageSectionId);
        }
        static void Main(string[] args)
        {
            string file      = @"c:\temp\mydoc.docx";
            string imageFile = @"c:\temp\myimage.jpg";
            string labelText = "PersonMainPhoto";

            using (var document = WordprocessingDocument.Open(file, isEditable: true))
            {
                var mainPart = document.MainDocumentPart;
                var table    = mainPart.Document.Body.Descendants <Table>().First();

                var pictureCell = table.Descendants <TableCell>().First(c => c.InnerText == labelText);

                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                using (FileStream stream = new FileStream(imageFile, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                pictureCell.RemoveAllChildren();
                AddImageToCell(pictureCell, mainPart.GetIdOfPart(imagePart));

                mainPart.Document.Save();
            }
        }
Exemple #29
0
        public static void Main(string[] args)
        {
            File.Copy(TemplatePath, OutputPath, true);

            using (PresentationDocument presentationDoc = PresentationDocument.Open(OutputPath, true))
            {
                PresentationPart presPart = presentationDoc.PresentationPart;

                // Step 1: Identify the proper Part Id
                SlidePart contentSlidePart = (SlidePart)presPart.GetPartById("rId2");

                // Step 2: Replace one image with external file
                string imageRel   = "rIdImg";
                int    imageRelId = 1;
                var    imgId      = imageRel + imageRelId;

                ImagePart imagePart = contentSlidePart.AddImagePart(ImagePartType.Jpeg, imgId);

                using (Image image = Image.FromFile(ImagePath))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        m.Position = 0;
                        imagePart.FeedData(m);

                        SwapPhoto(contentSlidePart, imgId);
                    }
                }

                // Step 3: Replace text matched by the key
                SwapPlaceholderText(contentSlidePart, "{{Title}}", "Testing Title for IBM");

                // Step 4: Fill out multi value fields by table
                var tupleList = new List <(string category, string model, string price)>
                {
                    ("Automobile", "Ford", "$25K"),
                    ("Automobile", "Toyota", "$30K"),
                    ("Computer", "IBM PC", "$2.5K"),
                    ("Laptop", "Dell", "$1K"),
                    ("Laptop", "Microsoft", "$2K")
                };

                Drawing.Table tbl = contentSlidePart.Slide.Descendants <Drawing.Table>().First();

                foreach (var row in tupleList)
                {
                    Drawing.TableRow tr = new Drawing.TableRow();
                    tr.Height = 100;
                    tr.Append(CreateTextCell(row.category));
                    tr.Append(CreateTextCell(row.model));
                    tr.Append(CreateTextCell(row.price));
                    tbl.Append(tr);
                }

                // Step 5: Save the presentation
                presPart.Presentation.Save();
            }
        }
Exemple #30
0
 public frmMakeParameterizedPart(ImagePart part)
 {
     InitializeComponent();
     _pe = new PartCode();
     //_pe.ImagePart = part;
     _pe.Dock = DockStyle.Fill;
     this.Controls.Add(_pe);
 }
        private Rectangle GetImagePart(Size size, ImagePart part)
        {
            var rect = new Rectangle(0, 0, size.Width, size.Height);

            switch(part)
            {
                case ImagePart.TopHalf:
                    rect.Height /= 2;
                    break;
                case ImagePart.BottomHalf:
                    rect.Height /= 2;
                    rect.Y += rect.Height;
                    break;
                case ImagePart.LeftHalf:
                    rect.Width /= 2;
                    break;
                case ImagePart.RightHalf:
                    rect.Width /= 2;
                    rect.X += rect.Width;
                    break;
                case ImagePart.TopLeftQuadrant:
                    rect.Width /= 2;
                    rect.Height /= 2;
                    break;
                case ImagePart.TopRightQuandrant:
                    rect.Width /= 2;
                    rect.Height /= 2;
                    rect.X += rect.Width;
                    break;
                case ImagePart.BottomLeftQuadrant:
                    rect.Width /= 2;
                    rect.Height /= 2;
                    rect.Y += rect.Height;
                    break;
                case ImagePart.BottomRightQuadrant:
                    rect.Width /= 2;
                    rect.Height /= 2;
                    rect.X += rect.Width;
                    rect.Y += rect.Height;
                    break;
            }

            return rect;
        }