Warning: Please consider that this post is over 13 years old and the content may no longer be relevant.
Need to generate a pdf programmatically in dot net? You could purchase an HTML to PDF converter and worry about getting the page to format nicely for paper, or you could use the freely available ReportViewer control from Microsoft.
Microsoft offers SQL Server Reporting Services (SSRS) with SQL Server 2005 and later editions to generate and publish reports using the Report Definition Language (RDL), as an alternative to Crystal Reports. SSRS requires a Report Server to publish reports to so they can be useful, however they also offer a ASP.Net or Windows Forms component called the ReportViewer which we can use in our code without the need for any SQL database to generate reports, and these reports can be saved as Excel files, PDF’s or images.
The ReportViewer uses a modified version of RDL called RDLC, which does not save any information about the data source along with the report, which makes it perfect for generating reports from objects that aren’t a database. For instance, I recently needed to generate PDF letters with custom information in them, so this solution proved perfect.
I’m going to demonstrate how to pass parameters to an ASP.Net page and return a PDF with that information in it, this could just as easily be done in a Windows Forms project. I’m using Visual Studio 2005, in my preferred language of c#.
Start by creating a new Web Site in Visual Studio. We are going to use a collection of custom business objects as the data source for our report, so add a new class to our project and call it Person.cs. Copy the following code into your Person.cs file.
Now that we have our business object we can create the report. Click add item on the project and select Report. Call this item Report.rdlc.
In the left hand toolbar you should see Website Data Sources (if not select Data > Show Data Sources from the file menu) and in the data sources you should see our Person object. You can now build a report using the fields from our person object and the tools in the toobox. For simplicity just drag some Textboxes onto the report from the toolbox and enter any static text in them that you want, then drag on the Person’s title, firstName and lastName and arrange them appropriately.
Finally we need to write the code which will create the person data source and generate the report. Before we do this we need a reference to the ReportViewer control, right click on the project and Add Reference, in the .Net tab, select Microsoft.ReportViewer.WebForms.Now copy the following code into the Default.aspx source.
And copy the following into the Code View of Default.aspx (Default.aspx.cs).
Now run your project, enter some person data into the form and click submit. Open the PDF file and verify that the report is addressed to your person.