0

I'm trying to generate a Word document using Spire.Doc and download it. I can download the document, but it is empty. Does anyone have any idea why that is and can help me? This is my code:

Document doc = new Document();
        Paragraph paragraph = doc.AddSection().AddParagraph();
        paragraph.AppendText("Hello World!");
        doc.SaveToFile("Example.doc", FileFormat.Doc);
        //Saves the Word document to  MemoryStream
        MemoryStream stream = new MemoryStream();
        stream.Position = 0;


        //Download Word document in the browser
        return File(stream, "application/msword", "Example.doc");
  • Where do you actually Save the document to the Stream? All you do is initialise a Stream object. I believe Spire has a `doc.SaveToStream(stream);` which you can use. – Ryan Thomas Jan 11 '22 at 09:44
  • I get errors when i implement your option, can you improve my code? @RyanThomas – user17900933 Jan 11 '22 at 10:13
  • I have provided a working example as an answer, hopefully this works for you, let me know if not :) – Ryan Thomas Jan 11 '22 at 10:40

1 Answers1

0

Here is a working example using .NET Core 3.1 and FreeSpire.Doc v9.9.7

[HttpGet]
public IActionResult DownloadWordDoc()
{
    //Create the document object;
    Document doc = new Document();

    //Create a paragraph and add some text
    var paragraph = doc.AddSection().AddParagraph();
    paragraph.AppendText("Hello World!");

    //Create and save the document to a memory stream
    var ms = new MemoryStream();
    doc.SaveToStream(ms, FileFormat.Docx);
    ms.Seek(0, SeekOrigin.Begin);

    //You may want to make this MIME type string into a constant
    var fsr = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    fsr.FileDownloadName = "Example.docx";

    return fsr;
}

You may also need the following using statements, but I'm presuming you already have them.

using System.IO;
using Spire.Doc;
Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27