To export crystal report to pdf, excel or any supported file and then email it using VB.NET, follow these steps:
1. Include the following namespaces on your Imports directive.
'For exporting and sending PDF to client
Imports CrystalDecisions.ReportSource
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
'For Sending Email
Imports System.Net.Mail
Imports System.Text
Imports System.Text.RegularExpressions
2. To Export Crystal Report use the following codes:
'Login to database
Dim LogInfo As New TableLogOnInfo()
LogInfo.ConnectionInfo.ServerName = "server"
LogInfo.ConnectionInfo.DatabaseName = "database"
LogInfo.ConnectionInfo.UserID = "username"
LogInfo.ConnectionInfo.Password = "password"
'Load Report
Dim oReport As New ReportDocument
oReport.Load( "C:\rptsample.rpt") 'Set Parameters
oReport.SetParameterValue("Parameter1", "Test Parameter 1")
oReport.SetParameterValue("Parameter2", "Test Parameter 2")
Dim lFileName As String = "C:\exportedfile.pdf"
'Export to disk as PDF file
oReport.ExportToDisk(ExportFormatType.PortableDocFormat, lFileName)
3. Then email the exported file using the MailMessage class as shown below.
'Send Email
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("youremail@company.com")
'Lets assume that txtEmail textbox contains multiple emails separated by comma
Dim strEmails() As String = txtEmail.Text.Split(",")
For Each str As String In strEmails
If IsValidEmail(str) Then
mail.To.Add(str)
End If
Next
'set the content
mail.Subject = "Your subject"
mail.Body = "Your Message"
'attach exported pdf
Dim att As New Attachment(lFileName)
mail.Attachments.Add(att)
'send the message
Dim smtp As New SmtpClient("127.0.0.1") 'SMTP Server
smtp.Send(mail)
For more VB.NET coding tips, subscribe now
3 comments:
Thank you so much for this article. All I wanted to do is export a report to PDF without actually opening the report in the viewer. Your code is simple and concise and doesn't do anything other than what I wanted. I appreciate your separating the email portion as well because I didn't need it. Thank you so much!!!
Thank you very much EXCELLENT POST!! Worked right away! =D
Could you tell me how can I delete the recently exported PDFs just after beign created? Thank You =D
Post a Comment