En la primera parte del artículo creamos una aplicación SP.Net Core en la que implementamos los siguientes métodos: mostrar informe, mostrar diseñador de informes y guardar informe modificado en el diseñador en un servidor. Pero solo son dos funcionalidades que hemos declarado. Tenemos que implementar el método exportar informe deseado en formato PDF o HTML con la descarga posterior de este informe. Para que el usuario sepa que informe están disponibles para la descarga, implementamos el método recibir lista de informes.
Añadimos al modelo de datos (la carpeta Model) la estructura de datos para la lista de informes:
1 2 3 4 5 6 7 |
public class Reports { // Report ID public int Id { get; set; } // Report File Name public string ReportName { get; set; } } |
Ahora podemos crear la lista de informes con indicadores en nuestro controlador:
Como hemos mencionado arriba, necesitamos una lista de informes en la aplicación del cliente. Sirve para demostrar informe, editarlo en el diseñador y descargarlo en formato PDF o HTML.
1 2 3 4 5 6 |
// Get a list of reports in json format [HttpGet] public IEnumerable<Reports> Get() { return reportItems; // Gets a list of reports } |
Todo es fácil aquí, una lista de informe en formato JSON. Y ahora implementamos un método bastante complicado, método de obtener la exportación del informes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// Get the report file in pdf / html // Attribute has a required id parameter [HttpGet("{id}")] public IActionResult Get(int id, [FromQuery] ReportQuery query) { string mime = "application/" + query.Format; // MIME header with default value // Find the report Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); // Get the value of the collection by identifier if (reportItem != null) { string reportPath = (webRoot + "/App_Data/" + reportItem.ReportName); // Determine the path to the report string dataPath = (webRoot + "/App_Data/nwind.xml");// Determine the path to the database using (MemoryStream stream = new MemoryStream()) // Create a stream for the report { try { using (DataSet dataSet = new DataSet()) { // Fill the source with data dataSet.ReadXml(dataPath); // Turn on FastReport web mode Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); // Download report report.RegisterData(dataSet, "NorthWind"); // We register data in the report if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); // Set the value of the report parameter, if the parameter value is transmitted in the URL } report.Prepare();//prepare a report // if pdf format is selected if (query.Format == "pdf") { // Export report to PDF PDFExport pdf = new PDFExport(); // We use a stream to store the report so as not to create extra files report.Export(pdf, stream); } // if html report format is selected else if (query.Format == "html") { // Export report to HTML HTMLExport html = new HTMLExport(); html.SinglePage = true; // Single page report html.Navigator = false; // Top navigation bar html.EmbedPictures = true; // Embeds images in a document report.Export(html, stream); mime = "text/" + query.Format; // Redefine mime for html } } } // Get the name of the resulting report file with the desired extension var file = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format); // Download the report file return File(stream.ToArray(), mime, file); } // Handle exceptions catch { return new NoContentResult(); } finally { stream.Dispose(); } } } else return NotFound(); } |
Este método recibe dos parámetros de entrada: id y query. El primero es el identificador del informe de nuestra lista, y el segundo, un conjunto de parámetros que vamos a especificar en url. Vamos a echar un vistazo a este conjunto abajo, mientras ahora seguimos con el método Get.
El método SetParameterValue establece el valor del parámetro que pasamos a url si es necesario. Es una demostración de posibilidades.
Como ve, del parámetro format sabemos qué ha seleccionado el usuario. En nuestro caso puede ser los formatos PDF o HTML. Dependiendo del formato, se exporta el informe. Cada tipo de exportación tiene sus propios ajustes. Como resultado, la exportación se guarda en el stream y del stream se transforma en un archiva para descargar.
Ahora volvamos al segundo parámetro de Get, al método query. Es del tipo ReportQuery. Cree este clase en el modelo de datos:
1 2 3 4 5 6 7 8 |
// Report Request Structure public class ReportQuery { // Format of resulting report: pdf, html public string Format { get; set; } // Value of "Parameter" variable in report public string Parameter { get; set; } } |
Como entiende, los métodos Get se cogen de WebAPI. Este proyecto es un híbrido: tiene tanto una parte View, como una interfaz WebAPI.
De esta manera, para obtener una vista que muestre un unforme, debe crear un url de este tipo:
https://localhost:44346/api/reports/ShowReport?name=ReportName.frx
Para obtener una presentación con el diseñador de informes, el hipervínculo solo tiene que ser diferente en el nombre del método:
https://localhost:44346/api/reports/Designer?name=ReportName.frx
Pero para obtener el nombre del informe, necesita una lista de informes disponibles en la aplicación del cliente. Згуву obtener la lista de informes en formato JSON utilizando url:
https://localhost:44346/api/reports/
Para descargar el informe en el formato seleccionado, necesitará formar un url del tipo:
https://localhost:44346/api/reports/1?format=pdf
Donde el número del informe corresponde al id de la lista de informes en el servidor, y el formato puede tener valores: pdf o html. Además, puede especificar un parámetro de informe si hay alguno en su modelo de informe. A continuación el url se verá así:
https://localhost:44346/api/reports/1?format=pdf¶meter=REPORT
En este caso, el parámetro propiamente dicho en el informe se tiene que llamar Parameter y el valor se coge de url. De manera parecida, puede pensar en tantos parámetros, cuántos quiera en url.
Hemos terminado trabajar con el lado del servidor. En la siguiente parte del artículo, vamos a echar un vistazo en cómo utilizar todo eso en una aplicación del cliente en PFP.