Example T569785
Visible to All Users

Reporting for ASP.NET MVC - How to print or export a report without showing a preview

This example demonstrates how to print or export a report in an ASP.NET MVC application without displaying this report's preview.

Report Print Dialog

Follow the steps below to print or export a report:

  • Call one of the report's ExportTo…  methods to obtain an exported document.
  • Call the Controller.File method to convert the exported document into a FileContentResult object.

Follow the steps below to print a report:

  • Export the report to PDF.
  • Return the exported PDF file as an action result with the Content-Disposition header set to inline.
  • The returned PDF is opened by the browser's built-in PDF viewer. To avoid this, export the PDF to a separate iframe - only the print dialog is displayed.

Files to Review

More Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)

Example Code

T569785/App_Start/FilterConfig.cs(vb)
C#
using System.Web; using System.Web.Mvc; namespace T569785 { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
T569785/App_Start/RouteConfig.cs(vb)
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace T569785 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
T569785/App_Start/WebApiConfig.cs(vb)
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace T569785 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
T569785/Controllers/HomeController.cs(vb)
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using T569785.Models; using DevExpress.XtraReports.UI; using T569785.Reports; using System.IO; using DevExpress.XtraPrinting; namespace T569785.Controllers { public class HomeController : Controller { // // GET: /Home/ private FileResult ExportDocument(byte[] document, string format, string fileName, bool isInline) { string contentType; string disposition = (isInline) ? "inline" : "attachment"; switch (format.ToLower()) { case "docx": contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break; case "xls": contentType = "application/vnd.ms-excel"; break; case "xlsx": contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; case "mht": contentType = "message/rfc822"; break; case "html": contentType = "text/html"; break; case "txt": case "csv": contentType = "text/plain"; break; case "png": contentType = "image/png"; break; default: contentType = String.Format("application/{0}", format); break; } Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}", disposition, fileName)); return File(document, contentType); } public ActionResult Index() { return View(new ExportModel() { Format = "pdf" }); } [HttpGet] public ActionResult Print() { XtraReport report = new ProductsReport(); using (MemoryStream ms = new MemoryStream()) { report.ExportToPdf(ms, new PdfExportOptions() { ShowPrintDialogOnOpen = true }); return ExportDocument(ms.ToArray(), "pdf", "Report.pdf", true); } } [HttpPost] public ActionResult Export(ExportModel model) { XtraReport report = new ProductsReport(); string fileName = String.Format("Report.{0}", model.Format); using (MemoryStream ms = new MemoryStream()) { switch (model.Format) { case "pdf": report.ExportToPdf(ms); break; case "docx": report.ExportToDocx(ms); break; case "xls": report.ExportToXls(ms); break; case "xlsx": report.ExportToXlsx(ms); break; case "rtf": report.ExportToRtf(ms); break; case "mht": report.ExportToMht(ms); break; case "html": report.ExportToHtml(ms); break; case "txt": report.ExportToText(ms); break; case "csv": report.ExportToCsv(ms); break; case "png": report.ExportToImage(ms, new ImageExportOptions() { Format = System.Drawing.Imaging.ImageFormat.Png }); break; } return ExportDocument(ms.ToArray(), model.Format, fileName, false); } } } }
T569785/Models/ExportModel.cs(vb)
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace T569785.Models { public class ExportModel { public string Format { get; set; } } }
T569785/Views/Home/Index.cshtml
Razor
@{ Layout = null; } @model T569785.Models.ExportModel <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script type="text/javascript"> function PrintWithiFrame() { window.open('@Url.Action("Print", "Home")', "PrintingFrame"); var frameElement = document.getElementById("FrameToPrint"); frameElement.addEventListener("load", function (e) { if (frameElement.contentDocument.contentType !== "text/html") frameElement.contentWindow.print(); }); } function PrintInNewWindow() { var frameElement = window.open('@Url.Action("Print", "Home")', "_blank"); frameElement.addEventListener("load", function (e) { if (frameElement.document.contentType !== "text/html") frameElement.print(); }); } </script> </head> <body> <div> @using (Html.BeginForm("Export", "Home")) { <table style="text-align: center; border-collapse: collapse"> <tr style="border-bottom: 1pt solid black"> <td style="width: 150px"> PDF-based Printing </td> <td style="width: 150px" colspan="2"> Exporting </td> </tr> <tr> <td width="500px"> <input type="button" value="Print With iFrame" onclick="PrintWithiFrame(); return false;" /> <br /> <b>Note:</b> Printing with an invisible iFrame element is not recommended. Although this solution provides more desktop-like experience, it's not guaranteed to work reliably across all browsers. For example, it won't work in the Edge or Safari browser. <br /> <br /> <input type="button" value="Print New Window" onclick="PrintInNewWindow(); return false;" /> <br /> <b>Note:</b> clicking this button will open a separate tab in the browser. This is the recommented approach. <iframe id="FrameToPrint" name="PrintingFrame" style="position:absolute; left: -10000px; top: -10000px;"></iframe> </td> <td style="vertical-align: top"> @Html.DropDownListFor(m => m.Format, new SelectListItem[] { new SelectListItem() { Value = "pdf", Text= "Pdf" }, new SelectListItem() { Value = "docx", Text= "Docx" }, new SelectListItem() { Value = "xls", Text= "Xls" }, new SelectListItem() { Value = "xlsx", Text= "Xlsx" }, new SelectListItem() { Value = "rtf", Text= "Rtf" }, new SelectListItem() { Value = "mht", Text= "Mht" }, new SelectListItem() { Value = "html", Text= "Html" }, new SelectListItem() { Value = "txt", Text= "Text" }, new SelectListItem() { Value = "csv", Text= "Csv" }, new SelectListItem() { Value = "png", Text= "Image" } }) </td> <td style="vertical-align: top"> <input type="submit" value="Export" /> </td> </tr> </table> } </div> </body> </html>

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.