Generate and Download Reports in ASP.NET Core

View as MarkdownMarkdown

Set up your AI agent

Give your coding agent live access to the GroupDocs documentation and API reference through the GroupDocs Docs MCP server — no install, no API key. Learn more

claude mcp add --transport http groupdocs-docs https://docs.groupdocs.com/mcp

Also process documents locally

The GroupDocs.Assembly MCP server lets your agent work with files on your machine; they are never uploaded. It needs the .NET 10 SDK or Docker.

claude mcp add groupdocs-assembly -- dnx GroupDocs.Assembly.Mcp --yes
Folders, licensing and more →

The request a web application actually receives is “give me this as a Word file”. This page is the small, complete version of that: a minimal API that takes JSON, fills a template and streams back the document — with a rendered first page so the reader sees the report before downloading it.

Note
A runnable implementation of this page is on GitHub: aspnet-core-report-download-net.

Keep everything in memory

A web request has no business writing intermediate files: two requests would collide over the same name, and a container would need a writable disk for no reason. Both the template and the report are streams.

public byte[] Assemble(string json, bool asPdf)
{
    using MemoryStream data = new(Encoding.UTF8.GetBytes(json));
    using MemoryStream report = new();
    using FileStream template = File.OpenRead(Path.Combine(TemplatesPath, "Customer orders.docx"));

    DocumentAssembler assembler = new();

    if (asPdf)
    {
        assembler.AssembleDocument(
            template, report,
            new LoadSaveOptions(FileFormat.Pdf),
            new DataSourceInfo(new JsonDataSource(data), "customers"));
    }
    else
    {
        assembler.AssembleDocument(
            template, report,
            new DataSourceInfo(new JsonDataSource(data), "customers"));
    }

    return report.ToArray();
}
Warning
There is no overload that takes a template path and an output stream. When the report goes to a stream, open the template as a stream too.

The endpoint

app.MapPost("/api/reports", async (HttpRequest request, ReportBuilder reports, string? format) =>
{
    using StreamReader reader = new(request.Body);
    string json = await reader.ReadToEndAsync();

    bool asPdf = string.Equals(format, "pdf", StringComparison.OrdinalIgnoreCase);

    try
    {
        byte[] report = reports.Assemble(json, asPdf);

        return Results.File(
            report,
            asPdf ? "application/pdf" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            asPdf ? "customer-orders.pdf" : "customer-orders.docx");
    }
    catch (Exception exception)
    {
        // A template or data error belongs to the caller, not to the server.
        return Results.BadRequest(new { error = exception.Message });
    }
});

Results.File with a file name sets Content-Disposition, which is what makes the browser download rather than display.

A preview instead of a viewer

Note
DocumentAssembler.GeneratePreview is available since version 26.11.
public byte[] PreviewPage(byte[] document, int pageNumber, int resolution)
{
    using MemoryStream source = new(document);
    MemoryStream? page = null;

    PreviewOptions previewOptions = new(
        _ => page = new MemoryStream(),
        (_, _) => { /* the stream is read after GeneratePreview returns */ })
    {
        PreviewFormat = PreviewFormats.PNG,
        PageNumbers = new[] { pageNumber },   // 1-based
        Resolution = resolution
    };

    new DocumentAssembler().GeneratePreview(source, previewOptions);
    return page!.ToArray();
}

Before 26.11, showing a report in a browser meant converting the whole document to HTML and accepting that it would not look like the file, or embedding a viewer. One page as a PNG is smaller than either, and it is exactly what the reader is about to download. Full options on Generating document previews.

Note the second callback. The release callback runs while GeneratePreview is still working, so a stream you intend to read afterwards must not be disposed there.

Before this goes to production

  • Apply the licence once, in the constructor of a singleton, not per request.
  • Limit the request body. It is read whole into memory.
  • Return 400, not 500, for a template or data error — it is the caller’s input. With InlineErrorMessages you can return the document instead and let the reader see where it broke; see Templates for incomplete data.
  • Install fonts in the image. Rendering lays text out, and the .NET runtime images ship without fonts — see Running in Docker and serverless.
  • Cache nothing by accident. DocumentAssembler is cheap to create; share the template file, not the assembler.

Frequently asked questions

How do you return a generated Word document from an ASP.NET Core endpoint? Assemble into a MemoryStream and return Results.File(bytes, contentType, fileName). The file name sets Content-Disposition, which is what makes the browser download the file.

Is there an overload taking a template path and an output stream? No. When the result goes to a stream, open the template as a stream as well.

How do you preview a report without a viewer component? DocumentAssembler.GeneratePreview renders a page to PNG with the same engine that produced the document, so the preview matches the file exactly.

Should a template or data error return 500? No. A tag the data cannot satisfy is caller input: return 400.

What has to change before production? Apply the licence once in a singleton rather than per request, limit the request body, decide what a broken template does, and install fonts in the container image.