如何在 Blazor 服务器中使用 wkhtmltopdf Rotativa ViewAsPdf

问题描述 投票:0回答:2

我想使用 Rotativa.AspNetCore.ViewAsPdf("~/Views/MyView/PDF.cshtml", model) 在 Blazor Server 中的操作方式与我在常规 ASP.NET CORE MVC 应用程序中的操作方式相同。

  1. 我在 .NET 8 的 Blazor 服务器项目中安装了“Rotativa.AspNetCore”nuget

  2. 在 Program.cs 中添加了

    RotativaConfiguration.Setup(app.Environment.WebRootPath); app.UseRotativa();

  3. 创建了一个包含 PDF.cshtml 视图的“Views”文件夹

  4. 创建了一个控制器,我通过 httpClient 从我的 razor 组件调用以生成 PDF

[HttpPost("exportPDF")]
public ActionResult ExportPDF(PDFModel model)
{

    return new Rotativa.AspNetCore.ViewAsPdf("~/Views/MyView/PDF.cshtml", model)
    {
        FileName = "MyFile" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf",
        PageSize = Rotativa.AspNetCore.Options.Size.A4,
        PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
        PageMargins = { Left = 15, Right = 15, Top = 15 },
        CustomSwitches = "--footer-center \"MyDocument + "\" --footer-right \"Page: [page]/[toPage]\" --footer-font-size \"6\""
    };
}

我收到“对象引用未设置到对象实例”。来自“Rotativa.AspNetCore”源的异常。

有人在 Blazor 中使用此功能吗?

c# asp.net-core blazor wkhtmltopdf rotativa
2个回答
0
投票

这是官方示例项目

它使用

window.triggerFileDownload
来下载PDF文件,我们只需要像下面这样调用它。

<NavLink class="nav-link" @onclick="@( e => DownloadFileFromURL("pdf-view-name"))">

在我本地运行良好,这是测试结果。

Program.cs 文件应如下所示。

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Rotativaio.AspNetCore;
using RotativaIoBlazorSample.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

var rotativaIoUrl = "https://eunorth.rotativa.io";
var rotativaApiKey = "18d28****c52d383bf53d24d"; 

builder.Services.AddRotativaIo(rotativaIoUrl, rotativaApiKey);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapControllerRoute("mvc", "{controller}/{action}");

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

提示:您应该注册一个帐户,这很重要。然后像上面一样使用它。


0
投票

我自己搞定了。完全可以使用 rotativa.exe 和 Rotativa.AspNetCore nuget 在 Blazor 中使用“ViewAsPdf”方法生成 PDF。我的初始设置很好,我添加了以下两种控制器方法:

public async Task<FileResult> ReturnPDF(int modelId)
{
    PDFModel model = new PDFModel(); //or load from db

    byte[] pdfBytes = await GetPDFBytes(model);

    return File(pdfBytes, "application/pdf");
}

调用以下命令使用 rotativa 创建 pdf:

public async Task<byte[]> GetPDFBytes(PDFModel model)
{

   var pdf =  new Rotativa.AspNetCore.ViewAsPdf("~/Views/PDF.cshtml", model)
   {
       FileName = "Export_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf",
       PageSize = Rotativa.AspNetCore.Options.Size.A4,
       PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
       PageMargins = { Left = 15, Right = 15, Top = 15 },
       CustomSwitches = "--footer-center \"ID_" + model.Id + "\" --footer-right \"Page: [page]/[toPage]\" --footer-font-size \"6\""
};

   byte[] pdfBytes = await pdf.BuildFile(this.ControllerContext);
   return pdfBytes;

}

并通过以下方式从 .razor 组件调用它:

<a href="@(_navManager.BaseUri + "mypage/ReturnPDF")" class="btn btn-danger" target="_blank">PDF_TEST_FileResult</a>

我还尝试创建一个 API 控制器并向其发送包含整个 PDF 模型的发布请求,但 PDF 从未在浏览器中显示,而是在 razor 代码中返回到调用对象。

© www.soinside.com 2019 - 2024. All rights reserved.