如何在.net 8.0 Web API中配置Rotativa来生成PDF和下载文件

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

我在较旧的框架中使用过 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”行上找不到对象引用。

我已经检查过,页面对象不为空。

任何帮助将不胜感激。

c# .net pdf rotativa
1个回答
0
投票

我刚刚遇到了同样的问题。我通过在 Program 类中添加以下代码行解决了这个问题:

services.AddControllersWithViews();
© www.soinside.com 2019 - 2024. All rights reserved.