This tutorial will guide you through setting up Tomcat and Cocoon to serve XML pages, then you will create a DTD, XML file and three XSL stylesheets so that you can view your data in your desktop browser, a cell phone browser and a pdf file.
The last thing we do in this tutorial is convert the xml to a pdf file. Creating a pdf file is great when your users might want to keep or print a copy of the data. Since pdfs are not editable they are a great way to provide users with a document that they will not be able to accidentally (or purposely) modify later.
For pdf generation we will use FOP from Apache. FOP takes in an xml document, an FO stylesheet and outputs a pdf. FOP is actually a separate project from cocoon but the FOP jar is included in the cocoon distribution so you do not need to add anything new to the project. There are a lot of similarities with html or wml stylesheets but you will notice that the formatting is much more specific. You need to create a file called address-pdf.xsl and open it in a text browser. Begin the file with the usual xsl:stylesheet PI but you also need to say that you will be using the xml namespaces for xml and fo:
For any fo file you first need an fo:root element. The fo:root element is essentially the same as the root xsl:template. It defines page layouts, page sequences and host of optional text formatting instructions.
Next add an fo:page-sequence to define how to create the pages within the document. Your entire document can be within one fo:page-sequence or you can use different page-sequence for sections.
Next you need to add fo:flow to output the text. In our file we are applying the templates from the xml result tree.
<fo:flow>
<xsl:apply-templates/>
</fo:flow>
</fo:page-sequence>
Close
the fo:root and xsl:template
</fo:root>
</xsl:template>
Finally we create xsl:templates for the elements of our contact item. In each template we have an fo:block which is used to define font, font size, alignment, etc.
You will notice that the xsl syntax is similar to previous xml files but with fo formatting instruction. Now all that needs to be done is to tell your xml file to use address-pdf.xsl. For simplicity open homer.xml and replace:
It is possible to have both the pdf and html file generated at the same time and have the pdf downloaded from a link in the html page but it is not a straight forward as you might think. I will save that for another day. All that is left for you now is to point your browser to http://localhost:8080/address/homer.xml. If you have an Acrobat plugin the pdf should load automatically. If you do not have a plugin you should be prompted to download the file. Once downloaded open Acrobat to view the file.
That covers this tutorial. If everything has gone well you have a good idea of how powerful xml can be. Hopefully it can help you manage your data and make your life a little easier