Click here to Skip to main content
Click here to Skip to main content

Create data driven PDF on the fly by using SQL server reporting service (SSRS)

By , 17 Jun 2007
 

Screenshot - pdf_webapp.jpg

Screenshot - pdf_result1.jpg

Introduction

The example is a web application, accepting the user input text and creating a data driven PDF on the fly. The web application programmatically calls the SQL server reporting service (SSRS)'s web service to do the trick.

Background

Basically there are 4 approaches for the SSRS data driven report rendering:

  1. End user triggers report through SSRS built-in UI (the report viewer)
  2. End user triggers report through a pre-built URL. This URL will trigger the SSRS to render report
  3. SSRS scheduled job will render reports on schedule
  4. Programmer calls the SSRS web service to render report programmatically

This article uses approach #4. By calling the web service, the programmer gains the most control out of SSRS and can do more with less restrictions (if used properly).

You can use the same idea to create your own Excel spreadsheet or CSV files on the fly.

If you don't have SSRS development environment, I suggest you try my live demo first. To install the whole environment locally from scratch is not a trivial task.

This article assumes the reader already knows:

  • how to install and use SSRS
  • how to author and publish a SSRS report template (RDL file)
  • how to use C# to call a web service

Free, mean and lean

If you just want a pure report engine for not-too-heavy-duty usage, you don't have to buy SQL server standard edition (means thousands of dollars in license fee). SQL server express edition is totally free and can do most SSRS functions.

Some limitations you need to keep in mind when you use SSRS express edition:

  1. Scheduled reporting
    SSRS needs SQL server job scheduler to do scheduled reporting, current express edition doesn't have this function.
  2. Scale to multiple CPUs
    At present, SQL server express edition can only utilize one CPU.

The example code was tested on a XP Pro SP2 PC and Windows 2003 server SP1 with SQL server express edition 2005.

Using the code

The source code was tested on a PC:

  • Windows XP Pro SP2
  • .NET 2.0 framework
  • Visual Studio 2005
  • Business Intelligence Template (for SSRS authoring)
  • SQL server express edition 2005 with advanced services SP2 (download from Microsoft)
  • IIS 5.1 (comes with XP pro)

(If you just want see how it goes, you can try my live demo here)

Before you test the example code, you need to make sure that your SSRS and web service is configured properly.

Screenshot - pdf_ssrscfg.jpg

The above screenshot is the SSRS configuration screen. "green" indicator means proper configuration of the entry.

Now you can compile and deploy the two source projects on your local PC:

  1. PdfReport.zip is the RDL template to author the sample PDF report
    • Deploy the report (pdf01.rdl) to your local PC (http://localhost/reportserver)
    • To make things easier, pdf01.rdl doesn't have any data source
    • To demo data-driven, I put one report parameter (user input) and five "real-time" yahoo stock charts (To make things more interesting, I used MSFT, SUNW, IBM, GOOG, ORCL)
  2. RsPdf.zip is the web application calling the SSRS's web service to create real PDF from pdf01.rdl template. (In the example solution file, I already added the web reference WSDL file which refers to http://localhost/ReportServer/ReportExecution2005.asmx)

Security tips

You can see the code below right before the SSRS rendering:

rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;

Because you are using local PC to do the test, I also assume that you as a programmer always login local PC as a local admin, so the default credentials are powerful enough to call the local SSRS web service.

In case you are deploying the same function to a public server like my live demo, you might want to do the following steps before your code can run properly.

  1. Create a local user (e.g. user1234) in your server or you can also create an active directory domain user
  2. Make sure this user is in SQLServer2005ReportingServicesWebServiceUser local user group (This user group is created when you install and configure SSRS)
  3. Login to http://YourPublicServerURL/reports
  4. Click "edit" button of your report entry (pdf01 in this example)
  5. Add the newly created local user (or AD user) to the security tab of this report template (pdf01 in this example)
  6. Use the following code before the SSRS rendering:

    rsExec.Credentials = new NetworkCredential
                        ("user1234", "password", "domain");

If user1234 is an AD user, "domain" is the AD domain; If it is just a local user, leave it as blank "".

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Simon Pang
Software Developer
Canada Canada
a believer of "One app worths thousand words" and a business application developer in Toronto Canada.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey16-Apr-12 19:19 
Nice
AnswerRe: Passing the report a parameter.memberSimon Pang5-Aug-11 9:23 
Hi,
The example does accept one user input parameter to the PDF. (the top green text in the PDF is a user input parameter from UI)
 
If you want to see the latest example and source code, I also have an updated article in codeproject
here

GeneralMy vote of 5memberTwisted Highway12-Apr-11 5:52 
Nice piece of work. I checked out your blog on this too and that worked perfect with very few lines of code. One thing I found was the images don't display from SQL Rpt Svc 2010 otherwise is works.
GeneralPDF Report from SQL query - explain paginationmemberThebldr21-Aug-10 4:49 
I would like to know how PDF pages can be created using large results of SQL query.
 
Thanks,
 
A. Samuel
Glory to him, for the things he has done.

GeneralError In PDFmemberMember 434380930-Jun-10 0:00 
Hi dude,
 
I tried to run the report in LIVE DEMO. I am unable to get the PDF file instead of i am getting Error message. Please try to resolve it.
GeneralFilter Data in GridviewmemberS Banik24-Oct-09 2:42 
I am designing an Employee Master Web Page. For it, I have a Drop Down List in which different different will displayed. Now I am want that when I select any particular department, the details employee records against that department will displayed in the Grid View Control.
GeneralCapture PDF file to emailmemberMember 13834205-Oct-09 4:12 
Is it possible to not just render the PDF file, but capture it somehow so it can be emailed?
 
I need to be able to allow a user to indicate they want to release a batch of invoices, and get the parameters from an SQL table, then email to proper supplier.
 
I tried using a shared schedule to do this, but i need the user to indicate when invoices are available to be sent, and the user is not admin, so they did not have access to shared schedule.
GeneralI am getting error for this Error is System.Web.Services.Protocols.SoapException: The item '/pdf01' cannot be found.memberramashwin29-Sep-09 16:33 
I am getting this error below mention line
 
Rse2005.ExecutionInfo ei = rsExec.LoadReport("/pdf01", historyID);
 

Error message
 

System.Web.Services.Protocols.SoapException: The item '/pdf01' cannot be found.
Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/pdf01' cannot be found.
at Microsoft.ReportingServices.Library.DefinitionLoader.GetParameterDefinition(CatalogItemContext itemContext, String historyId, Boolean forRendering, SecurityRequirements requirements)
at Microsoft.ReportingServices.Library.ReportParameterDefinition.Load(CatalogItemContext itemContext, String historyId, Boolean forRendering, RSService service, SecurityRequirements requirements)
at Microsoft.ReportingServices.Library.GetDataForExecutionAction._GetDataForExecution(CatalogItemContext reportContext, ClientRequest session, String historyID, DataSourcePromptCollection& prompts, ExecutionSettingEnum& execSetting, DateTime& snapshotExecutionDate, ReportSnapshot& snapshotData, Int32& pageCount, Boolean& hasDocMap, PageSettings& reportPageSettings, PaginationMode& paginationMode)
at Microsoft.ReportingServices.Library.GetDataForExecutionAction.ExecuteStep(CatalogItemContext reportContext, ClientRequest session, DataSourcePromptCollection& prompts, ExecutionSettingEnum& execSetting, DateTime& executionDateTime, ReportSnapshot& snapshotData, Int32& pageCount, Boolean& hasDocMap, PageSettings& reportPageSettings, PaginationMode& paginationMode)
at Microsoft.ReportingServices.Library.CreateNewSessionAction.Save()
at Microsoft.ReportingServices.WebServer.ReportExecution2005Impl.LoadReport(String Report, String HistoryID, ExecutionInfo2& executionInfo)
--- End of inner exception stack trace ---
at Microsoft.ReportingServices.WebServer.ReportExecution2005Impl.LoadReport(String Report, String HistoryID, ExecutionInfo2& executionInfo)
at Microsoft.ReportingServices.WebServer.ReportExecutionService.LoadReport(String Report, String HistoryID, ExecutionInfo& executionInfo)
 

Please help any one
 
Thanks
 
Ram
GeneralGreatmemberridha touir11-May-09 6:31 
Great job thanks
Generalredirect to another page after viewing pdf outputmembertammi.harris23-Oct-07 8:17 
How can I send the user from the rspdf.aspx page to another page after closing the pdf document?
 
Thanks for your help
GeneralRe: redirect to another page after viewing pdf outputmemberSimon Pang28-Oct-07 8:41 
I can't think of an easy way to realize this exact behavior in rspdf.aspx
 
But there might be 2 options worth to try:
(1) Try "async" SOAP call to catch these kinds of events
For instance, replace rsExec.Render with rsExec.EndRender
 
or
 
(2) Instead of directly openning pure PDF as a response result, make a new real web page and PDF showing inside it.
 
Embed a little piece of javascript to the web page, so whenever the page is closed, it will reopen another webpage.
 
I think the Option(2) is easier than Option(1).
 
HTH

GeneralRe: redirect to another page after viewing pdf outputmembertammi.harris29-Oct-07 3:38 
Thank you!
QuestionServer SetupmemberRyanRyanRyanRyanRyanRyanRyan22-Aug-07 12:52 
Hi Simon,
 
One of our developers ran across your article and it is exactly what he wants to do, but he is having trouble getting the sample to work. I am trying to assist him (sys admin) but am unclear what exactly needs to be installed or configured (if anything) on the server side to make this work. Reporting Services is working correctly on our development server, and we use it to create reports for other projects.
 
From my research, I across the ReportViewer redistributable, but am not sure if this really needed or not. VS 2005 is not installed on our dev server of course, and I don't see any server components like I remember being in VS 2003 that were installed on the server. Is all that is required a working SSRS? If so, our problem must lie elsewhere as our dev server is IIS/SQL/SSRS, all local.
 
Thanks for the info.
 
Ryan
 

AnswerRe: Server SetupmemberSimon Pang22-Aug-07 15:23 
Hi Ryan:
 
The article source code assumes you run SSRS in the local PC.
Since you have a remote dev server (IIS/SQL/SSRS), you need to change the web service configuration in your source code.
 
Here is the solution:
 
(1)Locate the web service configuration of the example.
<source code installed directory>\RsPdf\App_WebReferences\ReportExecution2005
 
(2)Use notepad to open ReportExecution2005.discomap file,
Change "http://localhost/ReportServer/ReportExecution2005.asmx" to
"http://<your dev server IP address>/ReportServer/ReportExecution2005.asmx" and save it
 

(3)Use notepad to open ReportExecution2005.wsdl file,
Change "http://localhost/ReportServer/ReportExecution2005.asmx" to
"http://<your dev server IP address>/ReportServer/ReportExecution2005.asmx" and save it
 
This is it.
 
HTH
-Simon
=====================
BTW, the example's developing environment can all be done on a single PC, with:
 
XP SP2
 
IIS 5.1(locally installed)
 
.NET 2.0
 
VS2005
 
SQL Server Business Intelligence Development Studio
(This is an add-on to the VS2005 and you can download it from microsoft)
 
SQL server express 2005
 
No ReportViewer needed in the whole solution.
 

 

GeneralRe: Server SetupmemberR__y___a_n11-Sep-07 4:59 
Simon,
 
Thanks for the help but we are still having problems. I have attempted your sample and also Microsoft's similar sample http://support.microsoft.com/kb/875447. Either sample is exactly what we want to do, but regardless of the attempt, we get no results when we click the button to produce the PDF. I have no idea what we are doing wrong but on yours and the MS sample, we simply get no PDF. In both cases I can generate the report by going to SSRS directly.
 
I have tried it... my developer has tried it... I've built default stand-alone all-in-one workstations to attempt it on a clean system... nothing works and we get the same (lack of) results. We are either missing some component that needs to be installed or perhaps it is a setup and/or security issue that I don't know how to configure. However, I can't find anything that explains what must be done to make these samples work.
 
My developer asked if you have the project file for this sample that you would be willing to share. He pointed out a file "RsPdf.aspx.cs" that he says would help him understand. Would you be willing to share this file?
 
For me, I am convinced the problem lies in our setup, either a configuration or security issue that is keeping the PDF from showing, although I have no leads on where the problem is. I see that people are successfully doing this all over the internet, obviously yours is working great, but I just can't seem to duplicate it. It must be something really basic that we are missing.
 
Any ideas? Thanks for any help you can give.
 
Ryan
GeneralRe: Server SetupmemberSimon Pang11-Sep-07 8:34 
Ryan:
 
Not sure what's wrong exactly in your setup. If you can manually view reports through SSRS, That means SSRS itself is configured OK.
 

I would guess you might need to customize the security part of your code. Refer to my "security tips" in this article.
 
VS2005 web project doesn't need a project.sln file to open the project. You can directly open the folder as a website project. Your programmer can use VS2005 directly to open the RsPdf Folder you downloaded from codeproject. All the sources are included already.
 
Just in case if you still have issues and like to discuss further directly, email me: info[at]rptea.com
 
HTH
 

QuestionError thrown in online demo - http://www5.rptea.com/rspdf/memberwiegelman10-Jul-07 5:49 
I typed "This is a test" into the online demo and received the following error message. It appears that you are not alloowing remote connections so the server throws an error.
 
Server Error in '/RsPdf' Application.
--------------------------------------------------------------------------------
 
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>
SQL Server Reporting Services
</title><meta name="Generator" content="Microsoft SQL Server Reporting Services 9.00.3042.00" />
<meta name="HTTP Status" content="500" />
<meta name="ProductLocaleID" content="9" />
<meta name="CountryLocaleID" content="1033" />
<meta name="StackTrace" content=" at Microsoft.ReportingServices.Library.ConnectionManager.OpenConnection()
at Microsoft.ReportingServices.Library.Global.get_SharePointIntegratedFlagFromCatalog()
at Microsoft.ReportingServices.WebServer.Global.RunOnlyOnceStartReportServer()
at Microsoft.ReportingServices.WebServer.Global.StartApp()
at Microsoft.ReportingServices.WebServer.Global.Application_BeginRequest(Object sender, EventArgs e)" />
<style>
BODY {FONT-FAMILY:Verdana; FONT-WEIGHT:normal; FONT-SIZE: 8pt; COLOR:black}
H1 {FONT-FAMILY:Verdana; FONT-WEIGHT:700; FONT-SIZE:15pt}
LI {FONT-FAMILY:Verdana; FONT-WEIGHT:normal; FONT-SIZE:8pt; DISPLAY:inline}
.ProductInfo {FONT-FAMILY:Verdana; FONT-WEIGHT:bold; FONT-SIZE: 8pt; COLOR:gray}
A:link {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#3366CC; TEXT-DECORATION:none}
A:hover {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#FF3300; TEXT-DECORATION:underline}
A:visited {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#3366CC; TEXT-DECORATION:none}
A:visited:hover {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; color:#FF3300; TEXT-DECORATION:underline}
 
</style>
</head><body bgcolor="white">

Reporting Services Error

  • The report server cannot open a connection to the report server database. A connection to the database is required for all requests and processing. (rsReportServerDatabaseUnavailable) Get Online Help
    • An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)

SQL Server Reporting Services
</body>
</html>
--.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Rest of error message omitted...
 

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42
AnswerRe: Error thrown in online demo - http://www5.rptea.com/rspdf/memberSimon Pang10-Jul-07 11:11 
It's working now.
The online example's SQL server stopped itself for some reason (I have to dig down a little bit and ask my ISP for that).
QuestionInvalid PathmemberWelshlady9-Jul-07 1:43 
Hi
I'm getting an invalid path message, could you please confirm what needs to go where?
System.Web.Services.Protocols.SoapException: The item '/PdfReport/pdf01' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/PdfReport/pdf01' cannot be found.
 
I have copied the PdfReport folder and its contents under my reportserver folder.
The rsPDf folder I have set up as a virtual directory under IIS.
 
Thanks.
AnswerRe: Invalid PathmemberSimon Pang9-Jul-07 2:44 
"rsPDF" itself is a VS2005 project, you can run it in VS2005 IDE and don't need to set up anything in IIS, this is a benefit of VS2005 web project.
 
The procedure to run the example is (assume your SSRS configured properly):
 
(1)Open the "PdfReport" project, and "deploy" it to your "localhost" report server
(2)Open the "rsPDF" project and run it directly from VS2005 IDE.
 

Did you "deploy" pdf01? "Deploy" here means upload your pdf report template to SSRS database.
 
Usually you do this in VS2005 IDE, right click the project name (PdfReport in this case) and hit "deploy".
 
The article assume your SSRS server is "localhost", you can test the "deploy" like this:
open browser and type http://localhost/reportserver, you should see "pdfreport" entry, and open "pdfreport" entry, you should see "pdf01" entry.
 
Again, How to configure SSRS is beyond the scope of this article. If you are not sure about your SSRS installation and configuration, please refer to SQL server book online or any other SSRS book.
QuestionNice...memberNamshub28-Jun-07 22:29 
I've been doing something similar, but as always you find a sample after you've solved the issues.
 
On question though, have you thought about the passwording of the document. Unfortunately I need to have the added security of a password on the PDF document so the data is secure (to a point of course!)
 
Any thoughts would be helpfull. Big Grin | :-D
AnswerRe: Nice... [modified]memberSimon Pang30-Jun-07 4:26 
I think the current SSRS doesn't have this capability.
But I will use 3rd party library to do this.
 
One library (open source) I used a lot is "PDFsharp",
 
Here is the c# example on how to programmatically add password to PDF file:
 
http://www.pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=36&Itemid=47[^]
 
HTH
-Simon
 

 
-- modified at 10:31 Saturday 30th June, 2007
Generalerror occurs 'file is damaged'membervikas chaudhary24-Jun-07 18:07 
Sometimes an error occurs while opening the PDF file that 'file is damaged.Can't be opened'
can u provide any solution to that and reason behind this?
AnswerRe: error occurs 'file is damaged'memberSimon Pang25-Jun-07 2:58 
Use any text editor (such as notepad.exe) to open the PDF in pure text mode,
 
If You see the first part of the text are HTML code, it means web application's HTML is embeded into PDF,
The same thing bothered me when I test it, but it's fixed by the below statement:
 
Response.End();
 
The statement cut the HTML stream before it build PDF. This is valid for my IE 7 environment.
 
For Firefox/Opera, you might want to tweak around a little bit.
GeneralRe: error occurs 'file is damaged'membervikas chaudhary25-Jun-07 3:56 
well,I appreciate ur quick reply but the problem still persist when i was using the statement in my code.Any other way to resolve the issue?
AnswerRe: error occurs 'file is damaged'memberSimon Pang25-Jun-07 4:22 
Did you open your PDF with a pure text editor (notepad.exe)? Did you see the HTML part at the beginining of the file? Did you have the same problem even when you try the LIVE DEMO (http://www5.rptea.com/rspdf)?
 
If so, this must relate to the web browser configurations.
Hard to guess which part went wrong without knowing details of the test environment.
 
But I suggest 2 ways to work around this issue:
 
(1) Switch your client test environment to another PC with default IE 7 setup
or
(2) Instead of downloading the stream directly to the browser client, Changing the source code to save the web service output binary bytes into a server hosted PDF file.
 
Hope this help your situation.
 

 

GeneralGreat Job!!memberleomicheloni19-Jun-07 2:29 
Great Job!! thanks.Smile | :)
GeneralNicememberthund3rstruck18-Jun-07 8:25 
Fantastic job man! This is cool.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 17 Jun 2007
Article Copyright 2007 by Simon Pang
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid