问题
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