Hi bhushan98,
Here i have created a sample for download Crystal Report with digitally signature to PDF.
Crystal Reports does not have built-in support for directly applying digital signatures during the export process.
So you need to export the report to PDF file and add digital signature to the PDF using any thirt party tool.
Here i am making use of ITextSharp library.
For more details on exporting Crystal report, please refer Export Crystal Report to PDF programmatically in ASP.Net.
Report Design
For this example i have saved the digitally signed certificate i.e. MySignature.pfx in the project folder.
Install Itextsharp package
Use the following command to install the Itextsharp package.
Install-Package iTextSharp -Version 5.5.13.3
HTML
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
<br />
<asp:Button ID="btnExport" Text="Export" runat="server" OnClick="Export" />
Namespaces
Inherit the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.IO
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.security
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Pkcs
Code
C#
ReportDocument crystalReport;
protected void Page_Load(object sender, EventArgs e)
{
crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/CustomerReport.rpt"));
Customers dsCustomers = GetData("SELECT TOP 10 * FROM Customers");
crystalReport.Database.Tables[0].SetDataSource(dsCustomers.Tables["Table"]);
CrystalReportViewer1.ReportSource = crystalReport;
}
protected void Export(object sender, EventArgs e)
{
// Export Crystal Report to Stream.
Stream stream = crystalReport.ExportToStream(ExportFormatType.PortableDocFormat);
using (MemoryStream ms = new MemoryStream())
{
// Read the Exported PDF.
using (PdfReader pdfReader = new PdfReader(stream))
{
// Initialize the PDF Stamper and Creating the Signature Appearance.
using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, ms, '\0', null, true))
{
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
//signatureAppearance.Reason = "";
signatureAppearance.Location = "Mumbai";
// Set signature location.
float x = 200;
float y = 200;
signatureAppearance.Acro6Layers = false;
signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark;
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), 1, "signature");
// Load Digital Certificate(PFX).
string pfxFilePath = Server.MapPath("~/MySignature.pfx");
// Password of Digital Certificate(PFX).
string pfxPassword = "12345";
Pkcs12Store pfxKeyStore = new Pkcs12Store(new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read), pfxPassword.ToCharArray());
// Sign the Document.
string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(entryAlias => pfxKeyStore.IsKeyEntry(entryAlias));
if (alias != null)
{
ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;
IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);
MakeSignature.SignDetached(signatureAppearance, pks, new Org.BouncyCastle.X509.X509Certificate[]
{
pfxKeyStore.GetCertificate(alias).Certificate
}, null, null, null, 0, CryptoStandard.CMS);
}
// Save the Signed PDF.
pdfStamper.Close();
}
}
// Download the Digitally signed PDF.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.BinaryWrite(ms.ToArray());
Response.Flush();
Response.End();
}
}
private Customers GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection())
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, conString))
{
using (Customers dsCustomers = new Customers())
{
sda.Fill(dsCustomers);
return dsCustomers;
}
}
}
}
VB.Net
Private crystalReport As ReportDocument
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
crystalReport = New ReportDocument()
crystalReport.Load(Server.MapPath("~/CustomerReport.rpt"))
Dim dsCustomers As Customers = GetData("SELECT TOP 10 * FROM Customers")
crystalReport.Database.Tables(0).SetDataSource(dsCustomers.Tables("Table"))
CrystalReportViewer1.ReportSource = crystalReport
End Sub
Protected Sub Export(sender As Object, e As EventArgs)
' Export Crystal Report to Stream.
Dim stream As Stream = crystalReport.ExportToStream(ExportFormatType.PortableDocFormat)
Using ms As MemoryStream = New MemoryStream()
' Read the Exported PDF.
Using pdfReader As PdfReader = New PdfReader(stream)
' Initialize the PDF Stamper and Creating the Signature Appearance.
Using pdfStamper As PdfStamper = PdfStamper.CreateSignature(pdfReader, ms, ChrW(0), Nothing, True)
Dim signatureAppearance As PdfSignatureAppearance = pdfStamper.SignatureAppearance
'signatureAppearance.Reason = "";
signatureAppearance.Location = "Mumbai"
' Set signature location.
Dim x As Single = 200
Dim y As Single = 200
signatureAppearance.Acro6Layers = False
signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark
signatureAppearance.SetVisibleSignature(New iTextSharp.text.Rectangle(x, y, x + 150, y + 50), 1, "signature")
' Load Digital Certificate(PFX).
Dim pfxFilePath As String = Server.MapPath("~/MySignature.pfx")
' Password of Digital Certificate(PFX).
Dim pfxPassword = "12345"
Dim pfxKeyStore As Pkcs12Store = New Pkcs12Store(New FileStream(pfxFilePath, FileMode.Open, FileAccess.Read), pfxPassword.ToCharArray())
' Sign the Document.
Dim [alias] As String = pfxKeyStore.Aliases.Cast(Of String)().FirstOrDefault(Function(entryAlias) pfxKeyStore.IsKeyEntry(entryAlias))
If Not Equals([alias], Nothing) Then
Dim privateKey As ICipherParameters = pfxKeyStore.GetKey([alias]).Key
Dim pks As IExternalSignature = New PrivateKeySignature(privateKey, DigestAlgorithms.SHA256)
MakeSignature.SignDetached(signatureAppearance, pks, New Org.BouncyCastle.X509.X509Certificate() {pfxKeyStore.GetCertificate([alias]).Certificate}, Nothing, Nothing, Nothing, 0, CryptoStandard.CMS)
End If
' Save the Signed PDF.
pdfStamper.Close()
End Using
End Using
' Download the Digitally signed PDF.
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "attachment; filename=Report.pdf")
Response.BinaryWrite(ms.ToArray())
Response.Flush()
Response.End()
End Using
End Sub
Private Function GetData(query As String) As Customers
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection()
Using sda As SqlDataAdapter = New SqlDataAdapter(query, conString)
Using dsCustomers As Customers = New Customers()
sda.Fill(dsCustomers)
Return dsCustomers
End Using
End Using
End Using
End Function
Screenshots
Crystal report with Export Button
Exported PDF with signature