it looks like in order to building a pdf from a view it is mandatory to use the “BuildFile(ControllerContext context)” method which requires ControllerContext as an input argument.
So what can we do when there is no HttpContext, for instance consider a scenario in which you are intended to generate some pdfs and email them to some clients in a background job (e.g. IHostedService)? Is there any workaround for it?
I want to be able to send emails with an attached pdf created with Rotativa ASP.Net core every 2 hours, but I get the problem when I do it from the IHostedService, but if it is done with a button from the views it works correctly.
The problem seems to be in this line since the ControllerContext is null.
This is my code:
public async Task<IActionResult> EnviarParosPorCorreo(DateTime FechaInicio, DateTime FechaFinal)
{
var modelo = new VMReporteParo
{
Datos_Paros = Datos_Paro,
Acumulado_Paro = Acu_Paro,
Fallas = Fallas
};
var actionPDF = new ViewAsPdf("ImprimirParos", modelo)
{
CustomSwitches = "--enable-javascript --no-stop-slow-scripts --javascript-delay 3000 --page-size Letter --margin-top 2 --margin-right 0 --margin-bottom 0 --margin-left 0",
PageSize = Rotativa.AspNetCore.Options.Size.Letter,
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
PageMargins = { Left = 1, Right = 1 }
};
byte[] pdfData;
using (var pdfStream = new MemoryStream())
{
pdfData = await actionPDF.BuildFile(ControllerContext);
}
EnviarCorreo(pdfData);
return Ok("Correo enviado exitosamente.");
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromHours(2)); // Run every 2 hours
return Task.CompletedTask;
}
private async void DoWork(object state)
{
using (var scope = _serviceProvider.CreateScope())
{
var reportsController = scope.ServiceProvider.GetRequiredService<ReportsController>();
var startDate = DateTime.Now.Date;
var endDate = DateTime.Now.Date.AddDays(1).AddTicks(-1);
await reportsController.SendParosByMail(startdate, enddate);
}
}
Kevin Rodriguez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.