How to export crystal report as PDF through C# code?
In this article I am explain in detail about Export crystal report as PDF using C# code. This code is usually needed for all developers to export crystal report data as pdf without showing crystal report in web page. This one is simple code to implement in your project easily.
Description
We can export data from grid view to PDF using some third party dll. But In this resource I have explained how to export crystal report data as pdf. For example we are designed crystal report with company logo and some picture etc. we like to export that crystal report all data as PDF in single button click without seeing crystal report. For this requirement I write code here in simple method.Table structure
I have create one table to store user details
create table reg(ID int identity(1,1),Name varchar(50),email varchar(75),pwd varchar(10),desig varchar(50),Newsletter varchar(1))Default.aspx
In this page I created one registration form to collect user details and save in the database
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>New User Registration</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="700">
<tr>
<td height="40" colspan="2">
<b>New User Registration</b>
</td>
</tr>
<tr>
<td height="40" colspan="2" align="center">
<asp:Label ID="Label1" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td height="30" align="left" width="50%">
Name
</td>
<td height="30">
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30" align="left">
Login Email Id
</td>
<td height="30">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30" align="left">
Login Password
</td>
<td height="30">
<asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30" align="left">
Designation
</td>
<td height="30">
<asp:TextBox ID="txtDesig" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="40" colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>Default : Server side code behind
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
//Get Connection string from web.config file
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string newsletter;
try
{
//Open sql connection
sqlcon.Open();
//Insert data from web page control to database
sqlcmd=new SqlCommand("insert into reg(Name,email,pwd,desig) values('" + txtname.Text + "','" + txtEmail.Text + "','" + txtpwd.Text + "','" + txtDesig.Text +"')",sqlcon);
sqlcmd.ExecuteNonQuery();
Label1.Text="Record insert successfully";
//Clear all controls after save it
clear();
}
catch (Exception ex)
{
}
finally
{
//Close connection
sqlcon.Close();
}
}
void clear()
{
foreach (Control c in form1.Controls) //This loop takes all controls from the form1
{
//Clear all textbox values
if (c is TextBox)
((TextBox)c).Text = "";
//clear all check boxes
if (c is CheckBox)
((CheckBox)c).Checked = false;
//Clear all radio buttons
if (c is RadioButton)
((RadioButton)c).Checked = false;
}
}
}Design Crystal report
Create your crystal report with logo and company name etc. like belowDefault2: Client side
In this page I have placed one textbox, button control and crystal report viewer.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Display Records in crystal report</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="700">
<tr>
<td height="40" colspan="2">
<b>Display Record details</b>
</td>
</tr>
<tr>
<td height="30">
Enter User Name
</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="40" colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Export PDF"
onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td height="400" colspan="2" align="center" valign="top">
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Design look like this
If user enter name in that textbox then click export to pdf button directly create pdf file In the web page.Default2: Server side
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
using CrystalDecisions.ReportSource;
using System.IO;
using System.Net;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string query;
sqlcon.Open();
query = "select * from reg where name like '%" + txtName.Text + "%'";
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
string fname = DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + ".pdf";
//Create instance for crystal report Export option class
ExportOptions exprtopt = default(ExportOptions);
//create instance for destination option - This one is used to set path of your pdf file save
DiskFileDestinationOptions destiopt = new DiskFileDestinationOptions();
//Bind data in the crystal report first before export cystal report to PDF
ReportDocument RptDoc = new ReportDocument();
//Map your crystal report path
RptDoc.Load(Server.MapPath("~/CrystalReport.rpt"));
//Set your crystal report datasource as dt
RptDoc.SetDataSource(dt);
//Get path and assign into destination DiskFileName
destiopt.DiskFileName = Server.MapPath(fname);
exprtopt = RptDoc.ExportOptions;
exprtopt.ExportDestinationType = ExportDestinationType.DiskFile;
//use PortableDocFormat for PDF data
exprtopt.ExportFormatType = ExportFormatType.PortableDocFormat;
exprtopt.DestinationOptions = destiopt;
//finally export your report document
RptDoc.Export();
//To open your PDF after save it from crystal report
string Path = Server.MapPath(fname);
//create instance to client to open your pdf
WebClient client = new WebClient();
//Assign path to download pdf
Byte[] buffer = client.DownloadData(Path);
//metion content type as PDF and write
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
}Output
After user click export to PDF button the PDF created based on the Crystal report content like below.
Source Code Detail:
I have attached source code of crystal report export download it and try to export crystal report as pdf
Front End : ASP.NET
Code Behind : C#
Conclusion:
I hope this article help to Crystal report export from code behind C# code.