The iTextSharp's current XML to PDF example is clearly out of date and does not work. So I went about fixing the example. You can download it here:
iTextSharpExample.zip.
The generation of a PDF file from XML is surprisingly painless. The steps are as follows:
- Create an iTextSharp document
Document document = new Document();
- Get an instance of the PDF writer and at the same time specify the output PDF
PdfWriter.GetInstance(document, new FileStream("ExampleDoc.pdf", FileMode.Create));
- Create an iTextSharp Xml TextHandler passing in the document instance
ITextHandler xmlHandler = new ITextHandler(document);
- Get the TextHandler object to parse the XML file that has the iTextSharp XML elements
xmlHandler.Parse("ExampleDoc.xml");
Of course there's more to this because the XML document must be in a format that iTextSharp can use. Everything is in the itext.dtd file in the example, but here is a summary:
- The outermost element is itext and one can have title, subject, keywords and author attributes
- Within that you can have one of the following elements:
- chunk - a small piece of text - useful if you want to set the colour or background of the text
- phrase - a collection of chunks and allows you to define the space between lines
- paragraph - a collection of chunks/phrases with a carriage return after them
- The list and listitem element is used to add lists
- You can add images to paragraphs, listitem and several other elements using the image element and url attribute
- Tables are controlled through table, row and cell elements
Here is an example XML file:
<itext>
<paragraph leading="12.0" font="Helvetica" align="Default">
<image url="Cat.jpg" plainwidth="194.0" plainheight="202.0" />
I got this from
<anchor fontstyle="normal, underline" red="0" green="0" blue="255" reference="http://www.ridgywa.co.za/">
Eden's blog
</anchor>
</paragraph>
</itext>
This is what the pdf file generated using the xml above looks like:
iTextXmlToPdf Example.pdf