Saturday, October 31, 2009

iTextSharp PDF rendering in a medium trust ASP.Net environment

Rendering a PDF for download or email is a very common task for an e-commerce website. One thing to consider when deciding on a PDF library for rendering is what environment the site is running in. Most ASP.Net shared hosting solutions will restrict their hosted sites to Medium trust to prevent a rogue site from peeking at other sites on the server.

Medium trust environments can cause funny things to happen between the development environment and the production environment. By default the websites created in Visual Studio have Full trust, this can cause security problems after deployment if you haven't setup your development environment to mimic production. A good first step is to add a trust level to your web.config system.web section.

    <trust level="Medium" />
This will help to find any trust issues while developing.

So to rendering PDF. After trying ReportViewer 2008 in local mode and PDFSharp (both of which are still very good at rendering PDFs), I have found success with iTextSharp. ReportViewer and PDFSharp both require Full trust mode because they use native COM dlls as part of the GDI rendering process. This makes them unsuitable for shared hosting environments unless you can convince your hoster to raise your site's trust level. The PDFSharp Wiki says that release 1.30 solves most medium trust issues and that full support is in the near future, which is promising. My car also has most of it's wheels, but until I put the fourth one on it isn't going to go far on the road.

iTextSharp appears to have less documentation on the web (one of the best being a fairly comprehensive iTextSharp tutorial), but it is just as powerful as PDFSharp or ReportViewer. The best thing about it though is that it can run in Medium trust mode - once a minor change is made to allow partially trusted callers. To make this change download the iTextSharp source distribution (
Modify the AssemblyInfo.cs file to add the partially trusted callers attribute.
[assembly: AllowPartiallyTrustedCallers()]
Rebuild the iTextSharp assembly and it should be good to go in a Medium trust environment.

kick it on Shout it