示例#1
0
        void DoAllHtmlPages(StringBuilder sb, HTMLExport html)
        {
            //Prop.CurrentWidth = 0;
            //Prop.CurrentHeight = 0;

            for (int pageN = 0; pageN < html.PreparedPages.Count; pageN++)
            {
                if (html.PreparedPages[pageN].PageText == null)
                {
                    html.PageNumbers = (pageN + 1).ToString();
                    html.Export(Report, (Stream)null);

                    //if (html.PreparedPages[pageN].Width > Prop.CurrentWidth)
                    //    Prop.CurrentWidth = html.PreparedPages[pageN].Width;
                    //if (html.PreparedPages[pageN].Height > Prop.CurrentHeight)
                    //    Prop.CurrentHeight = html.PreparedPages[pageN].Height;
                }

                if (html.PreparedPages[pageN].CSSText != null &&
                    html.PreparedPages[pageN].PageText != null)
                {
                    sb.Append(html.PreparedPages[pageN].CSSText);
                    sb.Append(html.PreparedPages[pageN].PageText);

                    if (!EmbedPictures)
                    {
                        CacheHtmlPictures(html, Layers ? 0 : pageN);
                    }
                }
            }
        }
示例#2
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            // Creating a new document.
            WordDocument document    = new WordDocument();
            Stream       inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.WordtoHTML.doc");

            //Open the Word document to convert
            document.Open(inputStream, FormatType.Doc);
            //Export the Word document to HTML file
            MemoryStream stream     = new MemoryStream();
            HTMLExport   htmlExport = new HTMLExport();

            htmlExport.SaveAsXhtml(document, stream);
            document.Close();
            stream.Position = 0;
            StreamReader reader     = new StreamReader(stream);
            string       htmlString = reader.ReadToEnd();

            isGenerateButtonClicked = true;
            UIWebView webView = new UIWebView(this.Bounds);

            webView.Frame = new CGRect(0, 0, this.Bounds.Width, this.Bounds.Height);
            this.AddSubview(webView);
            webView.LoadHtmlString(htmlString, NSBundle.MainBundle.BundleUrl);
            webView.ScalesPageToFit = false;
        }
示例#3
0
        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);
        }
示例#4
0
        public IActionResult Index(int?report = null)
        {
            string strReport = ReportFiles[report.GetValueOrDefault()];

            if (strReport != null)
            {
                Report r = new Report();

                if (NorthWind == null)
                {
                    NorthWind = _context.GetDataSet("NorthWind");
                }
                r.RegisterData(NorthWind, "NorthWind");
                r.Load(strReport);

                r.Prepare();
                HTMLExport export = new HTMLExport();
                export.Layers = true;
                using (MemoryStream ms = new MemoryStream())
                {
                    export.EmbedPictures = true;
                    export.Export(r, ms);
                    ms.Flush();
                    ViewData["Report"]     = Encoding.UTF8.GetString(ms.ToArray());
                    ViewData["ReportName"] = strReport;
                }
            }
            return(View());
        }
示例#5
0
        internal IActionResult PrintHtml(BaseController controller)
        {
            PictureCache.Clear();

            using (var htmlExport = new HTMLExport())
            {
                htmlExport.OpenAfterExport = false;
                htmlExport.Navigator       = false;
                htmlExport.Layers          = Layers;
                htmlExport.SinglePage      = true;
                htmlExport.Pictures        = Pictures;
                htmlExport.Print           = true;
                htmlExport.Preview         = true;
                htmlExport.SubFolder       = false;
                htmlExport.EmbedPictures   = EmbedPictures;
                //htmlExport.WebImagePrefix = WebUtils.ToUrl(FastReportGlobal.FastReportOptions.RouteBasePath, controller.RouteBasePath, ID, "picture") + "/";
                htmlExport.WebImagePrefix = WebUtils.ToUrl(FastReportGlobal.FastReportOptions.RouteBasePath, $"preview.getPicture?reportId={ID}&pictureId=");
                htmlExport.ExportMode     = HTMLExport.ExportType.WebPrint;

                byte[] file = null;

                using (MemoryStream ms = new MemoryStream())
                {
                    htmlExport.Export(Report, ms);
                    file = ms.ToArray();
                }

                if (htmlExport.PrintPageData != null)
                {
                    //WebReportCache cache = new WebReportCache(this.Context);

                    // add all pictures in cache
                    for (int i = 0; i < htmlExport.PrintPageData.Pictures.Count; i++)
                    {
                        Stream stream = htmlExport.PrintPageData.Pictures[i];
                        byte[] image  = new byte[stream.Length];
                        stream.Position = 0;
                        int    n       = stream.Read(image, 0, (int)stream.Length);
                        string picGuid = htmlExport.PrintPageData.Guids[i];
                        //cache.PutObject(picGuid, image);
                        PictureCache[picGuid] = image;
                    }

                    // cleanup
                    for (int i = 0; i < htmlExport.PrintPageData.Pictures.Count; i++)
                    {
                        Stream stream = htmlExport.PrintPageData.Pictures[i];
                        stream.Dispose();
                        stream = null;
                    }

                    htmlExport.PrintPageData.Pictures.Clear();
                    htmlExport.PrintPageData.Guids.Clear();
                }

                return(new FileContentResult(file, "text/html"));
            }
        }
        public IActionResult Get()
        {
            //var webRootPath = _hostingEnvironment.WebRootPath;
            var ReportPath = (@"Reports\Master-Detail.frx");

            if (!System.IO.File.Exists(ReportPath))
            {
                return(NotFound());
            }

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

                    var Mime = "text/htlm";

                    using (Report report = new Report())
                    {
                        var dataSet = new DataSet();
                        dataSet.ReadXml(@"Data\nwind.xml");

                        report.Load(ReportPath);
                        report.RegisterData(dataSet, "NorthWind");
                        report.Prepare();

                        var html = new HTMLExport
                        {
                            SinglePage    = true,
                            Navigator     = false,
                            EmbedPictures = true
                        };

                        report.Export(html, stream);
                    }

                    // Get the name of the resulting report file with the necessary extension
                    //var file = string.Concat(Path.GetFileNameWithoutExtension(reportPath), ".html");
                    // ... and Download the report file
                    //return File(stream.ToArray(), Mime, file); // attachment

                    //... or open the report in the browser
                    return(File(stream.ToArray(), Mime));
                }
                // Handle exceptions
                catch (Exception ex)
                {
                    return(new NoContentResult());
                }
                finally
                {
                    stream.Dispose();
                }
            }
        }
        private void Imprimir()
        {
            internalReport.Prepare();

            if (ShowDesign)
            {
                internalReport.Design();
            }
            else
            {
                switch (Filtro)
                {
                case FiltroDFeReport.Nenhum:
                    if (MostrarPreview)
                    {
                        internalReport.Show();
                    }
                    else
                    {
                        internalReport.Print();
                    }
                    break;

                case FiltroDFeReport.PDF:
                    var pdfExport = new PDFExport
                    {
                        EmbeddingFonts  = true,
                        ShowProgress    = MostrarSetup,
                        PdfCompliance   = PDFExport.PdfStandard.PdfA_3b,
                        OpenAfterExport = MostrarPreview
                    };

                    internalReport.Export(pdfExport, NomeArquivo);
                    break;

                case FiltroDFeReport.HTML:
                    var htmlExport = new HTMLExport
                    {
                        Format        = HTMLExportFormat.MessageHTML,
                        EmbedPictures = true,
                        Preview       = MostrarPreview,
                        ShowProgress  = MostrarSetup
                    };

                    internalReport.Export(htmlExport, NomeArquivo);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            internalReport.Dispose();
            internalReport = null;
        }
示例#8
0
        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;
        }
        /// <summary>
        /// Generate html string from document template
        /// </summary>
        /// <returns>string of html</returns>
        public string GenerateHtml()
        {
            ProcessDocument();
            ProcessDocumentGroup();
            HTMLExport export = new HTMLExport();

            export.SaveAsXhtml(DocumentTemplate, HTMLStreamOutput);
            StreamReader reader = new StreamReader(HTMLStreamOutput);

            HTMLStreamOutput.Position = 0;
            return(reader.ReadToEnd());
        }
示例#10
0
        protected override void Done()
        {
            base.Done();
            HTMLExport htmlExport = Export as HTMLExport;

            htmlExport.Layers     = cbLayers.Checked;
            htmlExport.Wysiwyg    = cbWysiwyg.Checked;
            htmlExport.Pictures   = cbPictures.Checked;
            htmlExport.SinglePage = cbSinglePage.Checked;
            htmlExport.SubFolder  = cbSubFolder.Checked;
            htmlExport.Navigator  = cbNavigator.Checked;
        }
示例#11
0
        public override void Init(ExportBase export)
        {
            base.Init(export);
            HTMLExport htmlExport = Export as HTMLExport;

            cbWysiwyg.Checked    = htmlExport.Wysiwyg;
            cbPictures.Checked   = htmlExport.Pictures;
            cbSinglePage.Checked = htmlExport.SinglePage;
            cbSubFolder.Checked  = htmlExport.SubFolder;
            cbNavigator.Checked  = htmlExport.Navigator;
            cbLayers.Checked     = htmlExport.Layers;
        }
示例#12
0
        //public async Task<ActionResult> PrintStock(int id)
        //{
        //    var reportItem = "stock.frx";
        //    if (reportItem != null)
        //    {
        //        var path = $"{_iwebhost.WebRootPath}/reports/{reportItem}";

        //        try
        //        {
        //            var supplier = "ALL";
        //            IEnumerable<ShareModels.ModelViews.ProductStock> data = new List<ShareModels.ModelViews.ProductStock>();
        //            if(id<=0)
        //                data = (await _productService.GetProductStock()).OrderBy(x=>x.Name);
        //            else
        //            {
        //                data = (await _productService.GetProductStock()).Where(x => x.Supplier.Id == id).OrderBy(x => x.Name);
        //                supplier = data.FirstOrDefault().Supplier.Nama;
        //            }
        //            var datas = new List<ShareModels.Reports.NotaData>();
        //            int nomor = 1;
        //            foreach (var item in data)
        //            {
        //                datas.Add(new ShareModels.Reports.NotaData
        //                {
        //                    No = nomor,
        //                    Amount = item.StockView,
        //                    CodeArticle = item.CodeArticle,
        //                    CodeProduct = item.CodeName,
        //                    ProductName = $"{item.Name} {item.Size}",
        //                    Unit = item.SelectedUnit.Name,
        //                    Price = item.SelectedUnit.Sell,
        //                    Size = item.Size,
        //                    Total = item.SelectedUnit.Sell * item.StockView,

        //                });

        //                nomor++;
        //            }

        //            var datasets = datas.ToDataTable();
        //            return PrintStockAction(datasets, supplier, path);

        //        }
        //        catch (Exception)
        //        {
        //            return new NoContentResult();
        //        }
        //    }
        //    else
        //        return NotFound();
        //}

        private ActionResult PrintStockAction(DataTable datasets, Dictionary <string, string> dataParams, string path)
        {
            using MemoryStream stream = new MemoryStream();
            try
            {
                var mime = "text/" + "html"; //redefine mime for html
                datasets.TableName = "Table1";
                DataSet ds = new DataSet();
                ds.DataSetName = "Stock";
                ds.Tables.Add(datasets);
                ds.WriteXml($"{_iwebhost.WebRootPath}/reports/Stock.xml");

                Config.WebMode = true;
                using (Report report = new Report())
                {
                    report.Load(path);                                  //Load the report
                    report.RegisterData(ds.Tables["Table1"], "Table1"); //Register data in the report


                    foreach (var item in dataParams)
                    {
                        report.SetParameterValue(item.Key, item.Value);
                    }

                    report.Prepare();
                    HTMLExport html = new HTMLExport
                    {
                        SinglePage    = true, //report on the one page
                        Navigator     = true, //navigation panel on top
                        EmbedPictures = true,
                        Print         = true, Preview = true,
                        PageBreaks    = true
                    };
                    report.Export(html, stream);

                    report.GetDataSource("Table1").Enabled = true;
                }
                //Get the name of resulting report file with needed extension
                var file = String.Concat(Path.GetFileNameWithoutExtension(path), ".", "html");
                return(File(stream.ToArray(), mime));
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
            finally
            {
                stream.Dispose();
            }
        }
        private void Print()
        {
            internalReport.Prepare();

            switch (Filtro)
            {
            case ExtratoFiltro.Nenhum:
                if (MostrarPreview)
                {
                    internalReport.Show();
                }
                else
                {
                    internalReport.Print();
                }
                break;

            case ExtratoFiltro.PDF:
                var pdfExport = new PDFExport
                {
                    EmbeddingFonts  = true,
                    ShowProgress    = MostrarSetup,
                    JpegCompression = true,
                    JpegQuality     = 9,
                    OpenAfterExport = MostrarPreview
                };

                internalReport.Export(pdfExport, NomeArquivo);
                break;

            case ExtratoFiltro.HTML:
                var htmlExport = new HTMLExport
                {
                    Format        = HTMLExportFormat.MessageHTML,
                    EmbedPictures = true,
                    Preview       = MostrarPreview,
                    ShowProgress  = MostrarSetup
                };

                internalReport.Export(htmlExport, NomeArquivo);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            internalReport.Dispose();
            internalReport = null;
        }
示例#14
0
        /// <summary>
        /// Write the attributes of the tag specified
        /// </summary>
        /// <param name="p_Cell"></param>
        /// <param name="p_Position"></param>
        /// <param name="p_Export"></param>
        /// <param name="p_Writer"></param>
        /// <param name="p_ElementTagName"></param>
        protected virtual void ExportHTML_Attributes(Cells.ICellVirtual p_Cell, Position p_Position, IHTMLExport p_Export, System.Xml.XmlTextWriter p_Writer, string p_ElementTagName)
        {
            if (p_ElementTagName == "td")
            {
                //check for rowspan and colspan
                if (p_Cell is ICell)
                {
                    //TODO non è bellissimo mettere questo if (pensare come poter fare in un altro modo)
                    ICell l_Cell = (ICell)p_Cell;
                    //colspan, rowspan
                    p_Writer.WriteAttributeString("colspan", l_Cell.ColumnSpan.ToString());
                    p_Writer.WriteAttributeString("rowspan", l_Cell.RowSpan.ToString());
                }

                //write backcolor
                if ((p_Export.Mode & ExportHTMLMode.CellBackColor) == ExportHTMLMode.CellBackColor)
                {
                    p_Writer.WriteAttributeString("bgcolor", HTMLExport.ColorToHTML(BackColor));
                }

                string l_Style = "";

                //border
                l_Style = HTMLExport.CellBorderToHTMLStyle(Border);

                //style
                p_Writer.WriteAttributeString("style", l_Style);

                //alignment
                p_Writer.WriteAttributeString("align", Utility.ContentToHorizontalAlignment(TextAlignment).ToString().ToLower());
                if (Utility.IsBottom(TextAlignment))
                {
                    p_Writer.WriteAttributeString("valign", "bottom");
                }
                else if (Utility.IsTop(TextAlignment))
                {
                    p_Writer.WriteAttributeString("valign", "top");
                }
                else if (Utility.IsMiddle(TextAlignment))
                {
                    p_Writer.WriteAttributeString("valign", "middle");
                }
            }
            else if (p_ElementTagName == "font")
            {
                p_Writer.WriteAttributeString("color", HTMLExport.ColorToHTML(ForeColor));
            }
        }
示例#15
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(WordToHTML).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();

#if COMMONSB
            string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates.";
#else
            string rootPath = "SampleBrowser.DocIO.Samples.Templates.";
#endif
            Stream inputStream = assembly.GetManifestResourceStream(rootPath + "WordtoHTML.doc");
            //Open the Word document to convert
            document.Open(inputStream, FormatType.Doc);
            //Export the Word document to HTML file
            MemoryStream stream     = new MemoryStream();
            HTMLExport   htmlExport = new HTMLExport();
            htmlExport.SaveAsXhtml(document, stream);
            document.Close();

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("WordtoHTML.html", "application/html", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("WordtoHTML.html", "application/html", stream);
            }
            if (!(Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP))
            {
                //Set the stream to start position to read the content as string
                stream.Position = 0;
                StreamReader reader     = new StreamReader(stream);
                string       htmlString = reader.ReadToEnd();

                //Set the HtmlWebViewSource to the html string
                HtmlWebViewSource html = new HtmlWebViewSource();
                html.Html = htmlString;

                //Create the web view control to view the web page
                WebView view = new WebView();
                view.Source = html;
                ContentPage webpage = new ContentPage();
                webpage.Content = view;
                this.Content.Navigation.PushAsync(webpage);
            }
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (this.textBox1.Text != String.Empty)
                {
                    //Open the document to convert from word to HTML
                    WordDocument doc = new WordDocument(textBox1.Tag.ToString());
                    //Export the document to HTML and save as .html file
                    HTMLExport htmlExport = new HTMLExport();
                    htmlExport.SaveAsXhtml(doc, "DocToHtml.html");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the HTML file?", "File has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("DocToHtml.html")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("DocToHtml.html");
#endif
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    MessageBoxAdv.Show("Browse a word document and click the button to convert as a HTML.");
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
示例#17
0
 public void ExportarHtml(Stream outputStream)
 {
     try
     {
         Relatorio.Prepare();
         HTMLExport html = new HTMLExport
         {
             SinglePage    = true,  // Single page report
             Navigator     = false, // Top navigation bar
             EmbedPictures = true   // Embeds images into a document
         };
         Relatorio.Export(html, outputStream);
         outputStream.Position = 0;
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
示例#18
0
 void CacheHtmlPictures(HTMLExport html, int pageN)
 {
     //WebReportCache cache = new WebReportCache(this.Context);
     for (int i = 0; i < html.PreparedPages[pageN].Pictures.Count; i++)
     {
         try
         {
             Stream picStream = html.PreparedPages[pageN].Pictures[i];
             byte[] image     = new byte[picStream.Length];
             picStream.Position = 0;
             int    n    = picStream.Read(image, 0, (int)picStream.Length);
             string guid = html.PreparedPages[pageN].Guids[i];
             //cache.PutObject(guid, image);
             PictureCache[guid] = image;
         }
         catch
         {
             //Log.AppendFormat("Error with picture: {0}\n", i.ToString());
         }
     }
 }
示例#19
0
 public byte[] ExportarHtml()
 {
     using (MemoryStream stream = new MemoryStream()) // Create a stream for the report
     {
         try
         {
             Relatorio.Prepare();
             HTMLExport html = new HTMLExport
             {
                 SinglePage    = true,  // Single page report
                 Navigator     = false, // Top navigation bar
                 EmbedPictures = true   // Embeds images into a document
             };
             Relatorio.Export(html, stream);
             return(stream.ToArray());
         }
         catch (System.Exception ex)
         {
             throw ex;
         }
     }
 }
示例#20
0
        void DoHtmlPage(StringBuilder sb, HTMLExport html, int pageN)
        {
            if (html.PreparedPages[pageN].PageText == null)
            {
                html.PageNumbers = (pageN + 1).ToString();
                html.Export(Report, (Stream)null);
            }

            //Prop.CurrentWidth = html.PreparedPages[pageN].Width;
            //Prop.CurrentHeight = html.PreparedPages[pageN].Height;

            if (html.PreparedPages[pageN].CSSText != null &&
                html.PreparedPages[pageN].PageText != null)
            {
                sb.Append(html.PreparedPages[pageN].CSSText);
                sb.Append(html.PreparedPages[pageN].PageText);

                if (!EmbedPictures)
                {
                    CacheHtmlPictures(html, pageN);
                }
            }
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(App).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();
            Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.WordtoHTML.doc");
            //Open the Word document to convert
            document.Open(inputStream, FormatType.Doc);
            //Export the Word document to HTML file
            MemoryStream stream = new MemoryStream();
            HTMLExport htmlExport = new HTMLExport();
            htmlExport.SaveAsXhtml(document, stream);
            document.Close();

            if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WordtoHTML.html", "application/html", stream);
            else
                Xamarin.Forms.DependencyService.Get<ISave>().Save("WordtoHTML.html", "application/html", stream);
            if (!(Device.Idiom != TargetIdiom.Phone && Device.OS == TargetPlatform.Windows))
            {
                //Set the stream to start position to read the content as string
                stream.Position = 0;
                StreamReader reader = new StreamReader(stream);
                string htmlString = reader.ReadToEnd();

                //Set the HtmlWebViewSource to the html string
                HtmlWebViewSource html = new HtmlWebViewSource();
                html.Html = htmlString;

                //Create the web view control to view the web page
                WebView view = new WebView();
                view.Source = html;
                ContentPage webpage = new ContentPage();
                webpage.Content = view;
                this.ContentView.Navigation.PushAsync(webpage);
            }
        }
示例#22
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            // Creating a new document.
            WordDocument document    = new WordDocument();
            Stream       inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.WordtoHTML.doc");

            //Open the Word document to convert
            document.Open(inputStream, FormatType.Doc);
            //Export the Word document to HTML file
            MemoryStream stream     = new MemoryStream();
            HTMLExport   htmlExport = new HTMLExport();

            htmlExport.SaveAsXhtml(document, stream);
            document.Close();
            //Set the stream to start position to read the content as string
            stream.Position = 0;
            StreamReader reader     = new StreamReader(stream);
            string       htmlString = reader.ReadToEnd();
            Intent       i          = new Intent(m_context, typeof(WebViewActivity));

            i.PutExtra("HtmlString", htmlString);
            m_context.StartActivity(i);
        }
示例#23
0
        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");
        }
        public IActionResult Get(int id, [FromQuery] ReportQuery query)
        {
            string mime = "application/" + query.Format;                        //MIME-заголовок со значением по умолчанию
                                                                                // Найти отчет
            Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); //получаем значение коллекции по идентификатору

            if (reportItem != null)
            {
                string webRootPath = _hostingEnvironment.WebRootPath;                      //определяем путь к папке wwwroot
                string reportPath  = (webRootPath + "/App_Data/" + reportItem.ReportName); //определяем путь к отчету

                string dataPath = "";
                switch (reportItem.Id)
                {
                case 1:
                    dataPath = (webRootPath + "/App_Data/XmlDataSet2.xml");    //определяем путь к базе данных
                    MainDataSet.ConnectToData(_configuration.GetConnectionString("CatalogConnection"), dataPath);
                    break;

                case 2:
                    dataPath = (webRootPath + "/App_Data/XmlDataSet.xml");    //определяем путь к базе данных
                    MainDataSet.ConnectToDataReport2(_configuration.GetConnectionString("CatalogConnection"), dataPath);
                    break;
                }

                using (MemoryStream stream = new MemoryStream())     //Создаем поток для отчета
                {
                    try
                    {
                        using (DataSet dataSet = new DataSet())
                        {
                            //Заполняем источник данными
                            dataSet.ReadXml(dataPath);
                            //Включаем веб режим FastReport
                            Config.WebMode = true;
                            using (Report report = new Report())
                            {
                                report.Load(reportPath);                    //Загружаем отчет
                                report.RegisterData(dataSet, "Connection"); //Регистрируем данные в отчете
                                if (query.Parameter != null)
                                {
                                    report.SetParameterValue("Parameter", query.Parameter); //задаем значение параметра отчета, если передано значение параметра в URL
                                }
                                report.Prepare();                                           //подготавливаем отчет
                                                                                            //если выбран формат pdf
                                if (query.Format == "pdf")
                                {
                                    //Экспорт отчета в PDF
                                    PDFExport pdf = new PDFExport();
                                    //Используем поток для хранения отчета, чтобы не создавать лишние файлы
                                    report.Export(pdf, stream);
                                }
                                //если выбран формат отчета html
                                else if (query.Format == "html")
                                {
                                    //Экспорт отчета в HTML
                                    HTMLExport html = new HTMLExport();
                                    html.SinglePage    = true;     //отчет на одной странице
                                    html.Navigator     = false;    //навигационная панель сверху
                                    html.EmbedPictures = true;     //встраивает изображения в документ
                                    report.Export(html, stream);
                                    mime = "text/" + query.Format; //переопределяем mime для html
                                }
                            }
                        }
                        //получаем имя результирующего файла отчета с нужным расширением
                        var file = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format);
                        //если параметр inline истина, то открываем отчет в браузере
                        if (query.Inline)
                        {
                            return(File(stream.ToArray(), mime));
                        }
                        else
                        {
                            //иначе скачиваем файл отчета
                            return(File(stream.ToArray(), mime, file)); // attachment
                        }
                    }
                    //Обрабатываем исключения
                    catch
                    {
                        return(new NoContentResult());
                    }
                    finally
                    {
                        stream.Dispose();
                    }
                }
            }
            else
            {
                return(NotFound());
            }
        }
示例#25
0
        /// <summary>
        /// 用 FastReport return the report in HTML string
        /// Usage Example:
        ///   htmlbox.html = HTML("03", "03Z", "2012-01-01", "2012-01-15");
        /// </summary>
        /// <param name="fromCode"></param>
        /// <param name="toCode"></param>
        /// <param name="fromDate"></param>
        /// <param name="toDate"></param>
        /// <returns></returns>
        public static string HTML(string fromCode, string toCode, string fromDate, string toDate)
        {
            var result = "";

            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 前作最後處理
                        //report.SetParameterValue("pReportTitle", WestwindHelper.GetWord("report.SA1330", "Setting"));                                        // 塞個 report title 入去
                        //! 唔用 parameter, design time 嘅時候容易知道係邊隻 report
                        ((TextObject)report.Report.FindObject("lblReportTitle")).Text = WestwindHelper.GetWord("report.SA1330", "Setting");

                        //! 如果用 PrintOn.FirstPage,咁就祇能用 [Page]
                        //((PageHeaderBand)report.Report.FindObject("PageHeader1")).PrintOn = PrintOn.FirstPage;              // PageHeader1 淨係喺第一頁出現,出 HTML 有用
                        ((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 report export to HTML
                        HTMLExport html = new HTMLExport();
                        html.SinglePage    = true;      //report on the one page
                        html.Navigator     = false;     //navigation panel on top
                        html.EmbedPictures = true;      //build in images to the document
                        html.Zoom          = 1.20F;     //design 嘅 font size 係以 A4 為主,喺 HTML 會太細,所以要放大 1.25 倍
                        report.Export(html, stream);    //export as HTML to stream

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

                        stream.Position = 0;
                        var reader = new StreamReader(stream);
                        result = reader.ReadToEnd();
                        #endregion

                        stream.Flush();
                    }
                }
                catch (Exception ex)
                {
                    //
                }
                finally
                {
                    stream.Dispose();
                }
            }

            return(result);
        }
示例#26
0
        internal StringBuilder ReportInHtml()
        {
            PictureCache.Clear();

            var sb = new StringBuilder();

            using (HTMLExport html = new HTMLExport())
            {
                html.ExportMode = HTMLExport.ExportType.WebPreview;
                //html.CustomDraw += this.CustomDraw;
                html.StylePrefix = $"fr{ID}";         //html.StylePrefix = Prop.ControlID.Substring(0, 6);
                html.Init_WebMode();
                html.Pictures        = Pictures;      //html.Pictures = Prop.Pictures;
                html.EmbedPictures   = EmbedPictures; //html.EmbedPictures = EmbedPictures;
                html.OnClickTemplate = "fr{0}.click(this,'{1}','{2}')";
                html.ReportID        = ID;            //html.ReportID = Prop.ControlID;
                html.EnableMargins   = EnableMargins; //html.EnableMargins = Prop.EnableMargins;

                // calc zoom
                //CalcHtmlZoom(html);
                html.Zoom = Zoom;

                html.Layers      = Layers;                                              //html.Layers = Layers;
                html.PageNumbers = SinglePage ? "" : (CurrentPageIndex + 1).ToString(); //html.PageNumbers = SinglePage ? "" : (Prop.CurrentPage + 1).ToString();

                //if (Prop.AutoWidth)
                //    html.WidthUnits = HtmlSizeUnits.Percent;
                //if (Prop.AutoHeight)
                //    html.HeightUnits = HtmlSizeUnits.Percent;

                //html.WebImagePrefix = WebUtils.ToUrl(FastReportGlobal.FastReportOptions.RouteBasePath, controller.RouteBasePath, ID, "picture") + "/"; //html.WebImagePrefix = String.Concat(context.Response.ApplyAppPathModifier(WebUtils.HandlerFileName), "?", WebUtils.PicsPrefix);
                html.WebImagePrefix = WebUtils.ToUrl(FastReportGlobal.FastReportOptions.RouteBasePath, $"preview.getPicture?reportId={ID}&pictureId=");
                html.SinglePage     = SinglePage;       //html.SinglePage = SinglePage;
                html.CurPage        = CurrentPageIndex; //html.CurPage = CurrentPage;
                html.Export(Report, (Stream)null);

                //sb.Append("<div class=\"frbody\" style =\"");
                //if (HtmlLayers)
                //    sb.Append("position:relative;z-index:0;");
                //sb.Append("\">");

                // container for html report body
                //int pageWidth = (int)Math.Ceiling(GetReportPageWidthInPixels() * html.Zoom);
                //int pageHeight = (int)Math.Ceiling(GetReportPageHeightInPixels() * html.Zoom);
                //int paddingLeft = (int)Math.Ceiling(Padding.Left * html.Zoom);
                //int paddingRight = (int)Math.Ceiling(Padding.Right * html.Zoom);
                //int paddingTop = (int)Math.Ceiling(Padding.Top * html.Zoom);
                //int paddingBottom = (int)Math.Ceiling(Padding.Bottom * html.Zoom);
                //sb.Append("<div class=\"frcontainer\" style=\"width:" + pageWidth +
                //    "px;height:" + (SinglePage ? pageHeight * html.Count : pageHeight) +
                //    "px;padding-left:" + paddingLeft +
                //    "px;padding-right:" + paddingRight +
                //    "px;padding-top:" + paddingTop +
                //    "px;padding-bottom:" + paddingBottom + "px\">");

                if (html.Count > 0)
                {
                    if (SinglePage)
                    {
                        DoAllHtmlPages(sb, html);
                        CurrentPageIndex = 0; //Prop.CurrentPage = 0;
                    }
                    else
                    {
                        DoHtmlPage(sb, html, 0);
                    }
                }

                //sb.Append("</div>");
                //sb.Append("</div>");

                // important container, it cuts off elements that are outside of the report page bounds
                int pageWidth  = (int)Math.Ceiling(GetReportPageWidthInPixels() * html.Zoom);
                int pageHeight = (int)Math.Ceiling(GetReportPageHeightInPixels() * html.Zoom);
                sb.Insert(0, $@"<div style=""width:{pageWidth}px;height:{(SinglePage ? pageHeight * html.Count : pageHeight)}px;overflow:hidden;display:inline-block;"">");
                sb.Append("</div>");
            }

            return(sb);
        }
        // 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));
            }
        }
示例#28
0
        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());
            }
        }
示例#29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MHTExport"/> class.
 /// </summary>
 public MHTExport()
 {
     htmlExport = new HTMLExport();
     Res        = new MyRes("Export,Mht");
 }
        // 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));
            }
        }
        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));
            }
        }