Generate PDF from C#.NET
Generating PDF files from .NET has always been a cumbersome task. There are a couple of different ways by which a PDF can be created from Microsoft.NET.
- Crystal Reports.NET that comes with the Visual Studio.NET
- Free Utilities like NFop and Open source systems Report.NET, PDFSharp etc.
- Commercial software such as ABC Pdf, Aspose Pdf, etc
NFOP has always been my favorite to generate PDF documents. I have used this in enterprise level web applications to generate hundreds of PDF documents successfully. NFOP was originally developed by Jason Pettys. It is an extension of the open source project Apache FOP. NFOP (Formatting Objects Processor) accepts XSL-FO (XSL-Formatting object) as input and renders the result in PDF as output.
Even though the original article on NFOP by Laurent Kempfe gets you started, in the initial days I found this not adequate as it fails to provide a comprehensive view of how the FOP, .NET, XML, and XSL-FO go together in creating a PDF. This blog aims to bridge that gap.
Follow these six steps to successfully generate a PDF on the fly.
- Download NFop.
- Download Microsoft J#.NET redistributable package for .NET 1.1 or for .NET 2.0
- Create an ASP.NET project and add ApacheFop.Net and vjslib as a reference to the project.
- Data in XML format: Usually when generating a PDF document you will be dealing with dynamic content rather than static content. The first step is to get all the data that you want in a properly formatted XML document.
<?xml version=”1.0″ encoding=”utf-8″?>
- Create XSLT: Google XSL-FO and you will find lot of articles on the subject. However, you have to remember that not all the language elements in XSL-FO are supported by NFOP and there are no reliable documents that I have come across that provide this information. When generating complex PDF docs you may end up following trial and error method to find the XSL-FO elements accepted by NFOP. However, for most practical purposes you should not have any problem.
- Render PDF: Use the C# Code, XML (as part of C# code) and XSLT-File to generate the PDF. That’s all to it.