要在 ASP.NET Core 中生成并下载 Word 或 PDF 报告,请将文档组装到 MemoryStream 并使用 Results.File 返回。 不会触及磁盘,同一调用可根据一个选项生成 DOCX 或 PDF。

报告功能以可预见的顺序增长。首先有人想在屏幕上查看数据。然后他们想要 Word 文件,因为他们要编辑两句话并转发。接着他们想在下载之前先预览,因为上一次出错,没人想打开十七个文件去找问题。

本文正是第三种状态,篇幅足够一次阅读完。示例代码在 GitHub 上 — aspnet-core-report-download-net。

如何在 Web 请求中生成 DOCX 而不触及磁盘?

Web 请求不应写入中间文件。两个并发请求会因同名而冲突,清理工作会变成某人的 cron 任务,容器也会因为没有必要而需要可写磁盘。

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();
}

有一点小细节如果不小心会浪费一个小时:没有接受模板路径和输出流的重载。当报告写入流时,模板也必须以流的方式打开。

返回文件的端点

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 使用文件名会设置 Content-Disposition,这正是让浏览器下载而不是尝试显示的原因。

catch 是有意为之。数据无法满足的情况应返回 400,而不是 500 —— 你的监控不应因为有人提交了错误的 JSON 而报警。

如何在用户下载之前预览报告?

26.11 新增 — DocumentAssembler.GeneratePreview 是 GroupDocs.Assembly for .NET 的新 API。

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);

在此功能出现之前,在浏览器中显示报告只能选择两种不理想的方式:将整个文档转换为 HTML 并接受其外观与文件不一致,或嵌入查看器。将单页导出为 PNG 比这两者都更小,而且正好是读者即将下载的内容——相同的渲染器、相同的布局、相同的字体。

注意第二个回调。它在 GeneratePreview 仍在工作时运行,因此你之后打算读取的流不能在此处被释放。

投产前需要修复的事项

  • 只在单例的构造函数中应用一次许可证。不要在每个请求中都应用。
  • 限制请求体大小。它会一次性读取到内存中,默认限制较宽松。
  • 决定错误模板的处理方式。使用 InlineErrorMessages 可以返回文档并让读者看到出错位置 —— 参见 Templates that survive incomplete data。
  • 在镜像中安装字体。预览需要排版文本,而 .NET 运行时镜像没有字体 —— 参见 Generating documents in Docker。

常见问题

如何从 ASP.NET Core 端点返回生成的 Word 文档?
将文档组装到 MemoryStream 并返回 Results.File(bytes, contentType, fileName)。文件名决定了 Content-Disposition,从而让浏览器下载而不是尝试显示。

可以从同一端点返回 PDF 吗?
可以 —— 添加 new LoadSaveOptions(FileFormat.Pdf) 并将 content type 改为 application/pdf。

有没有接受模板路径和输出流的重载?
没有。当报告写入流时,模板也必须以流的方式打开。如果不注意会浪费一个小时。

如何在浏览器中预览报告而不使用查看器组件?
DocumentAssembler.GeneratePreview 使用生成文档的同一引擎将页面渲染为 PNG,因此预览与用户即将下载的文件一致。

错误的模板应该返回 500 吗?
不应该。数据无法满足的情况属于调用方输入错误 —— 返回 400 并避免触发告警。

这在容器中能工作吗?
可以,只要镜像中安装了字体。预览需要排版文本,而 .NET 运行时镜像默认没有任何字体 —— 参见 Generating documents in Docker。

试一试

git clone https://github.com/groupdocs-assembly/aspnet-core-report-download-net.git
cd aspnet-core-report-download-net
dotnet run --project src/ReportService

在左侧编辑数据,点击 Show first page,下载为 DOCX 或 PDF。前端约 120 行纯 JavaScript —— 没有框架、没有 CDN,也无需构建。

参考页面是 Generate reports in ASP.NET Core。