我在较旧的框架中使用过 Rotativa,但从未在 .net 8 中使用过,而且似乎找不到合适的文档。我已经安装了 Rotativa.AspNetCore 1.3.2(不确定这是否是我的情况下使用的正确版本)。
这就是我到目前为止所拥有的。
在program.cs中我添加了:
RotativaConfiguration.Setup(builder.Environment.ContentRootPath, "Rotativa");
我的项目结构:
我的控制器代码:
using Yardstick.BusinessLogic.Interfaces;
namespace Yardstick.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class PDFController : ControllerBase
{
private readonly IAgencyService _agencyService;
public PDFController(IAgencyService agencyService)
{
_agencyService = agencyService;
}
[HttpGet("DownloadAgencyPdfs")]
[ProducesResponseType(200, Type = typeof(FileResult))]
[ProducesResponseType(404)]
public async Task<IActionResult> DownloadAgencyPdfsAsync([FromQuery] int[] ids)
{
var agencies = await _agencyService.GetPdfAgenciesByIdsAsync(ids);
if (agencies != null && agencies.Count > 0)
{
var page = new Rotativa.AspNetCore.ViewAsPdf("Agency.cshtml", agencies[0])
{
PageSize = Rotativa.AspNetCore.Options.Size.A4,
};
if (page != null)
{
// Convert the ViewAsPdf result to a byte array
byte[] pdfBytes = await page.BuildFile(ControllerContext);
// Return the byte array as a file for download
return File(pdfBytes, "application/pdf", "Agencies.pdf");
}
}
return NotFound();
}
}
}
program.cs 中需要更多配置还是什么? 我是否使用了错误版本的 Rotativa? (对我来说 .net 8 Web API)。
我在“page.BuildFile”行上找不到对象引用。
我已经检查过,页面对象不为空。
任何帮助将不胜感激。
我刚刚遇到了同样的问题。我通过在 Program 类中添加以下代码行解决了这个问题:
services.AddControllersWithViews();