public IActionResult ExportToImage(string ReportPath, string Parameter = null) { using (MemoryStream ms = new MemoryStream()) { Report report = new Report(); string path = ReportPath; report.Load(path); if (Parameter != null) { var bank = _businessLayer.GetFinInstitutionInfoById(Parameter); report.SetParameterValue("BankName", bank.InstitutionName); report.SetParameterValue("FinancialInstitutionId", int.Parse(Parameter)); } report.Prepare(); ImageExport image = new ImageExport(); image.ImageFormat = ImageExportFormat.Jpeg; image.JpegQuality = 90; image.Resolution = 72; image.SeparateFiles = false; report.Export(image, ms); ms.Flush(); var filenamewithoutreports = path.Remove(0, 8); var filename = filenamewithoutreports.Remove(filenamewithoutreports.Length - 4); return(File(ms.ToArray(), "application/jpeg", filename + DateTime.Now.ToString() + ".jpeg")); } }
public string ExportToFile(Report report) { ExportBase export = null; string fileName = Path.GetTempPath() + @"\_rpt" + DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + Loginer.CurrentUser.Account; if (ExportType.IMG == _exportType) { fileName = fileName + ".png"; export = new ImageExport(); (export as ImageExport).ImageFormat = ImageExportFormat.Png; } else if (ExportType.PDF == _exportType) { fileName = fileName + ".pdf"; export = new PDFExport(); } else if (ExportType.XLS == _exportType) { fileName = fileName + ".xls"; export = new XMLExport(); } else if (ExportType.HTML == _exportType) { fileName = fileName + ".html"; export = new HTMLExport(); } export.AllowOpenAfter = false; report.Export(export, fileName); return(fileName); }
public PassReportGenerator(IEnumerable <Employee> employees) { _employees = employees; IsPrepared = false; _report = new Report(); _export = new ImageExport(); }
private static PrintDocument PrepareDoc(this Report report, PrinterSettings settings = null) { if (report.PreparedPages.Count < 1) { report.Prepare(); if (report.PreparedPages.Count < 1) { return(null); } } var page = 0; var exp = new ImageExport { ImageFormat = ImageExportFormat.Png, Resolution = 600 }; var doc = new PrintDocument { DocumentName = report.Name }; if (settings != null) { doc.PrinterSettings = settings; } // Ajustando o tamanho da pagina doc.QueryPageSettings += (sender, args) => { var rPage = report.PreparedPages.GetPage(page); args.PageSettings.Landscape = rPage.Landscape; args.PageSettings.Margins = new Margins((int)(scaleFactor * rPage.LeftMargin * Units.HundrethsOfInch), (int)(scaleFactor * rPage.RightMargin * Units.HundrethsOfInch), (int)(scaleFactor * rPage.TopMargin * Units.HundrethsOfInch), (int)(scaleFactor * rPage.BottomMargin * Units.HundrethsOfInch)); args.PageSettings.PaperSize = new PaperSize("Custom", (int)(ExportUtils.GetPageWidth(rPage) * scaleFactor * Units.HundrethsOfInch), (int)(ExportUtils.GetPageHeight(rPage) * scaleFactor * Units.HundrethsOfInch)); }; doc.PrintPage += (sender, args) => { using (var ms = new MemoryStream()) { exp.PageRange = PageRange.PageNumbers; exp.PageNumbers = $"{page + 1}"; exp.Export(report, ms); args.Graphics.DrawImage(Image.FromStream(ms), args.PageBounds); } page++; args.HasMorePages = page < report.PreparedPages.Count; }; doc.EndPrint += (sender, args) => page = 0; doc.Disposed += (sender, args) => exp?.Dispose(); return(doc); }
static void Main(string[] args) { Console.WriteLine("Welcome! Choose report type, please:\n" + "1 - SimpleList\n" + "2 - MasterDetail\n" + "3 - Group\n" + "4 - NestedGroups\n" + "5 - Subreport\n" + "6 - Table"); Report report; //while 1,2,3,4 is not pressed char key; do { key = Console.ReadKey().KeyChar; }while ((int)key < 49 || (int)key > 54); // create report instance switch (key) { case '1': report = GetSimpleListReport(); break; case '2': report = GetMasterDetailReport(); break; case '3': report = GetGroupReport(); break; case '4': report = GetNestedGroupsReport(); break; case '5': report = GetSubreportReport(); break; case '6': report = GetTableReport(); break; default: report = GetSimpleListReport(); break; } // prepare the report report.Prepare(); // save prepared report if (!Directory.Exists(outFolder)) { Directory.CreateDirectory(outFolder); } report.SavePrepared($@"{outFolder}\Prepared Report.fpx"); // export to image ImageExport image = new ImageExport(); image.ImageFormat = ImageExportFormat.Jpeg; report.Export(image, $@"{outFolder}\report.jpg"); // free resources used by report report.Dispose(); Console.WriteLine("\nPrepared report and report exported as image have been saved into the 'out' folder."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("Welcome! Press any key to procced..."); Console.ReadKey(); RegisterOwnFunctions(); // create report instance Report report = new Report(); // add report page ReportPage page = new ReportPage(); report.Pages.Add(page); // always give names to objects you create. You can use CreateUniqueName method to do this; // call it after the object is added to a report. page.CreateUniqueName(); // create title band page.ReportTitle = new ReportTitleBand(); // native FastReport unit is screen pixel, use conversion page.ReportTitle.Height = Units.Centimeters * 1; page.ReportTitle.CreateUniqueName(); // create two title text objects TextObject titleText1 = new TextObject(); titleText1.Parent = page.ReportTitle; titleText1.CreateUniqueName(); titleText1.Bounds = new RectangleF(0, 0, Units.Centimeters * 8, Units.Centimeters * 1); titleText1.Font = new Font("Arial", 14, FontStyle.Bold); titleText1.HorzAlign = HorzAlign.Center; // !!! use our function titleText1.Text = "[MyUpperCase(\"products\")]"; // !!! // prepare the report report.Prepare(); // save prepared report if (!Directory.Exists(outFolder)) { Directory.CreateDirectory(outFolder); } report.SavePrepared($@"{outFolder}\Prepared Report.fpx"); // export to image ImageExport image = new ImageExport(); image.ImageFormat = ImageExportFormat.Jpeg; report.Export(image, $@"{outFolder}\report.jpg"); // free resources used by report report.Dispose(); Console.WriteLine("\nPrepared report and report exported as image have been saved into the 'out' folder."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public static void GenereteReport(ReportParams reportParams) { if (reportParams == null) { throw new ArgumentNullException($"{nameof(reportParams)} cannot be null."); } // create report instance using (FastReport.Report report = new FastReport.Report()) { // load the existing report report.Load(reportParams.FrxPath); // register datasource's if (reportParams.DataSource != null) { foreach (var pair in reportParams.DataSource) { report.RegisterData(pair.Value, pair.Key); } } if (reportParams.Parameters != null) { foreach (var pair in reportParams.Parameters) { report.SetParameterValue(pair.Key, pair.Value); } } // prepare the report report.Prepare(); ExportBase export = null; switch (reportParams.OutputType) { case 0: // export to html export = new HTMLExport(); (export as HTMLExport).Format = HTMLExportFormat.HTML; break; case 1: export = new ImageExport(); (export as ImageExport).ImageFormat = ImageExportFormat.Png; break; default: throw new ArgumentException($"O parametro {reportParams.OutputType} é inválido"); } report.Export(export, reportParams.OutStream); } reportParams.OutStream.Position = 0; }
public byte[] PrintResult(string userNo, int page) { try { Config.WebMode = true; Report rep = new Report(); rep.Load(Server.MapPath("~/App_Data/rptResult.frx")); using (VShapeUpDataContext _context = new VShapeUpDataContext()) { var data = (from x in _context.V_ChallengeResult_Reports where x.UserNo == userNo && x.Page == page select x).ToList().ToDataTable(); rep.RegisterData(data, "Report"); DataBand band = rep.FindObject("Data") as DataBand; band.DataSource = rep.GetDataSource("Report"); } if (rep.Report.Prepare()) { //PDFExport pdfExport = new PDFExport(); //pdfExport.ShowProgress = false; //pdfExport.Compressed = true; //pdfExport.AllowPrint = true; //pdfExport.EmbeddingFonts = true; //MemoryStream strm = new MemoryStream(); //rep.Report.Export(pdfExport, strm); //rep.Dispose(); //pdfExport.Dispose(); //strm.Position = 0; //return strm.ToArray(); ImageExport export = new ImageExport(); MemoryStream strm = new MemoryStream(); rep.Report.Export(export, strm); rep.Dispose(); export.Dispose(); strm.Position = 0; return(strm.ToArray()); } else { return(null); } } catch (Exception ex) { return(null); } }
public byte[] Exportar(Report relatorio) { using (var ms = new MemoryStream()) { ImageExport image = new ImageExport(); image.ImageFormat = ImageExportFormat.Jpeg; image.JpegQuality = 90; image.Resolution = 72; image.SeparateFiles = false; relatorio.Export(image, ms); return(ms.ToArray()); } }
protected void OnSavePlotAsImage(string plotType, string fileFormat) { var filename = $"{CurrentGameName}_SynchronizationChartExport_{plotType}"; if (fileFormat == "svg") { ImageExport.SavePlotAsSVG(plotType == "inputlag" ? InputLagModel : SynchronizationModel, filename, _appConfiguration.HorizontalGraphExportRes, _appConfiguration.VerticalGraphExportRes); } else if (fileFormat == "png") { ImageExport.SavePlotAsPNG(plotType == "inputlag" ? InputLagModel : SynchronizationModel, filename, _appConfiguration.HorizontalGraphExportRes, _appConfiguration.VerticalGraphExportRes, _appConfiguration.UseDarkMode); } }
static void Main(string[] args) { using (var report = new Report()) { var movies = new List <Movie> { new Movie { SN = "tt1979376", Name = "Toy Story 4", Director = "Josh Cooley", EstimatedBudget = "$200,000,000", ReleaseDate = "21 June 2019" }, new Movie { SN = "tt3263904", Name = "Sully", Director = "Clint Eastwood", EstimatedBudget = "$60,000,000", ReleaseDate = "9 September 2016" }, new Movie { SN = "tt1535109", Name = "Captain Phillips", Director = "Paul Greengrass", EstimatedBudget = "$55,000,000", ReleaseDate = "11 October 2013" }, }; report.Load("report.frx"); report.RegisterData(movies, "Movies"); report.SetParameterValue("LastUpdated", DateTime.Now); report.Prepare(); using (var imageExporter = new ImageExport()) { imageExporter.ImageFormat = ImageExportFormat.Metafile; imageExporter.Resolution = 96; report.Export(imageExporter, "report.emf"); } } }
public void ExportarPng(Stream outputStream) { try { Relatorio.Prepare(); ImageExport png = new ImageExport { ImageFormat = ImageExportFormat.Png, SeparateFiles = false }; Relatorio.Export(png, outputStream); outputStream.Position = 0; } catch (System.Exception ex) { throw ex; } }
public byte[] PrintAllChallenger() { try { Config.WebMode = true; Report rep = new Report(); rep.Load(Server.MapPath("~/App_Data/rptResult.frx")); using (VShapeUpDataContext _context = new VShapeUpDataContext()) { var data = (from x in _context.V_RegisterChallengeResult_Reports select x).ToList().ToDataTable(); rep.RegisterData(data, "Report"); DataBand band = rep.FindObject("Data") as DataBand; band.DataSource = rep.GetDataSource("Report"); band.Sort.Add(new Sort("[ReportData.UserNo]")); band.Sort.Add(new Sort("[ReportData.Page]")); } if (rep.Report.Prepare()) { ImageExport export = new ImageExport(); MemoryStream strm = new MemoryStream(); rep.Report.Export(export, strm); rep.Dispose(); export.Dispose(); strm.Position = 0; return(strm.ToArray()); } else { return(null); } } catch (Exception ex) { return(null); } }
public byte[] ExportarPng() { using (MemoryStream stream = new MemoryStream()) // Create a stream for the report { try { Relatorio.Prepare(); ImageExport png = new ImageExport { ImageFormat = ImageExportFormat.Png, SeparateFiles = false }; Relatorio.Export(png, stream); return(stream.ToArray()); } catch (System.Exception ex) { throw ex; } } }
private void Method2() { #region 加载打印模板 Report report = new Report(); report.Load(Server.MapPath("~/BatchPurchase.frx")); report.RegisterData(GetDataSet()); report.Show(); report.Prepare(); #region 导出打印结果图片 string filePath = @"D:\TEMP\1.jpg"; ImageExport export = new ImageExport(); report.Export(export, filePath); #endregion #region 导出PDF string pdfFilePath = @"D:\TEMP\1.pdf"; PDFExport pdfExport = new PDFExport(); report.Export(pdfExport, pdfFilePath); #endregion //using (MemoryStream strm = new MemoryStream()) //{ // report.Export(pdfExport, strm); // // Stream the PDF back to the client as an attachment // Response.ClearContent(); // Response.ClearHeaders(); // Response.Buffer = true; // Response.ContentType = "Application/PDF"; // Response.AddHeader("Content-Disposition", "attachment;filename=report.pdf"); // strm.Position = 0; // strm.WriteTo(Response.OutputStream); // Response.End(); //} //report.Show(); #endregion }
static void Main(string[] args) { Console.WriteLine("Welcome! Press any key to procced..."); Console.ReadKey(); CreateBusinessObject(); // create report instance Report report = new Report(); // load the existing report report.Load($@"{inFolder}\report.frx"); // register the array report.RegisterData(businessObjects, "Categories"); // prepare the report report.Prepare(); // save prepared report if (!Directory.Exists(outFolder)) { Directory.CreateDirectory(outFolder); } report.SavePrepared($@"{outFolder}\Prepared Report.fpx"); // export to image ImageExport image = new ImageExport(); image.ImageFormat = ImageExportFormat.Jpeg; report.Export(image, $@"{outFolder}\report.jpg"); // free resources used by report report.Dispose(); Console.WriteLine("\nPrepared report and report exported as image have been saved into the 'out' folder."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
private void buttonConvert_Click(object sender, EventArgs e) { Report report = new Report(); report.Load("1.frx"); RichObject rich = new RichObject(); try { using (StreamReader reader = new StreamReader(openFileDialog1.FileName, Encoding.Default)) { rich.Text = reader.ReadToEnd(); reader.Close(); } } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine(rich.Text); report.SetParameterValue("Parameter.Parameter", rich.Text); report.Prepare(); switch (id) { case 0: PDFExport pdf = new PDFExport(); report.Export(pdf, "result" + comboBoxFormat.Text); report.Dispose(); break; case 1: ImageExport image1 = new ImageExport(); report.Export(image1, "result" + comboBoxFormat.Text); report.Dispose(); break; case 2: ImageExport image2 = new ImageExport(); report.Export(image2, "result" + comboBoxFormat.Text); report.Dispose(); break; case 3: SVGExport svg = new SVGExport(); report.Export(svg, "result" + comboBoxFormat.Text); report.Dispose(); break; case 4: HTMLExport html = new HTMLExport(); report.Export(html, "result" + comboBoxFormat.Text); report.Dispose(); break; } Console.WriteLine("End"); }
// Gets Report by ID with query public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query) { // Find the report Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem != null) { string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName); string dataPath = HostingEnvironment.MapPath("~/App_Data/nwind-employees.xml"); MemoryStream stream = new MemoryStream(); try { using (DataSet dataSet = new DataSet()) { dataSet.ReadXml(dataPath); Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); report.RegisterData(dataSet, "NorthWind"); if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); } // Two prepare Phases for eliminate any report dialogs report.PreparePhase1(); report.PreparePhase2(); if (query.Format == "pdf") { PDFExport pdf = new PDFExport(); report.Export(pdf, stream); } else if (query.Format == "html") { using (HTMLExport html = new HTMLExport()) { html.SinglePage = true; html.Navigator = false; html.EmbedPictures = true; report.Export(html, stream); } } else if (query.Format == "png") { using (ImageExport img = new ImageExport()) { img.ImageFormat = ImageExportFormat.Png; img.SeparateFiles = false; img.ResolutionX = 96; img.ResolutionY = 96; report.Export(img, stream); query.Format = "png"; } } else { WebReport webReport = new WebReport(); webReport.Report.Load(reportPath); webReport.Report.RegisterData(dataSet, "NorthWind"); if (query.Parameter != null) { webReport.Report.SetParameterValue("Parameter", query.Parameter); } // inline registration of FastReport javascript webReport.InlineRegistration = true; webReport.Width = Unit.Percentage(100); webReport.Height = Unit.Percentage(100); // get control HtmlString reportHtml = webReport.GetHtml(); byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString()); stream.Write(streamArray, 0, streamArray.Length); } } } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.ToArray()) }; stream.Dispose(); if (query.Format != null) { result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment") { FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format) }; } result.Content.Headers.ContentType = query.Format == null ? new MediaTypeHeaderValue("text/html") : new MediaTypeHeaderValue("application/" + query.Format); return(result); } catch { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } else { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
private static int RunInternal(Options options) { if (!File.Exists(options.InputRfxFilePath)) { Console.WriteLine("Input file \"{0}\" doesn't exist.", options.InputRfxFilePath); return(1); } using (var report = new Report()) { try { report.Load(options.InputRfxFilePath); } catch (Exception ex) { Console.WriteLine("Failed to load report template \"{0}\":\n{1}", options.InputRfxFilePath, ex); return(1); } 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]); } if (!report.Prepare()) { Console.WriteLine("Failed to prepare report."); return(1); } if (string.IsNullOrWhiteSpace(options.OutputFilePath)) { string extension = ImageFormatToExtension(options.Format); if (string.IsNullOrWhiteSpace(extension)) { Console.WriteLine("Unknown image 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; } using (var imageExporter = new ImageExport()) { imageExporter.ImageFormat = options.Format; if (options.Resolution > 0) { imageExporter.Resolution = options.Resolution; } else if (options.ResolutionX > 0 && options.ResolutionY > 0) { imageExporter.ResolutionX = options.ResolutionX; imageExporter.ResolutionY = options.ResolutionY; } 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)); } }
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); }
public static void CreateReport(Person person) { if (person == null) { throw new ArgumentNullException("person"); } var applicationFilePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); using (var report = new Report()) { try { report.Load(Path.Combine(applicationFilePath, "./Template.frx")); } catch (Exception ex) { MsgBox.Error("Failed to load report template.\r\n{0}", ex.ToString()); } if (person.Name != null) { report.SetParameterValue("Name", person.Name); } if (person.Age != null) { report.SetParameterValue("Age", person.Age.Value); } if (person.Gender != null) { report.SetParameterValue("Gender", person.Gender); } if (person.ID != null) { report.SetParameterValue("ID", person.ID); } if (person.Address != null) { report.SetParameterValue("Address", person.Address); } if (person.Phone != null) { report.SetParameterValue("Phone", person.Phone); } if (!report.Prepare()) { MsgBox.Error("Report.Prepare failed."); return; } else { MsgBox.Information("Report.Prepare"); } using (var imageExporter = new ImageExport()) { imageExporter.ImageFormat = ImageExportFormat.Metafile; imageExporter.Resolution = 600; report.Export(imageExporter, "Report.emf"); } } }
public IActionResult Get(int id, [FromQuery] ReportQuery query) { // MIME header with default value string mime = "application/" + query.Format; // Find report // we get the value of the collection by id ReportEntity reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem != null) { string webRootPath = _hostingEnvironment.WebRootPath; // determine the path to the wwwroot folder string reportPath = (webRootPath + "/App_Data/" + reportItem.ReportName); // determine the path to the report string dataPath = (webRootPath + "/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 by data dataSet.ReadXml(dataPath); // Turn on web mode FastReport Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); report.RegisterData(dataSet, "NorthWind"); if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); } //Prepare the report report.Prepare(); if (query.Format == "png") { // Export report to PDF ImageExport png = new ImageExport(); png.ImageFormat = ImageExportFormat.Png; png.SeparateFiles = false; // Use the stream to store the report, so as not to create unnecessary files report.Export(png, stream); } #if !OPENSOURCE // If pdf format is selected if (query.Format == "pdf") { // Export report to PDF PDFExport pdf = new PDFExport(); // Use the stream to store the report, so as not to create unnecessary files report.Export(pdf, stream); } #endif //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 into a document report.Export(html, stream); mime = "text/" + query.Format; // Override mime for html } } } // Get the name of the resulting report file with the necessary extension var file = string.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format); // If the inline parameter is true, then open the report in the browser if (query.Inline) { return(File(stream.ToArray(), mime)); } else { // Otherwise download the report file return(File(stream.ToArray(), mime, file)); // attachment } } // Handle exceptions catch (Exception ex) { return(new NoContentResult()); } finally { stream.Dispose(); } } } else { return(NotFound()); } }
public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query) { // Find the report Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem != null) { string reportPath = "../../App_Data/" + reportItem.ReportName; string dataPath = "../../App_Data/nwind-employees.xml"; MemoryStream stream = new MemoryStream(); try { using (DataSet dataSet = new DataSet()) { dataSet.ReadXml(dataPath); Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); report.RegisterData(dataSet, "NorthWind"); if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); } // Two prepare Phases for eliminate any report dialogs report.PreparePhase1(); report.PreparePhase2(); if (query.Format == "pdf") { PDFExport pdf = new PDFExport(); report.Export(pdf, stream); } else if (query.Format == "html") { using (HTMLExport html = new HTMLExport()) { html.SinglePage = true; html.Navigator = false; html.EmbedPictures = true; report.Export(html, stream); } } else { using (ImageExport img = new ImageExport()) { img.ImageFormat = ImageExportFormat.Png; img.SeparateFiles = false; img.ResolutionX = 96; img.ResolutionY = 96; report.Export(img, stream); query.Format = "png"; } } } } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.ToArray()) }; stream.Dispose(); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment") { FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + query.Format); return(result); } catch { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } else { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }