Try con QuestPDF
All checks were successful
Optimized Build and Deploy / remote-build-and-deploy (push) Successful in 7m36s

Se elimina Puppeteer y Chromium. Se utiliza QuestPDF para mayor velocidad y sin Razor.
This commit is contained in:
2025-06-20 19:04:23 -03:00
parent 1373bcf9ca
commit a5bcbefa52
11 changed files with 317 additions and 430 deletions

View File

@@ -14,6 +14,8 @@ using GestionIntegral.Api.Data.Repositories.Distribucion;
using GestionIntegral.Api.Services.Distribucion;
using GestionIntegral.Api.Services.Pdf;
using GestionIntegral.Api.Dtos.Reportes.ViewModels;
using GestionIntegral.Api.Controllers.Reportes.PdfTemplates;
using QuestPDF.Infrastructure;
namespace GestionIntegral.Api.Controllers
{
@@ -29,7 +31,7 @@ namespace GestionIntegral.Api.Controllers
private readonly IEmpresaRepository _empresaRepository;
private readonly IDistribuidorRepository _distribuidorRepository; // Para obtener el nombre del distribuidor
private readonly INovedadCanillaService _novedadCanillaService;
private readonly IPdfGeneratorService _pdfGeneratorService;
private readonly IQuestPdfGenerator _pdfGenerator;
// Permisos
private const string PermisoVerReporteExistenciaPapel = "RR005";
@@ -51,7 +53,7 @@ namespace GestionIntegral.Api.Controllers
IPublicacionRepository publicacionRepository,
IEmpresaRepository empresaRepository,
IDistribuidorRepository distribuidorRepository,
IPdfGeneratorService pdfGeneratorService)
IQuestPdfGenerator pdfGenerator)
{
_reportesService = reportesService;
_novedadCanillaService = novedadCanillaService;
@@ -60,7 +62,7 @@ namespace GestionIntegral.Api.Controllers
_publicacionRepository = publicacionRepository;
_empresaRepository = empresaRepository;
_distribuidorRepository = distribuidorRepository;
_pdfGeneratorService = pdfGeneratorService;
_pdfGenerator = pdfGenerator;
}
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
@@ -98,76 +100,58 @@ namespace GestionIntegral.Api.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetReporteExistenciaPapelPdf(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] int? idPlanta,
[FromQuery] bool consolidado = false)
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] int? idPlanta,
[FromQuery] bool consolidado = false)
{
if (!TienePermiso(PermisoVerReporteExistenciaPapel)) return Forbid();
var (data, error) = await _reportesService.ObtenerExistenciaPapelAsync(fechaDesde, fechaHasta, idPlanta, consolidado);
if (error != null)
{
return BadRequest(new { message = error });
}
if (data == null || !data.Any())
{
return NotFound(new { message = "No hay datos para generar el PDF con los parámetros seleccionados." });
}
if (error != null) return BadRequest(new { message = error });
if (data == null || !data.Any()) return NotFound(new { message = "No hay datos para generar el PDF." });
try
{
// Determinar la plantilla y el nombre de la planta
string templatePath;
string nombrePlantaParam = "Consolidado";
IDocument document; // Se declara aquí
if (consolidado)
{
templatePath = "Controllers/Reportes/Templates/ReporteExistenciaPapelConsolidado.cshtml";
var viewModel = new ExistenciaPapelConsolidadoViewModel
{
Existencias = data,
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
document = new ExistenciaPapelConsolidadoDocument(viewModel);
}
else
{
templatePath = "Controllers/Reportes/Templates/ReporteExistenciaPapel.cshtml";
if (idPlanta.HasValue)
if (!idPlanta.HasValue)
{
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
nombrePlantaParam = planta?.Nombre ?? "N/A";
return BadRequest(new { message = "El idPlanta es requerido para reportes no consolidados." });
}
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
var viewModel = new ExistenciaPapelViewModel
{
Existencias = data,
NombrePlanta = planta?.Nombre ?? $"Planta ID {idPlanta.Value}", // Manejo por si no se encuentra
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
document = new ExistenciaPapelDocument(viewModel);
}
// Crear el ViewModel para la plantilla Razor
var viewModel = new ExistenciaPapelViewModel
{
Existencias = data,
NombrePlanta = nombrePlantaParam,
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
// Configurar opciones de PDF (márgenes, etc.)
var pdfOptions = new PdfGenerationOptions
{
Margin = new PuppeteerSharp.Media.MarginOptions
{
Top = "2cm",
Bottom = "2cm",
Left = "1cm",
Right = "1cm"
},
Format = PuppeteerSharp.Media.PaperFormat.A4,
// Podríamos agregar un encabezado/pie de página aquí si fuera necesario
// FooterTemplate = "<div style='font-size:8px; width:100%; text-align:center;'>Página <span class='pageNumber'></span> de <span class='totalPages'></span></div>"
};
// Generar el PDF
byte[] pdfBytes = await _pdfGeneratorService.GeneratePdfFromRazorTemplateAsync(templatePath, viewModel, pdfOptions);
byte[] pdfBytes = await _pdfGenerator.GeneratePdfAsync(document);
string fileName = $"ExistenciaPapel_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}_{(consolidado ? "Consolidado" : $"Planta{idPlanta}")}.pdf";
return File(pdfBytes, "application/pdf", fileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al generar PDF para Existencia de Papel.");
_logger.LogError(ex, "Error al generar PDF con QuestPDF para Existencia de Papel.");
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al generar el PDF del reporte.");
}
}