Print RDLC Report Directly To Printer In MVC

Article Overview

  • Background
  • Prerequisites
  • How to print rdlc report directly to printer in MVC
  • Complete example
  • Output
  • Summary

Background

 
There was a situation where I had to render an rdlc report into a MVC application and directly open it to the print dialog box.
 
Hence, I have created an rdlc report in MVC and rendered that report as bytes using ReportViewer and saved it to pdf file. I have used PdfReader and added JavaScript to pdf file through PdfStamper for the mozilla browser issue. After that, I opened a print dialog using JavaScript.
 
Here, I have kept all the implementation details along with a complete example.
 
Prerequisites
  • You should have a basic knowledge of RDLC report implementation as well as MVC applications. 
  • Reference of "Microsoft.ReportViewer.WebForms" and "iTextSharp"

How to print rdlc report directly to printer in MVC

 
There are mainly four key steps to implement this:
  • Create rdlc report in MVC
  • Use ReportViewer and render as bytes
  • Create pdf file using PdfReader and add JavaScript to pdf file through PdfStamper
  • Open Print dialog using JavaScript
Now, let us see in detail.
 
Create rdlc report
 
Our first task is to add and create a report file into the project.
 
First, create a MVC project.
 
Second, add new RDLC report by “Add New Item” => “Visual C#” => “Report” selection.
 
Print RDLC Report Directly To Printer In MVC 
 
Third, design report. To make it easy to understand I have created one simple static report without any database connection just for simplicity.
 
Print RDLC Report Directly To Printer In MVC 
 
User ReportViewer and render as bytes
 
Now, our second task is to use (consume) report into the C# (code).
 
First, add “Microsoft.ReportViewer.WebForms” reference into the project.

Print RDLC Report Directly To Printer In MVC
 
Second, add “Microsoft.ReportViewer.WebForms” namespace.
  1. using Microsoft.Reporting.WebForms; 
Third, write code and set report path.
  1. reportViewer.LocalReport.ReportPath = Server.MapPath(@"~\Report1.rdlc"); 
Create pdf file using PdfReader and add JavaScript to pdf file through PdfStamper
 
Now, we have to render (convert) the report into bytes and save it as a pdf file along with some JavaScript settings like the following:

First, render report into bytes.
  1. Warning[] warnings;  
  2. string[] streamids;  
  3. string mimeType, encoding, filenameExtension;  
  4.   
  5. byte[] bytes = reportViewer.LocalReport.Render("Pdf"nullout mimeType, out encoding, out filenameExtension, out streamids, out warnings); 
Second, add iTextShart using NuGet to save pdf file and add some properties to that pdf file as described below.
 
Print RDLC Report Directly To Printer In MVC 
  1. //File  
  2. string FileName = "Test_" + DateTime.Now.Ticks.ToString() + ".pdf";  
  3. string FilePath = HttpContext.Server.MapPath(@"~\TempFiles\") + FileName;  
  4.   
  5. //create and set PdfReader  
  6. PdfReader reader = new PdfReader(bytes);  
  7. FileStream output = new FileStream(FilePath, FileMode.Create);  
  8.   
  9. string Agent = HttpContext.Request.Headers["User-Agent"].ToString();  
  10.   
  11. //create and set PdfStamper  
  12. PdfStamper pdfStamper = new PdfStamper(reader, output, '0'true);  
  13.   
  14. if (Agent.Contains("Firefox"))  
  15.     pdfStamper.JavaScript = "var res = app.loaded('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);');";  
  16. else  
  17.     pdfStamper.JavaScript = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', 200);";  
  18.   
  19. pdfStamper.FormFlattening = false;  
  20. pdfStamper.Close();  
  21. reader.Close(); 
Here, PdfStamper is being used to add JavaScript so that print popup will open especially for FireFox web browser.

Third, return created pdf file’s path.
  1. //return file path  
  2. string FilePathReturn = @"TempFiles/" + FileName;  
  3. return Content(FilePathReturn); 
Note, that here I am creating a pdf file and storing it into the “TempFiles” folder location.
 
Open Print dialog
 
Now, our last task is to open a file into the print dialog.
 
First, place a placeholder for pdf to show.
  1. <div id="divPDF">  
  2.     <div id="printerDiv"><iframe id="frmPDF"></iframe></div>  
  3. </div> 
Second, assign pdf and call print option from JavaScript.
  1. $('#frmPDF').attr('src''@Url.Content("~/")' + result);  
  2. setTimeout(function () {  
  3.     frame = document.getElementById("frmPDF");  
  4.     framedoc = frame.contentWindow;  
  5.     framedoc.focus();  
  6.     framedoc.print();  
  7. }, 1000); 
That’s it.
 

Complete example

 
For your reference, I have kept the complete example in a single folder and uploaded that with this article and it contains the below files:
  • Index.cshtml (View)
  • HomeController.cs (Controller)
  • Report1.rdlc (Report)
  • TempFiles (Folder to store created pdf file)
Complete code is like the following:
 
View (Index.cshtml)
  1. <style>  
  2.     #printerDiv iframe { position: absolute; top: -1000px; }  
  3. </style>  
  4. <div class="jumbotron">  
  5.     <button onclick="funExportToPDF()">Export to PDF</button>  
  6. </div>  
  7.   
  8. <div id="divPDF">  
  9.     <div id="printerDiv"><iframe id="frmPDF"></iframe></div>  
  10. </div>  
  11.   
  12. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>  
  13.   
  14. <script type="text/javascript">  
  15.   
  16.     function funExportToPDF() {  
  17.   
  18.         $.ajax({  
  19.             url: '@Url.Action("ExportToPDF", "Home")',  
  20.             type: 'GET',  
  21.             contentType: 'application/json; charset=utf-8',  
  22.             success: function (result) {  
  23.   
  24.                 $('#frmPDF').attr('src', '@Url.Content("~/")' + result);  
  25.   
  26.                 setTimeout(function () {  
  27.                     frame = document.getElementById("frmPDF");  
  28.                     frameframedoc = frame.contentWindow;  
  29.                     framedoc.focus();  
  30.                     framedoc.print();  
  31.                 }, 1000);  
  32.             },  
  33.             error: function (xhr, status, err) {  
  34.                 alert(err);  
  35.             }  
  36.         });  
  37.   
  38.         return false;  
  39.     }  
  40.   
  41. </script>  
Controller (HomeController.cs)
  1. public ActionResult ExportToPDF()  
  2. {  
  3.     //Report  
  4.     ReportViewer reportViewer = new ReportViewer();  
  5.   
  6.     reportViewer.ProcessingMode = ProcessingMode.Local;  
  7.     reportViewer.LocalReport.ReportPath = Server.MapPath(@"~\Report1.rdlc");  
  8.   
  9.     //Byte  
  10.     Warning[] warnings;  
  11.     string[] streamids;  
  12.     string mimeType, encoding, filenameExtension;  
  13.   
  14.     byte[] bytes = reportViewer.LocalReport.Render("Pdf"nullout mimeType, out encoding, out filenameExtension, out streamids, out warnings);  
  15.   
  16.     //File  
  17.     string FileName = "Test_" + DateTime.Now.Ticks.ToString() + ".pdf";  
  18.     string FilePath = HttpContext.Server.MapPath(@"~\TempFiles\") + FileName;  
  19.   
  20.     //create and set PdfReader  
  21.     PdfReader reader = new PdfReader(bytes);  
  22.     FileStream output = new FileStream(FilePath, FileMode.Create);  
  23.   
  24.     string Agent = HttpContext.Request.Headers["User-Agent"].ToString();  
  25.   
  26.     //create and set PdfStamper  
  27.     PdfStamper pdfStamper = new PdfStamper(reader, output, '0'true);  
  28.   
  29.     if (Agent.Contains("Firefox"))  
  30.         pdfStamper.JavaScript = "var res = app.loaded('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);');";  
  31.     else  
  32.         pdfStamper.JavaScript = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', 200);";  
  33.   
  34.     pdfStamper.FormFlattening = false;  
  35.     pdfStamper.Close();  
  36.     reader.Close();  
  37.   
  38.     //return file path  
  39.     string FilePathReturn = @"TempFiles/" + FileName;  
  40.     return Content(FilePathReturn);  

Output

 
The output will be like following in Chrome browser after clicking on "Export to PDF" button:
 
Print RDLC Report Directly To Printer In MVC 
 

Summary

 
Now, I believe you will be able to print rdlc reports directly to the printer in MVC.