Wednesday, July 29, 2009

Outputting Crystal Reports to PDF

A recent project at work called for outputting an HTML formatted document from a database directly to PDF. During some initial testing, I tried using Crystal Reports to accomplish this. Though it did not work (my version of Crystal Reports had extremely limited support for rendering HTML in a report field) , I did find out how to export a report directly to PDF without the need of a report control.

Firstly, add the imports:

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared


Then, create a ReportDocument instance and point it to your report (.rpt) file.

Dim rptFilePath As String = Server.MapPath(REPORTPATH)
Dim rptDoc As New ReportDocument
rptDoc.Load(rptFilePath)
rptDoc.SetDataSource(ds)

Use the ReportDocument ExportToHttpResponse method to send your report directly to PDF.

Response.Buffer = False
Response.ClearContent()
Response.ClearHeaders()
rptDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, True, "contract")