2015-10-15 122 views

回答

1

我试图找到一种方法,这里是答案:

public void FillDocument(Stream stream, XDocument document) 
    {  

using (WordprocessingDocument wordDocument = 
      WordprocessingDocument.Open(stream, true)) 
     { 
      List<SdtElement> descendants = wordDocument.MainDocumentPart.Document.Descendants<SdtElement>().ToList(); 
      foreach (HeaderPart headerPart in wordDocument.MainDocumentPart.HeaderParts) 
      { 
       descendants.AddRange(headerPart.Header.Descendants<SdtElement>().ToList()); 
      } 
      foreach (var footerPart in wordDocument.MainDocumentPart.FooterParts) 
      { 
       descendants.AddRange(footerPart.Footer.Descendants<SdtElement>().ToList()); 
      } 

      XDocument doc = document; 


      foreach (SdtElement item in descendants) 
      { 
       SdtAlias alias = item.Descendants<SdtAlias>().FirstOrDefault(); 

       if (alias != null) 
       { 
        string sdtTitle = alias.Val.Value; 

        //if Sdt Content Control is Picture 
        string imageContent = (from xElement in doc.Descendants("Picture") where xElement.Attribute("Id").Value == sdtTitle select xElement.Value).FirstOrDefault(); 
        if (imageContent != null) 
        { 
         MemoryStream result = (MemoryStream)StringToStream(imageContent); 

         D.Blip blipElement = item.Descendants<D.Blip>().FirstOrDefault(); 
         string imageId = "default value"; 

         if (blipElement != null) 
         { 
          imageId = blipElement.Embed.Value; 

          ImagePartType imagePartType = ImagePartType.Png; 

          //Add image and change embeded id. 
          ImagePart imagePart = null; 
          Type p = item.Parent.GetType(); 
          switch (p.Name) 
          { 
           case "Header": 
            HeaderPart headerPart = ((Header)(item.Parent)).HeaderPart; 
            imagePart = headerPart.AddImagePart(imagePartType); 
            imagePart.FeedData(result); 
            blipElement.Embed = headerPart.GetIdOfPart(imagePart); 
            break; 
           case "Body": 
            MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart; 
            imagePart = mainDocumentPart.AddImagePart(imagePartType); 
            imagePart.FeedData(result); 
            blipElement.Embed = mainDocumentPart.GetIdOfPart(imagePart); 
            break; 
           case "Footer": 
            FooterPart footerPart = ((Footer)(item.Parent)).FooterPart; 
            imagePart = footerPart.AddImagePart(imagePartType); 
            imagePart.FeedData(result); 
            blipElement.Embed = footerPart.GetIdOfPart(imagePart); 
            break; 
           default: 
            break; 
          } 

         } 
         continue; 
        } 
      } 

     } 

    }} 

它工作正常,并且可以在页眉或页脚或身体占满画面内容的控制!

相关问题