How to configure Rotativa in .net 8.0 Web API to generate PDF and download file

175 Views Asked by At

I've used Rotativa in older frameworks, but never in .net 8 and can't seem to find proper documentation. I've installed Rotativa.AspNetCore 1.3.2 (not sure if this is the correct version to use in my case).

So here is what I have so far.

In program.cs I have added :

RotativaConfiguration.Setup(builder.Environment.ContentRootPath, "Rotativa");

My project structure:

enter image description here

My controller code:

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

Do need more configuration in the program.cs or what something? Am I using the wrong version of Rotativa? (for me .net 8 Web API).

I'm getting an Object Reference Not Found on the 'page.BuildFile' line.

I've checked and the page object is not null.

Any help will be much appreciated.

0

There are 0 best solutions below