Пример #1
0
        public void TestExportPdfInfo()
        {
            Report         r              = new Report();
            ReportPage     page           = new ReportPage();
            PageHeaderBand pageHeaderBand = new PageHeaderBand();

            pageHeaderBand.CreateUniqueName();
            pageHeaderBand.Height = 300;
            page.Bands.Add(pageHeaderBand);
            r.Pages.Add(page);
            r.Prepare();

            PDFSimpleExport export = new PDFSimpleExport();

            export.Title    = "FastReport OpenSource Test Title dad5dd69-4c07-4789-ab4d-f03d0ba68c9c";
            export.Subject  = "FastReport OpenSource Test Subject 7cf3d3d9-716f-4c51-a397-c6389c3100ca";
            export.Keywords = "FastReport OpenSource Test Keywors 2fbbf8b9-2daf-40b5-b216-a4c3130aac56";
            export.Author   = "FastReport OpenSource Test Author a1e57c3e-1e0e-4b94-a472-07b5f05fa515";
            string pdf;

            using (MemoryStream ms = new MemoryStream())
            {
                r.Export(export, ms);
                pdf = Encoding.UTF8.GetString(ms.ToArray());
            }

#pragma warning disable xUnit2009 // Do not use boolean check to check for substrings
            Assert.True(pdf.Contains("/Title (" + StringToPdfUnicode(export.Title) + ")"));
            Assert.True(pdf.Contains("/Subject (" + StringToPdfUnicode(export.Subject) + ")"));
            Assert.True(pdf.Contains("/Keywords (" + StringToPdfUnicode(export.Keywords) + ")"));
            Assert.True(pdf.Contains("/Author (" + StringToPdfUnicode(export.Author) + ")"));
#pragma warning restore xUnit2009 // Do not use boolean check to check for substrings
        }
Пример #2
0
        // GET: Impresion
        public ActionResult Morosos()
        {
            var alumnos = db.Alumnoes
                          .Where(r => r.Solvente.Value != true)
                          .ToList();

            Report report = new Report();

            string thisFolder = Config.ApplicationFolder;

            string path     = Path.Combine(thisFolder, "Reportes\\Morosos.frx");
            string fullPath = Path.GetFullPath(path);

            report.Load(fullPath);


            report.RegisterData(alumnos, "Alumno");

            var fecha = DateTime.Now.ToLongDateString();

            report.SetParameterValue("Fecha", fecha);

            var nombreArchivo = $"{fecha} Alumnos Morosos.pdf";

            report.Prepare();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                export.Export(report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", nombreArchivo));
            }
        }
Пример #3
0
        public void TestExportPdfImages()
        {
            PDFSimpleExport export = new PDFSimpleExport();

            export.ImageDpi    = 300;
            export.JpegQuality = 90;
            Assert.Equal(300, export.ImageDpi);
            Assert.Equal(90, export.JpegQuality);


            export.ImageDpi    = 1200;
            export.JpegQuality = 100;
            Assert.Equal(1200, export.ImageDpi);
            Assert.Equal(100, export.JpegQuality);

            export.ImageDpi    = 96;
            export.JpegQuality = 10;
            Assert.Equal(96, export.ImageDpi);
            Assert.Equal(10, export.JpegQuality);

            export.ImageDpi    = 300;
            export.JpegQuality = 90;
            Assert.Equal(300, export.ImageDpi);
            Assert.Equal(90, export.JpegQuality);

            export.ImageDpi    = 3000;
            export.JpegQuality = 110;
            Assert.Equal(1200, export.ImageDpi);
            Assert.Equal(100, export.JpegQuality);

            export.ImageDpi    = 0;
            export.JpegQuality = 0;
            Assert.Equal(96, export.ImageDpi);
            Assert.Equal(10, export.JpegQuality);
        }
Пример #4
0
        public IActionResult ExportToPDF(string Reportpath, string Parameter = null)
        {
            var path      = Reportpath;
            var webReport = new WebReport();

            webReport.Report.Load(path);

            if (Parameter != null)
            {
                var bank = _businessLayer.GetFinInstitutionInfoById(Parameter);
                webReport.Report.SetParameterValue("BankName", bank.InstitutionName);
                webReport.Report.SetParameterValue("FinancialInstitutionId", Parameter);
            }
            webReport.Report.Prepare();
            using (MemoryStream ms = new MemoryStream())
            {
                PDFSimpleExport pdfExport = new PDFSimpleExport();
                pdfExport.Export(webReport.Report, ms);
                ms.Flush();
                var filenamewithoutreports = path.Remove(0, 8);
                var filename = filenamewithoutreports.Remove(filenamewithoutreports.Length - 4);

                return(File(ms.ToArray(), "application /pdf", filename + DateTime.Now.ToString() + ".pdf"));
            }
        }
Пример #5
0
        public void export_group_report_pdf()
        {
            var report = builder.Report(list)
                         .ReportTitle(title => title
                                      .Text("Employee List - [MonthName(Month([Date]))]")
                                      .HorzAlign(HorzAlign.Center)
                                      )
                         .GroupHeader(header => header
                                      .Condition(con => con.LastName)
                                      .SortOrder(SortOrder.Descending)
                                      .Expression("Substring({0},0,1)")
                                      )
                         .DataHeader(header => header
                                     .TextColor(Color.Brown)
                                     .Font("Helvetica")
                                     )
                         .Data(data =>
            {
                data.Column(col => col.FirstName).Width(20);
                data.Column(col => col.LastName).Expression("UpperCase({0})");
                data.Column(col => col.BirthDate).Format("MM/dd/yyyy");
                data.Column(col => col.IsActive).Title("Active").Width(10);
                data.Column(col => col.Level).HorzAlign(HorzAlign.Center);
            })
                         .Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Employees.pdf");
        }
Пример #6
0
        public ActionResult EstadoDeCuenta(long id)
        {
            var propietario = db.Propietarios
                              .Where(x => x.Id_Propietario == id)
                              .Include(x => x.Terrenoes)
                              .FirstOrDefault();

            var temp = new List <EstadoCuentaDTO>();
            var nombrePropietario = $"{propietario.Nombre} {propietario.Apelllido}";

            var total = 0m;

            foreach (var item in propietario.Terrenoes)
            {
                if (!item.Solvencia.GetValueOrDefault())
                {
                    continue;
                }
                var suma = 0m;
                foreach (var recibo in item.Reciboes)
                {
                    suma += recibo.Pago_Detalle.Monto.GetValueOrDefault();
                }
                temp.Add(new EstadoCuentaDTO()
                {
                    Direccion = $"{item.Direccion} Lote {item.Lote}", Monto = suma.ToString("F")
                });
                total += suma;
            }

            Report report = new Report();

            string thisFolder = Config.ApplicationFolder;

            string path     = Path.Combine(thisFolder, "Reportes\\EstadoCuenta.frx");
            string fullPath = Path.GetFullPath(path);

            report.Load(fullPath);

            report.RegisterData(temp, "EstadoCuenta");

            var fecha = DateTime.Now.ToLongDateString();

            report.SetParameterValue("Fecha", fecha);
            report.SetParameterValue("Propietario", nombrePropietario);
            report.SetParameterValue("Total", total.ToString("F"));

            var nombreArchivo = $"{fecha} {nombrePropietario} Estado de Cuenta.pdf";

            report.Prepare();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                export.Export(report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", nombreArchivo));
            }
        }
Пример #7
0
        private byte[] InternalGenerateReport(string reportFile, Dictionary <string, string> parameters)
        {
            FastReport.Report report = new FastReport.Report();
            report.Load(Path.Combine("Reports", reportFile));
            if (string.IsNullOrWhiteSpace(_appSettings.ConnectionString))
            {
                throw new NotSupportedException("Connectionstring não informada");
            }

            report.Dictionary.Connections[0].ConnectionString = _appSettings.ConnectionString;
            //report.SetParameterValue("initialDate", "2019-01-01");
            //report.SetParameterValue("finalDate", "2019-01-07");

            foreach (var parameter in parameters)
            {
                report.SetParameterValue(parameter.Key, parameter.Value);
            }

            report.Prepare();

            // report.Parameters[0].Value = 143;
            //report.Refresh();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                report.Export(export, ms);
                ms.Flush();
                return(ms.ToArray());
            }
        }
Пример #8
0
 public byte[] Exportar(Report relatorio)
 {
     using (var ms = new MemoryStream())
     {
         PDFSimpleExport pdfExport = new PDFSimpleExport();
         pdfExport.Export(relatorio, ms);
         return(ms.ToArray());
     }
 }
Пример #9
0
        public void TestExportWatermark()
        {
            Report r = new Report();

            r.LoadPrepared("Watermark.fpx");

            PDFSimpleExport export = new PDFSimpleExport();

            r.Export(export, "Watermark.pdf");
        }
Пример #10
0
        // GET: Impresion
        public ActionResult Impresion(long id)
        {
            var recibo = db.Reciboes
                         .AsNoTracking()
                         .Where(r => r.Id_Recibo == id)
                         .Include(r => r.Alumno)
                         .Include(r => r.Pago_Detalle)
                         .Include(r => r.Tutor)
                         .FirstOrDefault();

            Report report = new Report();

            string thisFolder = Config.ApplicationFolder;

            string path     = Path.Combine(thisFolder, "Reportes\\Recibo.frx");
            string fullPath = Path.GetFullPath(path);

            report.Load(fullPath);

            var detalles = new List <Pago_Detalle>()
            {
                recibo.Pago_Detalle
            };

            report.RegisterData(detalles, "Recibo");

            var nombreAlumno = $"{recibo.Alumno.Nombre} {recibo.Alumno.Apellido}";
            var nombreTutor  = $"{recibo.Tutor.Nombre} {recibo.Tutor.Apellidos}";
            var fecha        = DateTime.Now.ToLongDateString();

            report.SetParameterValue("Alumno", nombreAlumno);
            report.SetParameterValue("Tutor", nombreTutor);
            report.SetParameterValue("Fecha", fecha);

            var nombreArchivo = $"{fecha} {nombreAlumno} {nombreTutor}.pdf";

            report.Prepare();

            var alumno = db.Alumnoes.Where(x => x.Id_Alumno == recibo.Alumno.Id_Alumno).FirstOrDefault();

            alumno.Solvente        = true;
            db.Entry(alumno).State = EntityState.Modified;
            db.SaveChanges();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                export.Export(report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", nombreArchivo));
            }
        }
        public async Task <ActionResult> GerarRelatorio(
            [FromQuery] DateTime?DataInicial,
            [FromQuery] DateTime?DataFinal,
            [FromQuery] Guid?ClienteId,
            [FromQuery] int?Status)
        {
            try
            {
                var lista = _mapper.Map <List <PedidoViewModel> >(await _pedidoService.RecuperarTodos(DataInicial, DataFinal, ClienteId, Status));

                var filtro = string.Empty;
                if (DataInicial != null)
                {
                    filtro += $@"Inicial {DataInicial.GetValueOrDefault().ToString("dd/MM/yyyy")};";
                }
                if (DataFinal != null)
                {
                    filtro += $@"Final {DataFinal.GetValueOrDefault().ToString("dd/MM/yyyy")};";
                }
                if (Status != null)
                {
                    var StatusDescricao =
                        Status == 1 ? "Faturado" :
                        Status == 2 ? "Cancelado" :
                        "Aberto";
                    filtro +=
                        $@"Status {StatusDescricao};";
                }
                if ((ClienteId != null) && (ClienteId.HasValue))
                {
                    filtro +=
                        $@"Cód. Cliente {ClienteId};";
                }

                Report report = new Report();
                report.Load($@"{_env.ContentRootPath}\Report\Pedidos.frx");
                report.RegisterData(lista, "Pedidos");
                report.SetParameterValue("FILTRO", filtro);
                report.Prepare();

                var pdfExport      = new PDFSimpleExport();
                var nomeArquivoPdf = Path.ChangeExtension(Path.GetTempFileName(), "pdf");
                pdfExport.Export(report, nomeArquivoPdf);

                var stream = System.IO.File.OpenRead(nomeArquivoPdf);
                return(new FileStreamResult(stream, "application/octet-stream"));
            }
            catch (Exception ex)
            {
                return(CustomResponse(ex.Message));
            }
        }
        public void CreatePDF()
        {
            var customer = _CustomerDal.GetAll();


            report.Load(@"C:\Users\B\source\repos\TeknikServisBackEnd\Business\Reports\report.frx");
            report.RegisterData(customer, "customer");
            report.Prepare();
            report.SavePrepared(@"C:\Users\B\source\repos\TeknikServisBackEnd\Business\Reports\new.frx");
            PDFSimpleExport pdfSimple = new PDFSimpleExport();

            pdfSimple.Export(report, "asde.pdf");
        }
Пример #13
0
        public ActionResult Deudores()
        {
            var propietarios = db.Propietarios
                               .Include(x => x.Terrenoes)
                               .ToList();

            var temp = new List <PropietarioDTO>();

            foreach (var item in propietarios)
            {
                if (item.Terrenoes.Any(x => !x.Solvencia.GetValueOrDefault()))
                {
                    continue;
                }
                else
                {
                    temp.Add(new PropietarioDTO()
                    {
                        Nombre = item.Nombre, Apellido = item.Apelllido
                    });
                }
            }

            Report report = new Report();

            string thisFolder = Config.ApplicationFolder;

            string path     = Path.Combine(thisFolder, "Reportes\\Deudores.frx");
            string fullPath = Path.GetFullPath(path);

            report.Load(fullPath);

            report.RegisterData(temp, "Propietario");

            var fecha = DateTime.Now.ToLongDateString();

            report.SetParameterValue("Fecha", fecha);

            var nombreArchivo = $"{fecha} Deudores.pdf";

            report.Prepare();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                export.Export(report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", nombreArchivo));
            }
        }
Пример #14
0
        public IActionResult Pdf(string OPID, string DDL_License_Name, string DDL_PlanID)
        {
            var webReport = GetReport(OPID, DDL_License_Name, DDL_PlanID);

            webReport.Report.Prepare();

            using (var ms = new MemoryStream())
            {
                var pdfExport = new PDFSimpleExport();
                pdfExport.Export(webReport.Report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", Path.GetFileNameWithoutExtension("Report_") + ".pdf"));
            }
        }
Пример #15
0
        public IActionResult Pdf()
        {
            var webReport = GetReport();

            webReport.Report.Prepare();

            using (var ms = new MemoryStream())
            {
                var pdfExport = new PDFSimpleExport();
                pdfExport.Export(webReport.Report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", Path.GetFileNameWithoutExtension("Master-Detail") + ".pdf"));
            }
        }
Пример #16
0
        // Worker asíncrono. Genera el reporte en otro hilo.
        private static bool GenerarReporteOnTask(object info)
        {
            const string    methodName = "GenerarReporteOnTask";
            Report          report;
            PDFSimpleExport pdfExport;
            reportInfo      rInfo = (reportInfo)info;

            try
            {
                // Crear instancia del componente reporte.
                report = new Report();

                // Cargar definicion de reporte. Permite alternar entre archivo FRX en carpet \Reports
                // y definicion de reporte contenida en string en clase auxiliar
                //report.Load(rInfo.ReportLoadPath);
                report.LoadFromString(rInfo.ReportAsString);

                // Pasar datos.
                report.RegisterData(rInfo.DataSet, rInfo.DataSetName);
                // Pasar parametros
                report.SetParameterValue(rInfo.ParameterName, rInfo.Parameter);

                bool ret = report.Prepare();

                if (ret)
                {
                    pdfExport = new PDFSimpleExport();
                    pdfExport.Export(report, rInfo.PdfReportPath);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.WriteEntry(ClassName, methodName, TraceEventType.Error, string.Format("Error: {0}", ex.Message));
                return(false);
            }
            finally
            {
                report    = null;
                rInfo     = null;
                pdfExport = null;
            }
        }
        public IActionResult Generate([FromBody] ReportDto query)
        {
            string mime        = "application/pdf";               //MIME-header with default value
            string webRootPath = _hostingEnvironment.WebRootPath; //Define the path to the wwwroot folder
            string reportPath  = (webRootPath + "/Report.frx");   //Define the path to the report

            using (MemoryStream stream = new MemoryStream())      //Create the stream for the report
            {
                try
                {
                    using (DataSet dataSet = new DataSet())
                    {
                        RegisteredObjects.AddConnection(typeof(MsSqlDataConnection));
                        WebReport webReport = new WebReport();

                        MsSqlDataConnection sqlConnection = new MsSqlDataConnection();
                        sqlConnection.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
                        sqlConnection.CreateAllTables();
                        webReport.Report.Dictionary.Connections.Add(sqlConnection);


                        webReport.Report.Load(reportPath);
                        webReport.Report.SetParameterValue("AmostraId", query.AmostraId);
                        for (int i = 0; i < query.Ensaios.Length; i++)
                        {
                            webReport.Report.SetParameterValue($"EnsaioSelecionados{i+1}", query.Ensaios[i]);
                        }
                        webReport.Report.Prepare();
                        PDFSimpleExport pdfExport = new PDFSimpleExport();
                        pdfExport.Export(webReport.Report, stream);
                    }
                    //Get the name of resulting report file with needed extension
                    var file = String.Concat($"Laudo-{DateTime.Now}", ".", "pdf");
                    return(File(stream.ToArray(), mime, file)); // attachment
                }
                catch (Exception ex)
                {
                    throw new AppError(ex.Message);
                    return(new NoContentResult());
                }
                finally
                {
                    stream.Dispose();
                }
            }
        }
Пример #18
0
        public HttpResponseMessage GetPdf(string CVU)
        {
            var    claims = ClaimsPrincipal.Current.Identities.First().Claims.ToList();
            string UserId = claims?.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Sid, StringComparison.OrdinalIgnoreCase))?.Value;


            try
            {
                AccountManager        oAccountManager = new AccountManager();
                ICollection <Account> oAccounts       = oAccountManager.GetUserAccountsByUserId(Convert.ToInt32(UserId));

                if (!oAccounts.Where(a => a.CVU == CVU).Any())
                {
                    throw new ArgumentException("El cvu especificado no pertenece al usuario logeado");
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    var oReport = new Report();
                    oReport.Load(System.Web.Hosting.HostingEnvironment.MapPath("~/Reports/Boleta.frx"));
                    oReport.SetParameterValue("pCVU", CVU);
                    oReport.SetParameterValue("pCODIGO", "ClipMoney-" + UserId + "-" + CVU);

                    oReport.Prepare();

                    PDFSimpleExport oExport = new PDFSimpleExport();

                    oExport.Export(oReport, ms);
                    ms.Flush();


                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new ByteArrayContent(ms.ToArray());
                    response.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = "Factura.pdf";
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

                    return(response);
                }
            } catch (Exception ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);

                return(response);
            }
        }
Пример #19
0
        // GET: Impresion
        public ActionResult Impresion(long id)
        {
            var recibo = db.Reciboes
                         .Where(r => r.Id_Recibo == id)
                         .Include(r => r.Pago_Detalle)
                         .Include(r => r.Terreno)
                         .FirstOrDefault();

            Report report = new Report();

            string thisFolder = Config.ApplicationFolder;

            string path     = Path.Combine(thisFolder, "Reportes\\Recibo.frx");
            string fullPath = Path.GetFullPath(path);

            report.Load(fullPath);

            var detalles = new List <Pago_Detalle>()
            {
                recibo.Pago_Detalle
            };

            report.RegisterData(detalles, "Recibo");

            var nombrePropietario = $"{recibo.Terreno.Propietario.Nombre} {recibo.Terreno.Propietario.Apelllido}";
            var fecha             = DateTime.Now.ToLongDateString();
            var lote = $"{recibo.Terreno.Direccion} Lote: {recibo.Terreno.Lote}";

            report.SetParameterValue("Propietario", nombrePropietario);
            report.SetParameterValue("Fecha", fecha);
            report.SetParameterValue("Lote", lote);

            var nombreArchivo = $"{fecha} {nombrePropietario}.pdf";

            report.Prepare();

            PDFSimpleExport export = new PDFSimpleExport();

            using (MemoryStream ms = new MemoryStream())
            {
                export.Export(report, ms);
                ms.Flush();
                return(File(ms.ToArray(), "application/pdf", nombreArchivo));
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            string reportsFolder = FindReportsFolder();

            Report report = new Report();

            report.Load(Path.Combine(reportsFolder, "Simple List.frx"));

            DataSet data = new DataSet();

            data.ReadXml(Path.Combine(reportsFolder, "nwind.xml"));

            report.RegisterData(data, "NorthWind");

            report.Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Simple List.pdf");
        }
Пример #21
0
        public void export_report_resized_columns_by_percentage_pdf()
        {
            var report = builder.Report(list)
                         .ReportTitle(title => title
                                      .Text("Employee List")
                                      .HorzAlign(HorzAlign.Center)
                                      )
                         .Data(data =>
            {
                data.Column(col => col.FirstName).Width(25); // 25%
                data.Column(col => col.LastName).Width(20);  // 20%
                data.Column(col => col.BirthDate);           // other three columns are equal - (55/3)%
                data.Column(col => col.IsActive);
                data.Column(col => col.Level);
            })
                         .Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Employees.pdf");
        }
Пример #22
0
        public void export_report_using_column_format_pdf()
        {
            var report = builder.Report(list)
                         .ReportTitle(title => title
                                      .Text("Employee List")
                                      .HorzAlign(HorzAlign.Center)
                                      )
                         .Data(data =>
            {
                data.Column(col => col.FirstName);
                data.Column(col => col.LastName);
                data.Column(col => col.BirthDate).Format("MM/dd/yyyy");
                data.Column(col => col.IsActive);
                data.Column(col => col.Level);     // this column formatted with data annotation
            })
                         .Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Employees.pdf");
        }
Пример #23
0
        public void export_report_using_expression_pdf()
        {
            var report = builder.Report(list)
                         .ReportTitle(title => title
                                      .Text("Employee List - [MonthName(Month([Date]))]")
                                      .HorzAlign(HorzAlign.Center)
                                      )
                         .Data(data =>
            {
                data.Column(col => col.FirstName);
                data.Column(col => col.LastName).Expression("UpperCase({0})");
                data.Column(col => col.BirthDate);
                data.Column(col => col.IsActive);
                data.Column(col => col.Level);
            })
                         .Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Employees.pdf");
        }
Пример #24
0
        public void export_basic_report_pdf()
        {
            var report = builder.Report(list)
                         .ReportTitle(title => title
                                      .Text("Employee List")
                                      .HorzAlign(HorzAlign.Center)
                                      )
                         .Data(data =>
            {
                data.Column(col => col.FirstName);     // this column get title with data annotation
                data.Column(col => col.LastName).Title("Last Name");
                data.Column(col => col.BirthDate);
                data.Column(col => col.IsActive);
                data.Column(col => col.Level);
            })
                         .Prepare();

            PDFSimpleExport pdfExport = new PDFSimpleExport();

            pdfExport.Export(report, "Employees.pdf");
        }
Пример #25
0
        public void ExportPdf()
        {
            Report r = new Report();

            r.LoadPrepared("TestReport.fpx");

            PDFSimpleExport export = new PDFSimpleExport();
            string          pdf;

            using (MemoryStream ms = new MemoryStream())
            {
                r.Export(export, ms);
                pdf = Encoding.ASCII.GetString(ms.ToArray());
            }

#pragma warning disable xUnit2009 // Do not use boolean check to check for substrings
            Assert.True(pdf.StartsWith("%PDF-1.5"));
#pragma warning restore xUnit2009 // Do not use boolean check to check for substrings

            int i     = 0;
            int index = 0;
            while ((index = pdf.IndexOf("/Page ", index + 1)) != -1)
            {
                i++;
            }
            Assert.Equal(4, i);

            i     = 0;
            index = 0;

            while ((index = pdf.IndexOf("FEFF0046006100730074005200650070006F00720074002E004E00450054", index + 1)) != -1)
            {
                i++;
            }

            Assert.Equal(2, i);
        }
Пример #26
0
        /// <summary>
        /// 用 FastReport return the PDF in byte array
        /// </summary>
        /// <param name="fromCode"></param>
        /// <param name="toCode"></param>
        /// <param name="fromDate"></param>
        /// <param name="toDate"></param>
        /// <returns></returns>
        public static byte[] PDF(string fromCode, string toCode, string fromDate, string toDate)
        {
            byte[] result = null;

            var sql = string.Format(_Sql, fromDate, toDate, fromCode, toCode);

            //! 提供一個 data connection object (依家用 MsSql)
            FastReport.Utils.RegisteredObjects.AddConnection(typeof(FastReport.Data.MsSqlDataConnection));

            using (MemoryStream stream = new MemoryStream()) //Create the stream for the report
            {
                try
                {
                    Config.WebMode = true;

                    using (Report report = new Report())
                    {
                        report.Load(ReportFilePath);

                        #region populate data source
                        //! 首先,取消 designer 用緊嘅 Connection
                        report.Dictionary.Connections.Clear();

                        //! 再準備 custom 嘅 data source
                        DataSet ds = new DataSet();
                        ds = SqlHelper.Default.ExecuteDataSet(CommandType.Text, sql);

                        //! 替代 design time 嘅設定
                        string desingTimeDataSourceAlias = "Table", desingTimeDataBandName = "Data1";
                        report.Dictionary.Report.RegisterData(ds, desingTimeDataSourceAlias, true);
                        ((DataBand)report.Report.FindObject(desingTimeDataBandName)).DataSource = report.GetDataSource(desingTimeDataSourceAlias);
                        report.GetDataSource(desingTimeDataSourceAlias).Enabled = true;
                        //! DataSource 已經 sorted,不過 DataBand 會亂來,除非你喺 designer 設定咗 DataBand 個 Sort
                        //! 我選擇喺 code 度搞
                        ((DataBand)report.Report.FindObject(desingTimeDataBandName)).Sort.AddRange(new Sort[] {
                            new Sort(string.Format("[{0}.TxDate]", desingTimeDataSourceAlias), false),
                            new Sort(string.Format("[{0}.TxType]", desingTimeDataSourceAlias), false),
                            new Sort(string.Format("[{0}.TxNumber]", desingTimeDataSourceAlias), false)
                        });
                        #endregion

                        #region render 個 report 前作最後處理
                        ((TextObject)report.Report.FindObject("lblReportTitle")).Text = WestwindHelper.GetWord("report.SA1330", "Setting");

                        ((TextObject)report.Report.FindObject("txtPageNofM")).Text = string.Format(WestwindHelper.GetWord("reports.pageNofM", "General"), "[Page]", "[TotalPages]");

                        report.SetParameterValue("pCompanyName", WestwindHelper.GetWord("companyInfo.name", "Setting"));    // SystemInfoEx.CurrentInfo.Default.CompanyName);
                        ((TextObject)report.Report.FindObject("lblSelectedRange")).Text     = WestwindHelper.GetWordWithColon("reports.selectedRange", "General");
                        ((TextObject)report.Report.FindObject("lblSelectedStockCode")).Text = WestwindHelper.GetWordWithColon("article.code", "Product");
                        ((TextObject)report.Report.FindObject("lblSelectedDate")).Text      = WestwindHelper.GetWordWithColon("transaction.date", "Transaction");
                        report.SetParameterValue("pSelectedStockCode", string.Format("{0} ⇔ {1}", fromCode, toCode));
                        report.SetParameterValue("pSelectedDate", string.Format("{0} ⇔ {1}", fromDate, toDate));
                        ((TextObject)report.Report.FindObject("lblPrintedOn")).Text = WestwindHelper.GetWordWithColon("reports.printedOn", "General");
                        ((TextObject)report.Report.FindObject("lblPage")).Text      = WestwindHelper.GetWordWithColon("reports.page", "General");

                        ((TextObject)report.Report.FindObject("lblStockCode")).Text = WestwindHelper.GetWordWithColon("article.code", "Product");
                        ((TextObject)report.Report.FindObject("lblAppendix1")).Text = WestwindHelper.GetWordWithColon("appendix.appendix1", "Product");
                        ((TextObject)report.Report.FindObject("lblAppendix2")).Text = WestwindHelper.GetWordWithColon("appendix.appendix2", "Product");
                        ((TextObject)report.Report.FindObject("lblAppendix3")).Text = WestwindHelper.GetWordWithColon("appendix.appendix3", "Product");
                        ((TextObject)report.Report.FindObject("lblClass1")).Text    = WestwindHelper.GetWordWithColon("class.class1", "Product");
                        ((TextObject)report.Report.FindObject("lblClass2")).Text    = WestwindHelper.GetWordWithColon("class.class2", "Product");
                        ((TextObject)report.Report.FindObject("lblClass3")).Text    = WestwindHelper.GetWordWithColon("class.class3", "Product");
                        ((TextObject)report.Report.FindObject("lblClass4")).Text    = WestwindHelper.GetWordWithColon("class.class4", "Product");
                        ((TextObject)report.Report.FindObject("lblClass5")).Text    = WestwindHelper.GetWordWithColon("class.class5", "Product");
                        ((TextObject)report.Report.FindObject("lblClass6")).Text    = WestwindHelper.GetWordWithColon("class.class6", "Product");
                        ((TextObject)report.Report.FindObject("lblBFQty")).Text     = WestwindHelper.GetWordWithColon("inventory.bfQty", "Product");
                        ((TextObject)report.Report.FindObject("lblBFAmount")).Text  = WestwindHelper.GetWordWithColon("inventory.bfAmount", "Product");
                        ((TextObject)report.Report.FindObject("lblCDQty")).Text     = WestwindHelper.GetWordWithColon("inventory.cdQty", "Product");
                        ((TextObject)report.Report.FindObject("lblCDAmount")).Text  = WestwindHelper.GetWordWithColon("inventory.cdAmount", "Product");

                        ((TextObject)report.Report.FindObject("lblTxDate")).Text       = WestwindHelper.GetWord("transaction.date", "Transaction");
                        ((TextObject)report.Report.FindObject("lblTxType")).Text       = WestwindHelper.GetWord("transaction.type", "Transaction");
                        ((TextObject)report.Report.FindObject("lblQtyIn")).Text        = WestwindHelper.GetWord("transaction.qtyIn", "Transaction");
                        ((TextObject)report.Report.FindObject("lblQtyOut")).Text       = WestwindHelper.GetWord("transaction.qtyOut", "Transaction");
                        ((TextObject)report.Report.FindObject("lblPrice")).Text        = WestwindHelper.GetWord("transaction.price", "Transaction");
                        ((TextObject)report.Report.FindObject("lblCost")).Text         = WestwindHelper.GetWord("transaction.cost", "Transaction");
                        ((TextObject)report.Report.FindObject("lblTxNumber")).Text     = WestwindHelper.GetWord("transaction.number", "Transaction");
                        ((TextObject)report.Report.FindObject("lblReference")).Text    = WestwindHelper.GetWord("transaction.reference", "Transaction");
                        ((TextObject)report.Report.FindObject("lblLocation")).Text     = WestwindHelper.GetWord("workplace", "Model");
                        ((TextObject)report.Report.FindObject("lblSupplierCode")).Text = WestwindHelper.GetWord("supplier", "Model");
                        ((TextObject)report.Report.FindObject("lblRemarks")).Text      = WestwindHelper.GetWord("transaction.remarks", "Transaction");
                        ((TextObject)report.Report.FindObject("lblSubTotal")).Text     = WestwindHelper.GetWordWithColon("transaction.subtotal", "Transaction");
                        #endregion

                        report.Prepare();   //Prepare the report

                        #region export as PDF
                        var pdf = new PDFSimpleExport();
                        pdf.Export(report, stream);

                        // debug: write to a file
                        //pdf.Export(report, string.Format("C:\\Temp\\{0}.pdf", ReportFileName));

                        stream.Position = 0;
                        result          = stream.ToArray();

                        #endregion

                        stream.Flush();
                    }
                }
                catch (Exception ex)
                {
                    //
                }
                finally
                {
                    stream.Dispose();
                }
            }
            return(result);
        }
Пример #27
0
        private static int RunInternal(Options options)
        {
            if (!File.Exists(options.InputRfxFilePath))
            {
                Console.WriteLine("Input file \"{0}\" doesn't exist.",
                                  options.InputRfxFilePath);
                return(1);
            }

            string baseReportFilePath;
            var    isInheritedReport = TryGetBaseReportFilePath(
                options.InputRfxFilePath, out baseReportFilePath);

            using (var report = new Report())
            {
                if (isInheritedReport)
                {
#if true
                    try
                    {
                        report.Load(baseReportFilePath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to load base report template \"{0}\":\n{1}",
                                          baseReportFilePath, ex);
                        return(1);
                    }
#else
                    Func <object, CustomLoadEventArgs> loadBaseReport = (sender, e)
                    {
                        e.Report.Load(baseReportFilePath);
                    };

                    report.LoadBaseReport += new CustomLoadEventHandler(loadBaseReport);
                    report.LoadBaseReport -= new CustomLoadEventHandler(loadBaseReport);
#endif
                }

                try
                {
                    report.Load(options.InputRfxFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to load report template \"{0}\":\n{1}",
                                      options.InputRfxFilePath, ex);
                    return(1);
                }

#if DEBUG
                Console.WriteLine("Report filename: {0}.", report.FileName);
                Console.WriteLine("Base report filename: {0}.", report.BaseReport);
#endif

                foreach (var parameter in options.Parameters)
                {
                    var parameterParts = parameter.Split(new char[] { '=' }, 2);
                    if (parameterParts.Length != 2 || string.IsNullOrWhiteSpace(parameterParts[0]))
                    {
                        Console.WriteLine("Invalid parameter: {0}.", parameter);
                        return(1);
                    }

                    Console.WriteLine("Parameter: {0}={1}", parameterParts[0], parameterParts[1]);
                    report.SetParameterValue(parameterParts[0], parameterParts[1]);
                }

                foreach (var picture in options.Pictures)
                {
                    var parts = picture.Split(new char[] { '=' }, 2);
                    if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]))
                    {
                        Console.WriteLine("Invalid picture object name-location pair: {0}.", picture);
                        return(1);
                    }

                    var pictureObjectName = parts[0];
                    var pictureLocation   = parts[1];

                    var reportObject = report.FindObject(pictureObjectName);
                    if (reportObject == null)
                    {
                        Console.WriteLine("Couldn't find a picture object with name: {0}.", pictureObjectName);
                        return(1);
                    }

                    var pictureObject = reportObject as PictureObject;
                    if (pictureObject == null)
                    {
                        Console.WriteLine("Object \"{0}\" is not a picture object.", pictureObjectName);
                        return(1);
                    }

                    Image image = null;
                    if (!string.IsNullOrEmpty(pictureLocation))
                    {
                        if (File.Exists(pictureLocation))
                        {
                            try
                            {
                                image = Image.FromFile(pictureLocation);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to load picture from location {0}:\r\n{1}",
                                                  pictureLocation, ex.ToString());
                            }
                        }
                        else if (Base64Helper.IsBase64String(pictureLocation))
                        {
                            try
                            {
                                image = ImageHelper.LoadFromBase64(pictureLocation);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to load picture from base64 string {0}:\r\n{1}.",
                                                  pictureLocation, ex.ToString());
                            }
                        }
                        else
                        {
                            Console.WriteLine("Picture file \"{0}\" doesn't exist.", pictureLocation);
                        }
                    }

                    pictureObject.Image = image;
                }

                if (!report.Prepare())
                {
                    Console.WriteLine("Failed to prepare report.");
                    return(1);
                }

                if (string.IsNullOrWhiteSpace(options.OutputFilePath))
                {
                    string extension = FormatHelper.ExportFormatToExtension(options.Format);
                    if (string.IsNullOrWhiteSpace(extension))
                    {
                        Console.WriteLine("Unknown export format \"{0}\".", options.Format);
                        return(1);
                    }

                    var directory = Path.GetDirectoryName(options.InputRfxFilePath);
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(options.InputRfxFilePath);

                    var outputFilePath = Path.Combine(directory, fileNameWithoutExtension + extension);
                    int id             = 1;
                    while (File.Exists(outputFilePath))
                    {
                        if (id == int.MaxValue)
                        {
                            Console.WriteLine("Can not find a proper output file name.");
                            return(1);
                        }

                        Console.WriteLine("File \"{0}\" already exist.", outputFilePath);
                        outputFilePath = Path.Combine(directory,
                                                      fileNameWithoutExtension +
                                                      " (" + id.ToString() + ")" +
                                                      extension);

                        id++;
                    }

                    options.OutputFilePath = outputFilePath;
                }
                else
                {
                    string extension = Path.GetExtension(options.OutputFilePath);
                    if (!string.IsNullOrEmpty(extension))
                    {
                        // .\ReportGenerator.exe -i in.frx -o out.pdf
                        // will generate a .emf file, not a PDF file.
                        // So we need to fix it.
                        var expectedFormat = FormatHelper.ExportFormatFromExtension(extension);
                        if (expectedFormat != ExportFormat.Invalid && options.Format != expectedFormat)
                        {
                            if (options.Format != ExportFormat.Metafile)
                            {
                                Console.WriteLine("Incompatible formats are detected:\r\nFormat specified: {0}\r\nFormat guessed from extension: {1}\r\n",
                                                  options.Format, expectedFormat);
                            }

                            options.Format = expectedFormat;
                        }
                    }
                }

                if (options.Format == ExportFormat.Invalid)
                {
                    Console.WriteLine("Invalid export format: {0}.", options.Format);
                    return(1);
                }

                if (options.Format == ExportFormat.Pdf)
                {
                    using (var pdfExporter = new PDFSimpleExport())
                    {
                        if (options.Resolution > 0)
                        {
                            pdfExporter.ImageDpi = options.Resolution;
                        }

                        if (options.Quality >= 0 && options.Quality <= 100)
                        {
                            pdfExporter.JpegQuality = options.Quality;
                        }

                        report.Export(pdfExporter, options.OutputFilePath);
                    }
                }
                else
                {
                    using (var imageExporter = new ImageExport())
                    {
                        imageExporter.ImageFormat = FormatHelper.ExportFormatToImageExportFormat(options.Format);

                        // FastReport uses 96 DPI by default. If you specify a different
                        // DPI (e.g. 600 dpi, which is common for printers) here, FastReport
                        // will do some coordinate conversion when generating reports.
                        // In some older versions of FastReport, there is a problem when
                        // doing coordinate conversion, which results in incorrectly sized
                        // reports being generated.
                        // A test:
                        // ..\Templates\different_dpi_test.bat
                        // It seems that we can not change the DPI of output Metafile, however.
                        //
                        // [Export to Picture](https://www.fast-report.com/documentation/UserManFrNET-en/index.html?exporttoimage.htm)
                        // > "Resolution" - resolution of the graphical image.
                        // > Use 96dpi for displaying, 300dpi for printing.
                        // > When exporting into the TIFF format, you will able to
                        // > set separate values for horizontal and vertical resolution.
                        if (options.Resolution > 0)
                        {
                            imageExporter.Resolution = options.Resolution;
                        }
                        else if (options.ResolutionX > 0 && options.ResolutionY > 0)
                        {
                            imageExporter.ResolutionX = options.ResolutionX;
                            imageExporter.ResolutionY = options.ResolutionY;
                        }

                        if (options.Quality >= 0 && options.Quality <= 100)
                        {
                            imageExporter.JpegQuality = options.Quality;
                        }

                        report.Export(imageExporter, options.OutputFilePath);
                    }

                    if (options.RotateFlip != RotateFlipType.RotateNoneFlipNone)
                    {
                        using (var bitmap = Bitmap.FromFile(options.OutputFilePath))
                        {
                            bitmap.RotateFlip(options.RotateFlip);
                            bitmap.Save(options.OutputFilePath);
                        }
                    }
                }
            }

            return(0);
        }
        // Get report on ID from request
        public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query)
        {
            // Find report
            Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id);

            if (reportItem != null)
            {
                string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName);
                //string dataSource =
                MemoryStream stream = new MemoryStream();
                try
                {
                    //Enable web mode
                    Config.WebMode = true;
                    using (Report report = new Report())
                    {
                        report.Load(reportPath);     //Load report

                        // preguntar por el datasource
                        if (query.DsnId != null)
                        {
                            Dsn dsnItem = dsnItems.FirstOrDefault((p) => p.Id == id);
                            if (dsnItem != null)
                            {
                                report.Dictionary.Connections[0].ConnectionString = dsnItem.DataSource;
                            }
                        }



                        if (query.Fuente != null)
                        {
                            report.SetParameterValue("FUENTE", query.Fuente);     //  Fuente, The value we take from the URL
                        }
                        if (query.Documento != null)
                        {
                            report.SetParameterValue("DOCUMENTO", query.Documento);     // # Documento. The value we take from the URL
                        }
                        // Two phases of preparation to exclude the display of any dialogs
                        report.Prepare();


                        if (query.Format == "pdf")
                        {
                            //Export in PDF
                            PDFSimpleExport pdf = new PDFSimpleExport();
                            // We use the flow to store the report, so as not to produce files
                            report.Export(pdf, stream);
                        }
                        else if (query.Format == "html")
                        {
                            // Export in HTML
                            HTMLExport html = new HTMLExport();
                            html.SinglePage    = true;
                            html.Navigator     = false;
                            html.EmbedPictures = true;
                            report.Export(html, stream);
                        }
                        else
                        {
                            // Export in picture
                            ImageExport img = new ImageExport();
                            img.ImageFormat   = ImageExportFormat.Png;
                            img.SeparateFiles = false;
                            img.ResolutionX   = 96;
                            img.ResolutionY   = 96;
                            report.Export(img, stream);
                            query.Format = "png";
                        }
                    }

                    // Create result variable
                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(stream.ToArray())
                    };
                    stream.Dispose();

                    result.Content.Headers.ContentDisposition =
                        new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment")
                    {
                        // Specify the file extension depending on the type of export
                        FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format)
                    };
                    // Determine the type of content for the browser
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/" + query.Format);
                    return(result);
                }
                // We handle exceptions
                catch
                {
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }