Generating PDF from .Net

May 26, 2010 PDF ASP.NET C#
There are several neat libraries for .Net to create PDF files on the fly. Some rely on you doing all the content by code, others like FO.NET uses XSD to accomplish this.

Here's a hello world example for FO.NET, first the hello.fo content:
<?xml version="1.0" encoding="utf-8"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">

<fo:layout-master-set>
<fo:simple-page-master master-name="simple"
page-height="29.7cm"
page-width="21cm"
margin-top="1cm"
margin-bottom="2cm"
margin-left="2.5cm"
margin-right="2.5cm">
<fo:region-body margin-top="3cm"/>
<fo:region-before extent="3cm"/>
<fo:region-after extent="1.5cm"/>
</fo:simple-page-master>
</fo:layout-master-set>

<fo:page-sequence master-reference="simple">
<fo:flow flow-name="xsl-region-body">
<fo:block font-size="18pt" color="black" text-align="center">
Hello, World!
</fo:block>
</fo:flow>
</fo:page-sequence>

</fo:root>

And the C# code to generate the PDF from the XSD above:

using System.IO;
using Fonet;

namespace FonetExample {
class HelloWorld {
static void Main(string[] args) {
FonetDriver driver = FonetDriver.Make();
driver.Render("hello.fo", "hello.pdf");
}
}
}

You'll find the open source FO.NET library and documentation how to use it over at Codeplex.

Related posts: