Open XML - How to add a watermark to a docx document

前端 未结 2 1124
后悔当初
后悔当初 2021-01-04 08:50

I\'m trying to take an existing document and if a header doesn\'t exist, create one, and then add a watermark to the header that says \"DRAFT\" diagonally. I\'ve followed a

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 09:14

    This is now resolved by changing the way the file is opened up. When we change the Main function to:

    static void Main(string[] args)
    {
        //var doc = WordprocessingDocument.Open(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", true);
        //AddWatermark(doc);
        //doc.MainDocumentPart.Document.Save();
        byte[] sourceBytes = File.ReadAllBytes(@"C:\Users\loggedinuser\Desktop\TestDoc.docx");
        MemoryStream inMemoryStream = new MemoryStream();
        inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length);
    
        var doc = WordprocessingDocument.Open(inMemoryStream, true);
        AddWatermark(doc);
        doc.MainDocumentPart.Document.Save();
    
        doc.Close();
        doc.Dispose();
        doc = null;
    
        using (FileStream fileStream = new FileStream(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", System.IO.FileMode.Create))
        {
            inMemoryStream.WriteTo(fileStream);
        }
    
        inMemoryStream.Close();
        inMemoryStream.Dispose();
        inMemoryStream = null;
    }
    

    The document now correctly opens in word. Thanks to Brad B. a coworker at Sonoma Partners for finding this!

提交回复
热议问题