要在 ASP.NET Core 中產生並下載 Word 或 PDF 報告,請將文件組裝成 MemoryStream,並使用 Results.File 回傳。 不會觸及磁碟,且相同的呼叫會根據一個選項產生 DOCX 或 PDF。

報告功能會以可預測的順序演進。首先有人想在螢幕上看到資料。接著他們想要 Word 檔,因為他們要編輯兩句話並轉寄。再者他們想在下載前先預覽,因為上一次的結果錯誤,沒有人想開十七個檔案才找出問題。

這篇文章就是第三種情況,篇幅足夠一次閱讀完畢。範例放在 GitHub — aspnet-core-report-download-net。

如何在 Web 請求中產生 DOCX 而不觸及磁碟?

Web 請求不該寫入中間檔案。兩個同時的請求會因相同檔名而衝突,清理工作變成某人的排程任務,且容器會因無必要而需要可寫入的磁碟。

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 仍在執行時就會被呼叫,因此你之後要讀取的串流不能在此處被釋放。

上線前需要修正的事項

  • 一次性套用授權,於 singleton 的建構子中完成。不要在每個請求都套用。
  • 限制請求主體。它會一次讀入記憶體,預設限制相當寬鬆。
  • 決定錯誤模板的處理方式。使用 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。