Create a PDF file from a Crystal Report in Asp.Net C# and Vb.Net

← PrevNext →

A Portable Document Format (PDF) file is useful for sharing data on the web and has many useful features that make it an ideal choice for making documents. Here in this article I am going to show you with an example on how to create a PDF file from a Crystal Report in Asp.Net.

Generating a PDF file or exporting data into a PDF file from a Crystal report is not a difficult task, since this feature is readily available in Asp.Net. We just need to dig it out.

Crystal Report’s ExportToStream() function can export a pre-designed report into various file formats and its ExportToDisk() function can export the entire formatted data into a file.

However, in this article, I’ll show the use of Crystal Report ExportToDisk() function, which will allow you to convert the report into a PDF file and save it in a folder. Later, you can email or print the PDF file.

Create PDF using Crystal report

I am assuming that you have read my previous article on How to create Crystal Report in Asp.Net?. This article is very important, as it will help you understand the basics of creating and embedding a Crystal Report in your Asp.Net project. I am using the same procedure in this article too.

Once you have created a project with the Crystal report, just write another function called CreatePDF(), which will create a PDF file using the data extracted from an SQL Server table.

The Markup

Add a button to your web page and name it Create PDF. The click event of the button control will call the code behind function to create the PDF file.

<div>
    <asp:Button Text="Create PDF" ID="btPDF" OnClick="btPDF_Click" runat="server" />
</div>
Code Behind (C#)

Before writing your code for creating the PDF file, set the connection string in the Web.Config file. If you wish, you can define the connection string in a Class or a Module.

<connectionStrings>
    <add name="DNA_DB" connectionString="Data Source=dna;Persist Security Info=False;
    Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;"/>
</connectionStrings>

Also, add few crystal report references to your project. To add references, click Website from the top menu select Add Reference… menu. In the “.Net” tab search for,

01) CrystalDecisions.CrystalReports.Engine
02) CrystalDecisions.Shared

using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;                  // FOR DataSet().
using CrystalDecisions.Shared;      // FOR ExportFormatType.

public partial class _Default : System.Web.UI.Page 
{
    // CONNECTION PROPERTIES.
    SqlConnection myConn = default(SqlConnection);
    SqlCommand sqComm = default(SqlCommand);

    public CrystalDecisions.CrystalReports.Engine.ReportDocument Report = 
        new CrystalDecisions.CrystalReports.Engine.ReportDocument();

    protected void btPDF_Click(object sender, EventArgs e)
    {
        if (setConn())
        {
            string sQuery = "SELECT *FROM dbo.Employee";
            CreatePDF(sQuery, "Employee.rpt", "Employee");
        }
    }

    private bool CreatePDF(string sQuery, string rptFileName, string sTableName)
    {
        System.Data.SqlClient.SqlDataAdapter objDataAdapter = 
            new System.Data.SqlClient.SqlDataAdapter(sQuery, myConn);

        DataSet objDataSet = new DataSet()>;
        objDataAdapter.SelectCommand.CommandTimeout = 100;
        objDataAdapter.Fill(objDataSet, sTableName);

        Report.Load(Server.MapPath("report\\") + rptFileName);
        Report.SetDataSource(objDataSet);                  // SET REPORT DATA SOURCE.

        // FINALLY, CREATE THE PDF FILE USING EMPLOYEE DETAILS.
        Report.ExportToDisk(ExportFormatType.PortableDocFormat, 
            Server.MapPath("Crystal-to-PDF\\EmployeeDetails.pdf"));

        return true;
   }

    private bool setConn()
    {
        // SET DATABASE CONNECTION.
        try
        {
            myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DNA_DB"].ConnectionString);
            myConn.Open();

            sqComm = new SqlCommand();
            sqComm.Connection = myConn;
        }
        catch (Exception ex) { return false; }
        return true;
    }
}

The clicking of the button control on the web page, will call the function CreatePDF(), which accepts three parameters.

01) sQuery: The SQL query that will fetch the details from the “Employee” table.
02) rtpFileName: The Crystal Report file which we have designed earlier. This is the file which will be converted into PDF.
03) sTableName: The name of the DataSet, which will hold the SQL Server table’s data for designing the report.

Vb.Net
Option Explicit On

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports CrystalDecisions.Shared     'FOR ExportFormatType.

Partial Class _Default
    Inherits System.Web.UI.Page

    ' CONNECTION PROPERTIES.
    Dim myConn As SqlConnection
    Dim sqComm As SqlCommand

    Public Report As CrystalDecisions.CrystalReports.Engine.ReportDocument = New CrystalDecisions.CrystalReports.Engine.ReportDocument

    Protected Sub btPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
        If setConn() Then
            Dim sSql As String = "SELECT *FROM dbo.Employee"

            CreatePDF(sSql, "Employee.rpt", "Employee")
        End If
    End Sub

    Private Function CreatePDF(ByVal sQuery As String, ByVal rptFileName As String, ByVal sTableName As String) As Boolean
        Try
            Dim objDataAdapter As New System.Data.SqlClient.SqlDataAdapter(sQuery, myConn)
            Dim objDataSet As New DataSet
            objDataAdapter.SelectCommand.CommandTimeout = 500
            objDataAdapter.Fill(objDataSet, sTableName)

            Report.Load(System.AppDomain.CurrentDomain.BaseDirectory() & "report\" & rptFileName & "")
            Report.SetDataSource(objDataSet)                    ' SET REPORT DATA SOURCE.

            ' FINALLY, CREATE THE PDF FILE USING EMPLOYEE DETAILS.
            Report.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("Crystal-to-PDF\EmployeeDetails.pdf"))

            CreatePDF = True
            
        Catch ex As Exception
            CreatePDF = False
        Finally
        End Try
    End Function

    ' SET DATABASE CONNECTION.
    Private Function setConn() As Boolean
        Try
            myConn = New SqlConnection(ConfigurationManager.ConnectionStrings("DNA_DB").ConnectionString)
            myConn.Open()

            sqComm = New SqlCommand
        Catch ex As Exception
            Return False
        End Try

        Return True
    End Function
End Class
Conclusion

The PDF format is one possibility, which we have explored in this article. You must also try using other available formats to export data from Crystal report, other than the PDF format. Hope you have enjoyed and learned from the article and demo.

Other Formats

Thank's for reading. 🙂

← PreviousNext →