我尝试使用代码块删除文档中的水印
代码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);
}
}
}
代码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)
}
}
我已尝试过两个代码块。它会删除水印但会使文档损坏。我需要在此之后恢复。恢复后,文档很好。但我想要正确的解决方案,以便我可以使用C#代码删除水印而不会使文档损坏。请帮忙。
谢谢
答案 0 :(得分:0)
您还需要删除标题部分中的“图片”或“图形”。
例如
List<Picture> pictures = new List<Picture>(headerPart.RootElement.Descendants<Picture>());
...
foreach(Picture p in pictures) {
p.Remove();
}
...
headerPart.DeleteParts(imagePartList);