Search code examples
c#.netdocxxceed

Xceed Docx returns blank document


noob here, i want to export a report as docx file using the xceed docx, but it returns blank document (empty)

MemoryStream stream = new MemoryStream();
        Xceed.Words.NET.DocX document = Xceed.Words.NET.DocX.Create(stream);
        Xceed.Words.NET.Paragraph p = document.InsertParagraph();

        p.Append("Hello World");

        document.Save();

        return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOCHK.docx");

please help


Solution

  • The problem:

    While your data has been written to the MemoryStream, the internal "stream pointer" or cursor (in old-school terminology, think of it as like a tape-head) is at the end of the data you've written:

    Before document.Save():

    stream = [_________________________...]
    ptr    =  ^
    

    After calling document.Save():

    stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
    ptr    =                                                  ^
    

    When you call Controller.File( Stream, String ) it will then proceed to read on from the current ptr location and so only read blank data:

    stream = [<xml><p>my word document</p><p>the end</p></xml>from_this_point__________...]
    ptr    =                                                  ^   
    

    (In reality it won't read anything at all because MemoryStream specifically does not allow reading beyond its internal length limit which by default is the amount of data written to it so far)

    If you reset the ptr to the start of the stream, then when the stream is read the returned data will start from the beginning of written data:

    stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
    ptr    =  ^
    

    Solution:

    You need to reset the MemoryStream to position 0 before reading data from the stream:

    using Xceed.Words.NET;
    
    // ...
    
    MemoryStream stream = new MemoryStream();
    DocX document = DocX.Create( stream );
    Paragraph p = document.InsertParagraph();
    
    p.Append("Hello World");
    
    document.Save();
    
    stream.Seek( 0, SeekOrigin.Begin ); // or `Position = 0`.
    
    return File( stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOCHK.docx" );