Saturday, April 11, 2009

Convert a Crystal Report to PDF

This Code shows how to convert a Crystal Report to PDF Document.




'First Create a crystal Report.
' Drag and drop the Crystal Report Viewer in the form
' copy this code on top of the code
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Private myDS As New Dataset1() ' Dataset you created.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rpt As New CrystalReport1() 'The report you created.
Dim myConnection As SqlConnection
Dim MyCommand As New SqlCommand()
Dim myDA As New SqlDataAdapter()

Try

myConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;" & _
"Initial Catalog=pubs;")
MyCommand.Connection = myConnection
MyCommand.CommandText = "SELECT * FROM authors"
MyCommand.CommandType = CommandType.Text
myDA.SelectCommand = MyCommand

myDA.Fill(myDS, "authors")
rpt.SetDataSource(myDS)
CrystalReportViewer1.ReportSource = rpt

Catch Excep As Exception
MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub

' This code is used to convert crystal report to pdf
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

' Variable Declaration

Dim CrReport As New CrystalReport1() ' Report Name

Dim CrExportOptions As ExportOptions

Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()

Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()

' Set the destination path and file name
CrDiskFileDestinationOptions.DiskFileName = "d\RichText.pdf"

' Set the crystal report datasource to fill the dataset
CrReport.SetDataSource(myDS)


' Set export options

CrExportOptions = CrReport.ExportOptions



With CrExportOptions

' Set the destination to a disk file

.ExportDestinationType = ExportDestinationType.DiskFile

' Set the format to PDF

.ExportFormatType = ExportFormatType.PortableDocFormat

' Set the destination options to DiskFileDestinationOptions object

.DestinationOptions = CrDiskFileDestinationOptions

.FormatOptions = CrFormatTypeOptions



End With



' Trap any errors that occur on export

Try

' Export the report

CrReport.Export()

Catch err As Exception

MessageBox.Show(err.ToString())

End Try


End Sub

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home