Returning a Crystal report as a PDF ActionResult in ASP.Net MVC

In a recent project I needed to display a generated PDF contract document inside the browser. I found a great article by Patrick Kalkman illustrating how to create a custom ActionResult that converts a HTML string into a PDF using the iTextSharp library.

This seemed like the perfect solution, however, I later found that the conversion from HTML to PDF is not perfect at all and getting your design to look the same in PDF as it does in HTML is not easy. So I found another article by Hasibul Haque, where he shows how to return a Crystal Report as PDF using ASP.Net MVC.

The Crystal Report approach works well, as your design will look perfect. The only problem I had was Hasibul’s approach returned the PDF as a download and I wanted to display it inside the browser. I combined Patrick and Hasibul’s approaches and what I came up with was a CrystalReportPdfResult

The CrystalReportPdfResult is an ASP.Net ActionResult, that return the Crystal Report as a PDF file. The result (using an iframe) looks like this inside the browser:

image

Creating the CrystalReportPdfResult class

To generate the result as indicated by the previous image, follow these steps:

  1. Create a folder inside your ASP.Net MVC project called Pdf.
  2. Add a new class to this folder called CrystalReportPdfResult.cs.
  3. The new class will inherit from the ASP.Net MVC ActionResult class.

The entire code listing for the CrystalReportPdfResult class follows:

CrystalReportPdfResult.cs
  1. publicclassCrystalReportPdfResult : ActionResult
  2. {
  3.     privatereadonlybyte[] _contentBytes;
  4.     public CrystalReportPdfResult(string reportPath, object dataSet)
  5.     {
  6.         ReportDocument reportDocument = newReportDocument();
  7.         reportDocument.Load(reportPath);
  8.         reportDocument.SetDataSource(dataSet);
  9.         _contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
  10.     }
  11.     publicoverridevoid ExecuteResult(ControllerContext context)
  12.     {
  13.         var response = context.HttpContext.ApplicationInstance.Response;
  14.         response.Clear();
  15.         response.Buffer = false;
  16.         response.ClearContent();
  17.         response.ClearHeaders();
  18.         response.Cache.SetCacheability(HttpCacheability.Public);
  19.         response.ContentType = “application/pdf”;
  20.         using (var stream = newMemoryStream(_contentBytes))
  21.         {
  22.             stream.WriteTo(response.OutputStream);
  23.             stream.Flush();
  24.         }
  25.     }
  26.     privatestaticbyte[] StreamToBytes(Stream input)
  27.     {
  28.         byte[] buffer = newbyte[16 * 1024];
  29.         using (MemoryStream ms = newMemoryStream())
  30.         {
  31.             int read;
  32.             while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
  33.             {
  34.                 ms.Write(buffer, 0, read);
  35.             }
  36.             return ms.ToArray();
  37.         }
  38.     }
  39. }

 

Creating the Crystal Report

Next, we need to create the Crystal Report that will be returned as a PDF. Do this by following these steps:

  1. Create a new folder called Reports in your project.
  2. Add a new Crystal Report object to the Reports folder. You can find the item template under the Reporting tab on the Add New Item dialog.image
  3. Design the report to your liking and save it.
  4. If you need to install Crystal Reports for Visual Studio 2013, get it here.

Creating the Action that will return the PDF

Next, we need to create the actual Action on a Controller that will return the CrystalReportPdfResult, by following these steps:

  1. Open your controller. In this example, we’ll use the HomeController.
  2. Add a new method called Pdf that will return a CrystalReportPdfResult object.
  3. Inside this method, we’ll build a list of customer that will be used as data for the report and build the path to the report filename. The code for the method follows:
  1. publicCrystalReportPdfResult Pdf()
  2. {
  3.     List<Customer> model = newList<Customer>();
  4.     model.Add(newCustomer { CompanyName = “Blah Inc.”, ContactName = “Joe Blogs” });
  5.     string reportPath = Path.Combine(Server.MapPath(“~/Reports”), “rptCustomers.rpt”);
  6.     returnnewCrystalReportPdfResult(reportPath, model);
  7. }

 

Creating the View

We’ll embed the PDF using an <iframe>, so open a view. In this case we’ll  use About.cshtml and replace it’s mark-up with the following:

About.cshtml
  1. @{
  2.     ViewBag.Title = “Customer Report”;
  3. }
  4. <h2>@ViewBag.Title.</h2>
  5. <p>This is the customer report</p>
  6. <divclass=”row”>
  7.     <divclass=”col-md-10″>
  8.         <iframesrc=”@Url.Action(“Pdf”, “Home”)height=”500″width=”100%”></iframe>
  9.     </div>
  10.     <divclass=”col-md-2″>
  11.         <h3>Other page content</h3>
  12.         <buttontype=”button”class=”btn btn-primary”>Click here</button>
  13.     </div>
  14. </div>

 

Note, that we’re using the @Url.Action helper to set the src attribute of the <iframe> element. This will make a call to the Pdf action on the Home controller and render the result inside the <iframe>

I’ve tested this on the latest version of Chrome, Firefox and Internet Explorer and it works on all of them.

Hope this helps someone that needs something similar. Thank you for reading. Until next time, keep coding!

Download the sample project here.

If you have any comments or questions, please feel free to ask leave a comment or drop me a line on Twitter.

Need help with you next ASP.Net MVC Project?
Do you need guidance with your next .Net project?
Contact me for ASP.Net MVC and .Net software development and consulting.

Microsoft Outlook Email Templates for Web Designers and Developers Add-in

Bea Kylene Jumarang wrote a great piece listing some very handy email templates for web developers and designers. I found the information so valuable I could not help but create a Microsoft Outlook (2007, 2010 and 2013) Add-in that automatically inserts the templates for you.  It’s released under the GNU General Public License, which means it is completely free for you to use and share with your friends and colleagues.

Thanks Bea!

Download the add-in here.

Note that the actual templates are free for commercial and personal use, but you’re not allowed to sell it or claim it as your own. So for the sake of complete disclosure, I did not create the templates, I only created the Outlook add-in that automatically inserts the template text into your Outlook e-mail.

How it works

The add-in adds a new “Templates for Developers and Designers” tab to the Outlook E-mail window:

image

Clicking on the “Insert Template” button lists all the available templates:

image

Clicking on the template name, automatically inserts the template into the e-mail. If the e-mail has a recipient the recipient’s name will automatically be inserted into the e-mail as well:

image

This functionality will work when composing a new e-mail and when replying to an existing mail.

The Templates

All the templates are stored inside your My Documents folder inside a folder called TemplatesForDevsAndDesigners.

image

Each template has its own folder and inside this folder the actual template called template.html. You can edit this .html file in any text editor to customize the template to your liking.

It’s as easy as that. I hope you find the add-in useful.  Any comments, suggestions or bug reports, fire away in the comments or get in touch with me on Twitter.

You can download the add-in here.

SQL Server for Excel

After numerous requests, I’ve updated the SQL Connector for Excel and renamed it to SQL Server for Excel.
We can’t allow the MySQL guys to have all the fun.

Download the early Beta version from http://www.sqlforexcel.com/

Introducing the Bootstrap Bundle for ASP.Net MVC

Ever wished you could create an ASP.Net MVC website with the click of a few buttons, and selecting a few options? Now you can, The Bootstrap Bundle contains 15 different project and 16 item templates for Visual Studio 2013, that make creating a ready to go website a breeze.

It’s free, have  a look at www.bootstrapbundle.com or download it from Visual Studio Gallery.

Excel Online & Google Sheets for developers – what’s the difference?

In the last few weeks we’ve covered a lot of aspects of both Google Sheets and Excel Online and we’ve seen that both platforms offer developers various options to customize and integrate with. We also realized that each platform has as a number of caveats as well as a number of redeeming qualities.

In this article we’ll evaluate what we’ve learned so far about Google Sheets and Excel Online and compare the two platforms and what it means for developers.

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.

Creating Apps for Microsoft Outlook

In the last couple of weeks we’ve explored many aspects of both Google and Microsoft’s online offerings when it comes to Office productivity.

Gmail provides us with two options to add our own custom functionality in the form of sidebar and contextual gadgets.

Microsoft offers the JavaScript API for Office to developers which allows you to create Apps for Outlook using HTML, CSS and JavaScript. As we’ve discussed in earlier articles, the API does not perform the same level of customization options as the COM based object model, but we are seeing Microsoft investing heavily in the online space so we might get some mayor improvements and enhancements in the future.

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.

Developing Gmail contextual gadgets

In my last article, we explored How to develop Gmail sidebar gadgets. In today’s article we’ll take a closer look at what is involved in creating a contextual gadget for Gmail. Gmail contextual gadgets are a good way to add additional functionality to Gmail allowing your user to perform tasks right from inside their Gmail session.

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.

Extending Google Gmail with sidebar gadgets

Google Mail or Gmail provides developers with an extensibility model in the form of Gmail gadgets. Gmail gadgets come in two flavors: Sidebar gadgets and contextual gadgets.

Sidebar gadgets are shown on the left hand side of the Gmail user interface, just underneath the list of folders – this can be compared to setting your Add-in Express Advanced Task pane’s ExplorerLayout property to BottomNavigationPane.

Contextual gadgets are gadgets that run when certain clues are detected in Gmail. This can be a based on text in the subject or in the message body. For example the translate gadget in Gmail is automatically shown when a foreign language is detected.

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.

Google add-ons vs Microsoft Office Apps: Read/Write tests

We’ve been spending a lot of time with the Office/Productivity offerings from Google (Google Drive/Docs/Sheets) and Microsoft (Office 365, SharePoint, Word, Excel) and both of these two platforms have some drawbacks, but also some redeeming factors.

Google’s offering is purely cloud-based, your add-ons and scripts are hosted by Google and run on both the server and on the client. Microsoft’s offering is unique in the fact that apps for Office can run inside the browser based version of Office on the desktop version. A major drawback we’ve stumbled upon was the fact that Office task pane apps only support the desktop version of Microsoft Word and not the web-based version of MS Word! Because of this, today’s article will only compare Google Sheets and Microsoft Excel Online. It won’t be fair to compare a browser based version of Google Docs with a desktop version of Microsoft Word.

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.

How to create Excel Apps for Office 365

About a week ago we explored the aspects of extending Google Spreadsheets by creating Apps scripts. In that example, we created a sidebar and custom menus with which the user could specify the orientation their current selection could be changed to.

In today’s article, we’ll attempt the same functionality, but this time using the Napa development tools for Office 365. I’m slightly disappointed in saying that the Office Apps object model let me down a little bit with this example. For one, I would love to have seen a function with which I could get a reference to a specific range in the Excel sheet. At the moment the Office.js development model only provides us with access to the currently selected values. None the less, with some creative manoeuvres we will manage to make this example work. Let’s get started!

Read more at Add-in Express.

To see all my recent Add-in Express blog posts visit my author page.