Removing watermark in word with OpenXml & C# corrupts document

浪子不回头ぞ 提交于 2021-02-19 06:27:11

问题


I have tried following code block to delete the watermark from the document

Code 1:

private static void DeleteCustomWatermark(WordprocessingDocument package, string watermarkId)
{
    MainDocumentPart maindoc = package.MainDocumentPart;
    if(maindoc!=null)
        {
          var headers = maindoc.GetPartsOfType<HeaderPart>();
          if(headers!=null)
          {
              var head = headers.First(); //we are sure that this header part contains the Watermark with id=watermarkId
              var watermark = head.GetPartById(watermarkId);
              if(watermark!=null)
                  head.DeletePart(watermark);
          }
      }
  }

Code 2:

   public static void DeleteCustomWatermark(WordProcessingDocument package, string headerId)
   {
     //headerId is the id of the header section which contains the watermark
     MainDocumentPart = maindoc = package.MainDocumentPart;
     if(maindoc!=null)
      {
         var header = maindoc.HeaderParts.First(i=>maindoc.GetIdOfPart(i).Equals(headerId));
         if(header!=null)
             maindoc.DeletePart(header)
      }
    }

I have tried both the code blocks. it removes watermark but leaves the document corrupted. I need to recover after this. After recovery the docs are fine. But I want proper solution so that I can remove watermark with C# code without leaving the document corrupted. Please help.

Thanks


回答1:


You also need to remove the "Picture" or "Drawing" in the header parts.

e.g.

List<Picture> pictures = new List<Picture>(headerPart.RootElement.Descendants<Picture>());

...

foreach(Picture p in pictures) {
     p.Remove();
}

...

headerPart.DeleteParts(imagePartList);


来源:https://stackoverflow.com/questions/49167521/removing-watermark-in-word-with-openxml-c-sharp-corrupts-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!