user3419151
user3419151

Reputation: 1

Create a DocX and save to client machine c#

I am using the library from: https://github.com/xceedsoftware/DocX/blob/master/Xceed.Document.NET/Src/Document.cs in an MVC Project.

The functionality is now sitting on my server;

 public void Build(Results umbracoFormValues)
    {
        var ms = new MemoryStream();
        using (var document = DocX.Create(ms))
        {
            var heading = new Heading();
            heading.Branding(document);
            var sections = umbracoFormValues.SectionResults;
            foreach (var section in sections)
            {
                heading.Render(document, section);
                ConstructFieldTypes(document, section);
                new Footer().Render(document);
            }
            ms.Position = 0;
            document.SaveAs(new CreateNew().DocumentFileName(umbracoFormValues));
        }
    }

How do I then grab the newly created file and make it downloadable to the user/client?

Many thanks in advance.

Upvotes: 0

Views: 282

Answers (1)

Ortiga
Ortiga

Reputation: 8824

You can change your Build method to return the stream:

public Stream Build(Results umbracoFormValues)
{
    var ms = new MemoryStream();
    //code omitted for simplicity
    return ms;
}

Then in your action:

public async Task<IActionResult> MyAction(Results umbracoFormValues)
{
    var stream = Build(umbracoFormValues);

    var mimeType = "application/vnd.openxmlformats-officedocument.wordprocessing";
    var fileName = "myReport.docx";

    return File(stream, mimeType, fileName);
}

Keep in mind that there may be some differences depending on the dotnet core/framework you're using, as you haven't specified that.

Upvotes: 2

Related Questions