Wednesday, August 6, 2014

Insert Image in word document at a particular position using OPEN XML SDK

Insert Image in word document in particular position using OPEN XML SDK

#region Process Picture in word document
        private void ProcessImage(WordprocessingDocument myDoc)
        {
            try
            {
                foreach (Paragraph p in myDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(p => p.InnerText.ToUpper().Contains("{{Image}}")))
                {
                    string SignOfUser = string.Empty;
                    if (p.InnerText.Contains("{{") && p.InnerText.Contains("}}") && p.InnerText.Contains(":"))
                    {
                        SignOfUser = p.InnerText.Replace("{{", "").Replace("}}", "").Split(':')[1];
                    }
                    IEnumerable<Text> texts = p.Descendants<Text>();
                    foreach (Text text in texts)
                    {
                        text.Text = "";
                    }

                    if (string.IsNullOrEmpty(SignOfUser) == false)
                    {
                        SPFile file = GetWatermarkImage(SignOfUser + ".jpeg");
                        if (file != null)
                        {
                            MainDocumentPart mainPart = myDoc.MainDocumentPart;
                            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
                            using (Stream stream = file.OpenBinaryStream())
                            {
                                imagePart.FeedData(stream);
                            }
                            AddImageToBody(myDoc, p, mainPart.GetIdOfPart(imagePart));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }

        private void AddImageToBody(WordprocessingDocument wordDoc, Paragraph p, string relationshipId)
        {
            try
            {
                // Define the reference of the image.
                Drawing element =
                     new Drawing(
                         new OPDrawingWP.Inline(
                             new OPDrawingWP.Extent() { Cx = 999000L, Cy = 799000L },
                             new OPDrawingWP.EffectExtent()
                             {
                                 LeftEdge = 0L,
                                 TopEdge = 0L,
                                 RightEdge = 0L,
                                 BottomEdge = 0L
                             },
                             new OPDrawingWP.DocProperties()
                             {
                                 Id = (UInt32Value)1U,
                                 Name = "Picture 1"
                             },
                             new OPDrawingWP.NonVisualGraphicFrameDrawingProperties(
                                 new DocumentFormat.OpenXml.Drawing.GraphicFrameLocks() { NoChangeAspect = true }),
                             new OPDrawing.Graphic(
                                 new OPDrawing.GraphicData(
                                     new PIC.Picture(
                                         new PIC.NonVisualPictureProperties(
                                             new PIC.NonVisualDrawingProperties()
                                             {
                                                 Id = (UInt32Value)0U,
                                                 Name = "New Bitmap Image.jpg"
                                             },
                                             new PIC.NonVisualPictureDrawingProperties()),
                                         new PIC.BlipFill(
                                             new OPDrawing.Blip(
                                                 new OPDrawing.BlipExtensionList(
                                                     new OPDrawing.BlipExtension()
                                                     {
                                                         Uri =
                                                           "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                     })
                                             )
                                             {
                                                 Embed = relationshipId,
                                                 CompressionState =
                                                 OPDrawing.BlipCompressionValues.Print
                                             },
                                             new OPDrawing.Stretch(
                                                 new OPDrawing.FillRectangle())),
                                         new PIC.ShapeProperties(
                                             new OPDrawing.Transform2D(
                                                 new OPDrawing.Offset() { X = 0L, Y = 0L },
                                                 new OPDrawing.Extents() { Cx = 999000L, Cy = 799000L }),
                                             new OPDrawing.PresetGeometry(
                                                 new OPDrawing.AdjustValueList()
                                             ) { Preset = OPDrawing.ShapeTypeValues.Rectangle }))
                                 ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                         )
                         {
                             DistanceFromTop = (UInt32Value)0U,
                             DistanceFromBottom = (UInt32Value)0U,
                             DistanceFromLeft = (UInt32Value)0U,
                             DistanceFromRight = (UInt32Value)0U,
                             EditId = "50D07946"
                         });

                // Append the reference to paragraph, the element should be in a Run.
                p.AppendChild(new Run(element));
               
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }


        #endregion

Insert watermark (background image) in word document using OPEN XML SDK

Insert watermark in word document using OPEN XML SDK


// if watermark image is available in site assets document library then attach to document
                        SPFile waterMarkFile = GetWatermarkImage(watermarkFleName);
                        if (waterMarkFile != null)
                        {
                            InsertCustomWatermark(myDoc, waterMarkFile);
                        }


    #region Watermark
        private void InsertCustomWatermark(WordprocessingDocument package, SPFile p)
        {
            try
            {
                SetWaterMarkPicture(p);
                MainDocumentPart mainDocumentPart1 = package.MainDocumentPart;
                if (mainDocumentPart1 != null)
                {
                    //mainDocumentPart1.DeleteParts(mainDocumentPart1.HeaderParts);
                    HeaderPart headPart1 = mainDocumentPart1.AddNewPart<HeaderPart>();
                    GenerateHeaderPart1Content(headPart1);
                    string rId = mainDocumentPart1.GetIdOfPart(headPart1);
                    ImagePart image = headPart1.AddNewPart<ImagePart>("image/jpeg", "rId999");
                    GenerateImagePart1Content(image);
                    IEnumerable<SectionProperties> sectPrs = mainDocumentPart1.Document.Body.Elements<SectionProperties>();
                    foreach (var sectPr in sectPrs)
                    {
                        sectPr.RemoveAllChildren<HeaderReference>();
                        sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId });
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private void GenerateHeaderPart1Content(HeaderPart headerPart1)
        {
            try
            {
                Header header1 = new Header();
                Paragraph paragraph2 = new Paragraph();
                Run run1 = new Run();
                Picture picture1 = new Picture();
                V.Shape shape1 = new V.Shape() { Id = "WordPictureWatermark75517470", Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:415.2pt;height:456.15pt;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", OptionalString = "_x0000_s2051", AllowInCell = false, Type = "#_x0000_t75" };
                V.ImageData imageData1 = new V.ImageData() { Gain = "19661f", BlackLevel = "22938f", Title = "水印", RelationshipId = "rId999" };
                shape1.Append(imageData1);
                picture1.Append(shape1);
                run1.Append(picture1);
                paragraph2.Append(run1);
                header1.Append(paragraph2);
                headerPart1.Header = header1;
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private void GenerateImagePart1Content(ImagePart imagePart1)
        {
            try
            {
                System.IO.Stream data = GetBinaryDataStream(imagePart1Data);
                imagePart1.FeedData(data);
                data.Close();
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private string imagePart1Data = "";
        private System.IO.Stream GetBinaryDataStream(string base64String)
        {
            return new System.IO.MemoryStream(System.Convert.FromBase64String(base64String));
        }
        public void SetWaterMarkPicture(SPFile file)
        {
            try
            {
                byte[] byteArray = file.OpenBinary();
                imagePart1Data = System.Convert.ToBase64String(byteArray, 0, byteArray.Length);
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }



        #endregion



   #region Get Item from Site Assets Library
        private SPFile GetWatermarkImage(string ItemName)
        {
            SPFile file = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       using (SPSite spSite = new SPSite(SPContext.Current.Web.Url + "/sites/training"))
                       {
                           using (SPWeb spWeb = spSite.OpenWeb())
                           {
                               spWeb.AllowUnsafeUpdates = true;
                               SPList spList = spWeb.Lists.TryGetList("Site Assets");

                               if (spList != null)
                               {
                                   SPQuery qry = new SPQuery();
                                   qry.Query =
                                   string.Format(@"<Where>
                                 <Eq>
                                    <FieldRef Name='LinkFilename' />
                                    <Value Type='Computed'>{0}</Value>
                                </Eq>
                               </Where>", ItemName);
                                   qry.ViewFields = @"<FieldRef Name='FileRef' />";
                                   qry.RowLimit = 1;
                                   SPListItemCollection listItems = spList.GetItems(qry);
                                   if (listItems.Count > 0)
                                   {
                                       SPListItem item = listItems[0];
                                       file = item.File;
                                   }
                               }
                           }
                       }
                   });
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
            return file;
        }


        #endregion