Eden Ridgway's Blog

.Net and Web Development Information

  Home :: Contact :: Syndication  :: Login
  105 Posts :: 1 Stories :: 78 Comments :: 3 Trackbacks

Search

Article Categories

Archives

Post Categories

Development

General

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:

  1. Create an iTextSharp document
    Document document = new Document();
  2. 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));
  3. Create an iTextSharp Xml TextHandler passing in the document instance
    ITextHandler xmlHandler = new ITextHandler(document);
  4. 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
posted on Sunday, July 31, 2005 4:36 PM
Comments have been closed on this topic.