Introduction
The following tip will guide you to create a custom printing functionality to print RDLC report rather than using the built in ActiveX print functionality.
Background
There is a major problem in print button on Microsoft Report Viewer. Once you deploy a web application, Client needs to install the ActiveX on their PC in order to print the report. It is said that installing ActiveX is not a secure practice on secured environment. The worst part is when the server/client is on automatic update, there is a security patch which disables the printing functionality completely.
Read more about ActiveX Kill Bits here.
Because of the above reasons, it is wise to have your own printing functionality rather than using the built-in one.
Using the Code
You need to download the third party component called iTextSharp.dll.
You need to export the report to PDF, then print using iTextSharp. Also client needs to install the PDF reader as well.
- Create hidden
iFrame
as follows:
<iframe id="frmPrint" name="IframeName" width="500"
height="200" runat="server"
style="display: none" runat="server"></iframe>
- Add an ASP.NET button:
<asp:ImageButton ID="btnPrint" runat="server" OnClick="btnPrint_Click" />
- Add the following references:
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
- Add the following code to button click event:
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = View.ReportViewer.LocalReport.Render("PDF", null, out mimeType,
out encoding, out extension, out streamids, out warnings);
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"),
FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
Document document = new Document(PageSize.LETTER);
PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
int i = 0;
int p = 0;
int n = reader.NumberOfPages;
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
while (i < n)
{
document.NewPage();
p++;
i++;
PdfImportedPage page1 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page1, 0, 0);
}
PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
writer.AddJavaScript(jAction);
document.Close();
frmPrint.Attributes["src"] = "Print.pdf";
Points of Interest
You may need to add read/write permission on the folder where the PDF is created on the server.
History
- May 01, 2012: Article created