From 4cf2f94a7f3e0c809f7dd82d1ba74c1a6b74aeda Mon Sep 17 00:00:00 2001 From: Perea Date: Mon, 19 Jan 2026 09:05:47 +0100 Subject: [PATCH] prueba fallo de imprimir --- HerramientaCASA.sln | 4 +- .../Layout/ConfiguracionLayout.razor | 9 +- .../Components/Layout/LoginLayout.razor | 47 ++--- .../Components/Layout/MainLayout.razor | 2 +- .../Components/Pages/HerramientaCASAS.razor | 29 ++- .../Components/Pages/HerramientaURBAN.razor | 5 +- .../Components/Pages/Licitaciones.razor | 6 +- .../Components/Pages/LicitacionesURBAN.razor | 6 +- .../Components/Pages/Login/Login.razor | 2 +- HerramientaCASA/Program.cs | 41 +++++ HerramientaCASA/ServicioPDF.cs | 166 ++++-------------- HerramientaCASA/appsettings.json | 7 +- .../wwwroot/Imprimir/HeaderImprimir.html | 12 +- 13 files changed, 141 insertions(+), 195 deletions(-) diff --git a/HerramientaCASA.sln b/HerramientaCASA.sln index 64adfb6..aa3865f 100644 --- a/HerramientaCASA.sln +++ b/HerramientaCASA.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.11.35312.102 +# Visual Studio Version 18 +VisualStudioVersion = 18.1.11312.151 d18.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HerramientaCASA", "HerramientaCASA\HerramientaCASA.csproj", "{60B569DA-FC18-45B9-8ACC-8E29D8C2EA2C}" EndProject diff --git a/HerramientaCASA/Components/Layout/ConfiguracionLayout.razor b/HerramientaCASA/Components/Layout/ConfiguracionLayout.razor index ba27f0d..598c71b 100644 --- a/HerramientaCASA/Components/Layout/ConfiguracionLayout.razor +++ b/HerramientaCASA/Components/Layout/ConfiguracionLayout.razor @@ -147,7 +147,7 @@ { urlAnterior = await JS.InvokeAsync("eval", "document.referrer"); bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false); - string urlColegio = bd.enumeraciones.First(x => x.Codigo.Contains("CW.URLCOLEGIO")).ValorAlfabetico1; + string urlColegio = bd.enumeraciones.FirstOrDefault(x => x.Codigo.Contains("CW.URLCOLEGIO")).ValorAlfabetico1; if (!string.IsNullOrEmpty(urlAnterior)) @@ -158,18 +158,13 @@ if (rutaActual != "Denegado") { - if (!urlAnterior.Contains(urlColegio)) + if (urlColegio != null && !urlAnterior.Contains(urlColegio)) { Navigation.NavigateTo("/Denegado", true); } } } - else - { - Navigation.NavigateTo("/Denegado", true); - } - if (userState.idUser == 0) { diff --git a/HerramientaCASA/Components/Layout/LoginLayout.razor b/HerramientaCASA/Components/Layout/LoginLayout.razor index 293f024..ae91c73 100644 --- a/HerramientaCASA/Components/Layout/LoginLayout.razor +++ b/HerramientaCASA/Components/Layout/LoginLayout.razor @@ -51,33 +51,36 @@ protected override async Task OnAfterRenderAsync(bool firstRender) { - // if (firstRender) - // { - // urlAnterior = await JS.InvokeAsync("eval", "document.referrer"); - // bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false); - // string urlColegio = bd.enumeraciones.First(x => x.Codigo.Contains("CW.URLCOLEGIO")).ValorAlfabetico1; + if (firstRender) + { + urlAnterior = await JS.InvokeAsync("eval", "document.referrer"); + bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false); + string urlColegio = bd.enumeraciones.First(x => x.Codigo.Contains("CW.URLCOLEGIO")).ValorAlfabetico1; - // if (!string.IsNullOrEmpty(urlAnterior)) - // { + if (!string.IsNullOrEmpty(urlAnterior)) + { - // rutaActual = Navigation.ToBaseRelativePath(Navigation.Uri); + rutaActual = Navigation.ToBaseRelativePath(Navigation.Uri); - // if (rutaActual != "Denegado") - // { - // if (!urlAnterior.Contains(urlColegio)) - // { - // Navigation.NavigateTo("/Denegado", true); - // } - // } + if (rutaActual != "Denegado") + { + if (urlColegio != null && !urlAnterior.Contains(urlColegio)) + { + Navigation.NavigateTo("/Denegado", true); + } + } - // } - // else - // { - // Navigation.NavigateTo("/Denegado", true); - // } - // StateHasChanged(); - // } + } + else + { + if (urlColegio != null) + { + Navigation.NavigateTo("/Denegado", true); + } + } + StateHasChanged(); + } } } diff --git a/HerramientaCASA/Components/Layout/MainLayout.razor b/HerramientaCASA/Components/Layout/MainLayout.razor index 275b583..f949440 100644 --- a/HerramientaCASA/Components/Layout/MainLayout.razor +++ b/HerramientaCASA/Components/Layout/MainLayout.razor @@ -140,7 +140,7 @@ if (rutaActual != "Denegado") { - if (!urlAnterior.Contains(urlColegio)) + if (urlColegio != null && !urlAnterior.Contains(urlColegio)) { Navigation.NavigateTo("/Denegado", true); } diff --git a/HerramientaCASA/Components/Pages/HerramientaCASAS.razor b/HerramientaCASA/Components/Pages/HerramientaCASAS.razor index 038992a..c188492 100644 --- a/HerramientaCASA/Components/Pages/HerramientaCASAS.razor +++ b/HerramientaCASA/Components/Pages/HerramientaCASAS.razor @@ -376,7 +376,18 @@ public async Task imprimir() { - var cssPath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "Content", "Site.css"); + + var a = PdfService.obtenerURL(); + + mensajes.Add(new ToastMessage + { + Type = ToastType.Danger, + Message = a, + }); + + try + { + var cssPath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "Content", "Site.css"); var cssContent = await File.ReadAllTextAsync(cssPath); var contenidoHtml = await JSA.InvokeAsync("obtenerPDFImprimir", "DespachoImprimir"); @@ -392,14 +403,22 @@ "; - var logoByte = bd.ficheros.First(x => x.NombreFichero.Contains("LogoColegio2")).Fichero; - string logo64 = Convert.ToBase64String(logoByte); + var arrayPDF = PdfService.GenerarPdf("fullHtml"); + - var arrayPDF = PdfService.GenerarPdf(fullHtml, logo64); string base64Pdf = Convert.ToBase64String(arrayPDF); - await JSA.InvokeVoidAsync("descargarPdf", "SimulacionHerramientaCASA_" + DateTime.Now , base64Pdf); + await JSA.InvokeVoidAsync("descargarPdf", "SimulacionHerramientaCASA_" + DateTime.Now , null); + }catch(Exception ex) + { + mensajes.Add(new ToastMessage + { + Type = ToastType.Danger, + Message = ex.Message, + }); + } + } } diff --git a/HerramientaCASA/Components/Pages/HerramientaURBAN.razor b/HerramientaCASA/Components/Pages/HerramientaURBAN.razor index e40b8e1..df6c763 100644 --- a/HerramientaCASA/Components/Pages/HerramientaURBAN.razor +++ b/HerramientaCASA/Components/Pages/HerramientaURBAN.razor @@ -372,11 +372,8 @@ "; - var logoByte = bd.ficheros.First(x => x.NombreFichero.Contains("LogoColegio2")).Fichero; - string logo64 = Convert.ToBase64String(logoByte); - - var arrayPDF = PdfService.GenerarPdf(fullHtml, logo64); + var arrayPDF = PdfService.GenerarPdf(fullHtml); string base64Pdf = Convert.ToBase64String(arrayPDF); diff --git a/HerramientaCASA/Components/Pages/Licitaciones.razor b/HerramientaCASA/Components/Pages/Licitaciones.razor index 1dc7285..632f8b9 100644 --- a/HerramientaCASA/Components/Pages/Licitaciones.razor +++ b/HerramientaCASA/Components/Pages/Licitaciones.razor @@ -540,11 +540,7 @@ "; - var logoByte = bd.ficheros.First(x => x.NombreFichero.Contains("LogoColegio2")).Fichero; - - string logo64 = Convert.ToBase64String(logoByte); - - var arrayPDF = PdfService.GenerarPdf(fullHtml, logo64); + var arrayPDF = PdfService.GenerarPdf(fullHtml); string base64Pdf = Convert.ToBase64String(arrayPDF); diff --git a/HerramientaCASA/Components/Pages/LicitacionesURBAN.razor b/HerramientaCASA/Components/Pages/LicitacionesURBAN.razor index f270e1a..174a6f2 100644 --- a/HerramientaCASA/Components/Pages/LicitacionesURBAN.razor +++ b/HerramientaCASA/Components/Pages/LicitacionesURBAN.razor @@ -611,11 +611,7 @@ "; - var logoByte = bd.ficheros.First(x => x.NombreFichero.Contains("LogoColegio2")).Fichero; - - string logo64 = Convert.ToBase64String(logoByte); - - var arrayPDF = PdfService.GenerarPdf(fullHtml, logo64); + var arrayPDF = PdfService.GenerarPdf(fullHtml); string base64Pdf = Convert.ToBase64String(arrayPDF); diff --git a/HerramientaCASA/Components/Pages/Login/Login.razor b/HerramientaCASA/Components/Pages/Login/Login.razor index 86fae7f..2f773d4 100644 --- a/HerramientaCASA/Components/Pages/Login/Login.razor +++ b/HerramientaCASA/Components/Pages/Login/Login.razor @@ -70,7 +70,7 @@ { bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false); - logoColegioArray = bd.ficheros.Where(x => x.NombreFichero == "LogoColegio").Select(x => x.Fichero).First(); + logoColegioArray = bd.ficheros.Where(x => x.NombreFichero == "LogoColegio").Select(x => x.Fichero).First(); await ProtectedLocalStore.SetAsync("idUsuario", 0); await ProtectedLocalStore.SetAsync("EsAdmin", false); diff --git a/HerramientaCASA/Program.cs b/HerramientaCASA/Program.cs index 7a53743..43981c1 100644 --- a/HerramientaCASA/Program.cs +++ b/HerramientaCASA/Program.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; using Microsoft.AspNetCore.Mvc; using System.Globalization; using System.Runtime.InteropServices; +using tsUtilidades; var builder = WebApplication.CreateBuilder(args); @@ -41,6 +42,7 @@ builder.Services.AddRazorPages() options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles; }); + // Necesario para ver porqué está fallando ciertas cosas que dan el error Circuit builder.Services.AddServerSideBlazor().AddCircuitOptions(option => { option.DetailedErrors = true; }); builder.Services.AddHttpContextAccessor(); @@ -87,6 +89,8 @@ app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); +app.MapRazorPages(); + app.UseAntiforgery(); app.Use(async (context, next) => @@ -117,6 +121,43 @@ app.Use(async (context, next) => await next(); }); + +app.MapGet("/HeaderPdf", () => +{ + var bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: true); + + var logoByte = bd.ficheros + .First(x => x.NombreFichero.Contains("LogoColegio2")) + .Fichero; + + var logoBase64 = Convert.ToBase64String(logoByte); + + string html = $"\r\n" + + $"\r\n" + + $"\r\n" + + $"\r\n" + + $"\r\n" + + $"\r\n" + + $"\r\n" + + $"
\r\n" + + $"\r\n" + + $" \r\n" + + $"\r\n" + + $"\r\n" + + $"\r\n" + + $"
\r\n" + + $"Image\r\n" + + $"\r\n" + + $"Costes Asociados a los Servicios de Arquitectura - CASA\r\n" + + $"
\r\n" + + $"
\r\n" + + $"\r\n" + + $""; + + return Results.Content(html, "text/html"); +}); + + app.MapRazorComponents() .AddInteractiveServerRenderMode(); diff --git a/HerramientaCASA/ServicioPDF.cs b/HerramientaCASA/ServicioPDF.cs index 729760d..e024e43 100644 --- a/HerramientaCASA/ServicioPDF.cs +++ b/HerramientaCASA/ServicioPDF.cs @@ -1,174 +1,76 @@ -using DinkToPdf; +using bdHerramientaCACOA.dbcontext; +using BlazorBootstrap; +using DinkToPdf; using DinkToPdf.Contracts; using DocumentFormat.OpenXml.Packaging; +using Microsoft.EntityFrameworkCore.Metadata.Internal; using System.Text; namespace HerramientaCASA { public class ServicioPDF { private readonly IConverter _converter; + private readonly IWebHostEnvironment _env; - public ServicioPDF(IConverter converter) + public ServicioPDF(IConverter converter, IWebHostEnvironment env) { _converter = converter; + _env = env; } - public byte[] GenerarPdf(string html, string logoBase64) + public byte[] GenerarPdf(string html) { - var headerPath = Path.Combine(Path.GetTempPath(), $"header_{Guid.NewGuid()}.html"); - File.WriteAllText(headerPath, rellenarHeader(logoBase64)); try { var doc = new HtmlToPdfDocument() { GlobalSettings = { - PaperSize = PaperKind.A4, - Orientation = Orientation.Portrait, - Margins= new MarginSettings - { - Top = 11.8, - Left = 0, - Right = 0, - Bottom = 10 + PaperSize = PaperKind.A4, + Orientation = DinkToPdf.Orientation.Portrait, + Margins= new MarginSettings + { + Top = 11.8, + Left = 0, + Right = 0, + Bottom = 10 + }, }, - }, Objects = { new ObjectSettings() { HtmlContent = html, HeaderSettings = new HeaderSettings { - HtmUrl = headerPath + //HtmUrl = Path.Combine(Environment.CurrentDirectory, "wwwroot", "Imprimir", "HeaderImprimir.html") + //HtmUrl = "https://localhost:7275/HeaderPdf" + HtmUrl = obtenerURL() }, - } } }; return _converter.Convert(doc); } - finally + catch (Exception ex) { - if (headerPath != null && File.Exists(headerPath)) - { - File.Delete(headerPath); - } + throw new Exception(ex.Message); } - } - private string rellenarHeader(string logoBase64) + public string obtenerURL() { - string html = ""; + string url = ""; + var bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false); - html = $"\r\n" + - $"\r\n" + - $"\r\n" + - $"\r\n" + - $"\r\n"+ - $"\r\n"+ - $"\r\n" + - $"
\r\n"+ - $"\r\n" + - $" \r\n"+ - $"\r\n"+ - $"\r\n"+ - $"\r\n"+ - $"
\r\n" + - $"Image\r\n" + - $"\r\n"+ - $"Costes Asociados a los Servicios de Arquitectura - CASA\r\n"+ - $"
\r\n"+ - $"
\r\n"+ - $"\r\n"+ - $""; + if (_env.IsDevelopment()) + { + url = "https://localhost:7275/HeaderPdf"; + } + else + { + url = bd.enumeraciones.First(x => x.Codigo.Contains("CW.DOMINIO")).ValorAlfabetico1 + "/HeaderPdf"; + } - return html; + return url; } - - // /// - // /// Convierte HTML a PDF (bytes) usando HtmlRenderer.PdfSharpCore, inyectando site.css. - - // /// - // /// - // /// Contenido HTML del body (o el documento completo). Si pasas solo el body, se envolverá automáticamente. - // /// - // /// Ruta al archivo site.css en el servidor (p. ej. "wwwroot/css/site.css"). - // /// - // /// (Opcional) Base para resolver rutas relativas. - // /// Se inserta como <base href="..."> en <head>. - // /// - // /// Tamaño de página (A4 por defecto). - // /// Margen en puntos (40 por defecto). - // public byte[] HtmlToPdfWithSiteCss( - // string htmlBody, - // string siteCssPath, - // string? baseUri = null, - // PdfSharpCore.PageSize pageSize = PdfSharpCore.PageSize.A4, - // int margin = 40 - // ) - // { - // if (string.IsNullOrWhiteSpace(htmlBody)) - // throw new ArgumentException("El HTML no puede estar vacío.", nameof(htmlBody)); - - // if (string.IsNullOrWhiteSpace(siteCssPath) || !File.Exists(siteCssPath)) - // throw new FileNotFoundException("No se encontró el archivo CSS indicado.", siteCssPath); - - // // Evitar problemas de codificación (tildes, ñ) - // Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - - // // Lee el CSS local - // var css = File.ReadAllText(siteCssPath); - - // // HTML mínimo - // bool isFullHtml = htmlBody.Contains(""; - // if (!string.IsNullOrWhiteSpace(baseUri)) - // headExtras = $"{headExtras}"; - - // string fullHtml = isFullHtml - // ? InjectIntoHead(htmlBody, headExtras) - // : $"{headExtras}{htmlBody}"; - - // var cfg = new PdfGenerateConfig - // { - // PageSize = (PdfSharp.PageSize)pageSize, - // MarginLeft = margin, - // MarginRight = margin, - // MarginTop = margin, - // MarginBottom = margin - // }; - - // using var doc = PdfGenerator.GeneratePdf(fullHtml, cfg); - // using var ms = new MemoryStream(); - // doc.Save(ms); - // return ms.ToArray(); - - // // Inserta contenido en (si existe); si no, lo crea. - // static string InjectIntoHead(string html, string toInject) - // { - // int headOpen = html.IndexOf("= 0) - // { - // int headClose = html.IndexOf('>', headOpen); - // if (headClose > headOpen) - // { - // return html.Insert(headClose + 1, toInject); - // } - // } - // // No hay , lo creamos - // int htmlOpen = html.IndexOf("= 0) - // { - // int htmlTagEnd = html.IndexOf('>', htmlOpen); - // if (htmlTagEnd > htmlOpen) - // { - // return html.Insert(htmlTagEnd + 1, $"{toInject}"); - // } - // } - // // Documento raro: envolvemos completo - // return $"{toInject}{html}"; - // } - // } - //} } } \ No newline at end of file diff --git a/HerramientaCASA/appsettings.json b/HerramientaCASA/appsettings.json index 4e80a67..eec639f 100644 --- a/HerramientaCASA/appsettings.json +++ b/HerramientaCASA/appsettings.json @@ -14,8 +14,11 @@ //"ReadOnlyConnection": "Server=77.229.174.85;Port=22222;Database=herramientascacoa;User Id=cacoa;Password=cacoa2018-;" // CONEXIÓN COACYLE - "WriteConnection": "Server=77.229.174.85;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;", - "ReadOnlyConnection": "Server=77.229.174.85;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;" + //"WriteConnection": "Server=77.229.174.85;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;", + //"ReadOnlyConnection": "Server=77.229.174.85;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;" + + "WriteConnection": "Server=localhost;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;", + "ReadOnlyConnection": "Server=localhost;Port=22222;Database=herramientascoacyle;User Id=cacoa;Password=cacoa2018-;" }, "AllowedHosts": "*" } diff --git a/HerramientaCASA/wwwroot/Imprimir/HeaderImprimir.html b/HerramientaCASA/wwwroot/Imprimir/HeaderImprimir.html index 4d0e7af..83189f9 100644 --- a/HerramientaCASA/wwwroot/Imprimir/HeaderImprimir.html +++ b/HerramientaCASA/wwwroot/Imprimir/HeaderImprimir.html @@ -9,19 +9,13 @@ -
- Image + Image Costes Asociados a los Servicios de Arquitectura - CASA
+ - - - \ No newline at end of file + \ No newline at end of file