To generate and download a Word or PDF report in ASP.NET Core, assemble the document into a
MemoryStream and return it with Results.File. Nothing touches the disk, and the same call
produces a DOCX or a PDF depending on one option.
Reporting features grow in a predictable order. First somebody wants the data on a screen. Then they want it as a Word file, because they are going to edit two sentences and forward it. Then they want to see it before they download it, because the last one was wrong and nobody wants to open seventeen files to find out.
This post is that third state, small enough to read in one sitting. The sample is on GitHub — aspnet-core-report-download-net.
How do you generate a DOCX in a web request without touching disk?
A web request has no business writing intermediate files. Two concurrent requests collide over the same name, cleanup becomes somebody’s cron job, and a container needs a writable disk for no reason.
public byte[] Assemble(string json, bool asPdf)
{
using MemoryStream data = new(Encoding.UTF8.GetBytes(json));
using MemoryStream report = new();
using FileStream template = File.OpenRead("templates/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();
}
One small thing that costs an hour if you meet it by surprise: there is no overload taking a template path and an output stream. When the report goes to a stream, open the template as a stream too.
The endpoint that returns the file
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 is the caller's input, not a server fault.
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 try to display.
The catch is deliberate. A tag the data cannot satisfy is a 400, not a 500 — and your
monitoring should not page anybody because somebody posted the wrong JSON.
How do you show a report before the user downloads it?
New in 26.11 —
DocumentAssembler.GeneratePreviewis a new API in GroupDocs.Assembly for .NET.
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);
Before this existed, showing a report in a browser meant one of two bad options: convert the whole document to HTML and accept that it does not look like the file, or embed a viewer. A single page as a PNG is smaller than either, and it is exactly what the reader is about to download — the same renderer, the same layout, the same fonts.
Watch the second callback. It runs while GeneratePreview is still working, so a stream you intend
to read afterwards must not be disposed there.
What to fix 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, and the default limits are generous.
- Decide what a bad template does. With
InlineErrorMessagesyou can return the document and let the reader see where it broke — see Templates that survive incomplete data. - Install fonts in the image. The preview lays text out, and the .NET runtime images have no fonts — see Generating documents in Docker.
Questions people ask
How do I 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 is what sets Content-Disposition, which is what makes the browser download instead of trying
to display.
Can I return a PDF from the same endpoint?
Yes — add new LoadSaveOptions(FileFormat.Pdf) and switch the content type to application/pdf.
Is there an overload that takes a template path and an output stream? No. When the report goes to a stream, open the template as a stream too. This costs an hour if you meet it by surprise.
How do I preview a report in the browser 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 the user is about to download.
Should a bad template be a 500?
No. A tag the data cannot satisfy is the caller’s input — return 400 and keep it out of your
alerting.
Does this work in a container? Yes, once the image has fonts. The preview lays text out, and the .NET runtime images ship without any — see Generating documents in Docker.
Try it
git clone https://github.com/groupdocs-assembly/aspnet-core-report-download-net.git
cd aspnet-core-report-download-net
dotnet run --project src/ReportService
Edit the data on the left, press Show first page, download as DOCX or PDF. The front end is about 120 lines of plain JavaScript — no framework, no CDN, nothing to build.
The reference page is Generate reports in ASP.NET Core.