using DevExpress.DataAccess.Json; using DevExpress.XtraReports.UI; using Microsoft.Extensions.Logging; namespace Lux.Report.Data.Services { public class PdfReportService : IPdfReportService { private readonly IFileService _fileService; private readonly ILogger _logger; public PdfReportService(IFileService fileService, ILogger logger) { _fileService = fileService; _logger = logger; } public async Task GeneratePdfAsync( int reqId, string repType, string selFile, string codGroup, string imgFullUrl, string dataFullUrl ) { _logger.LogInformation($"Generating PDF for reqId={reqId}, repType={repType}, selFile={selFile}, codGroup={codGroup}"); string repPath = Path.Combine("reports", repType, selFile); byte[] pdfBytes = new byte[0]; // se esiste il file... if (_fileService.FileExists(repPath)) { // lettura file report var repData = _fileService.ReadAllBytes(repPath); using (MemoryStream ms = new MemoryStream(repData)) { var Report = XtraReport.FromStream(ms); var ds = ComposeJsonDataSource(dataFullUrl, reqId, codGroup); ds.Fill(); Report.DataSource = ds; Report.DataMember = ""; // deve diventare dinamico da paramsConfig + ParamsVal +... foreach (DevExpress.XtraReports.Parameters.Parameter param in Report.Parameters) { if (param.Name.Equals("pImgPath")) Report.Parameters["pImgPath"].Value = imgFullUrl; } //Report.Parameters["pImgPath"].Value = imgFullUrl; using var msOut = new MemoryStream(); Report.ExportToPdf(msOut); ms.Position = 0; pdfBytes = msOut.ToArray(); } } return pdfBytes; } public async Task GenerateDummyPdfAsync(string reason) { _logger.LogWarning("Generating dummy PDF because: {Reason}", reason); var html = $"

Errore

{reason}

"; return await RenderPdfFromHtmlAsync(html); } private Task RenderPdfFromHtmlAsync(string html) { // Qui metti la tua libreria PDF preferita (QuestPDF, DinkToPdf, PuppeteerSharp, ecc.) // Per ora restituiamo un array fittizio. return Task.FromResult(System.Text.Encoding.UTF8.GetBytes(html)); } /// /// Composizione DataSource Json /// /// URL di partenza /// ID record richiesto /// private JsonDataSource ComposeJsonDataSource(string rawDataUrl, int reqId, string codGroup) { // Create a new JSON source. var jsonSource = new UriJsonSource() { Uri = new Uri(rawDataUrl) }; jsonSource.PathParameters.Add(new PathParameter("ReqId", typeof(int), reqId)); if (!string.IsNullOrEmpty(codGroup)) { jsonSource.QueryParameters.Add(new QueryParameter("codGroup", typeof(string), codGroup)); } // Assign the JSON source to the data source. var datasource = new JsonDataSource() { JsonSource = jsonSource }; return datasource; } } }