Friday, March 5, 2010

Easy PDF generation with Seam

Seam is a fantastic integration framework that can do many things. It is mostly known for its integration with JSF 1.x making it actually usable and adding a lot of features that have now become standard in JSF 2.0 i.e. page actions, factory methods, better navigation, etc. 
But there are many more features worth mentioning: JPA lazy loading, BPM support in web applications, integration with quartz, iText integration and many more.

iText integration
The iText library is a widely used open source Java library for generating PDF documents. However, using its programatic API to construct a PDF document is time consuming (think building a XML document using DOM or construct a UI using Swing). Seam neatly ties iText, JSF, and Facelets together and allows developers to declaratively write PDF pages with dynamic content, just as you would do for JSF web pages. Furthermore, you can now use templates in PDF pages.

The key to do this the special XHTML tag library for PDF elements that transparently calls iText when the page is rendered. Let's see a simple example of how we to use the iText integration to send a number of PDF documents attached in an email.
public class PdfSender {

    private Renderer renderer;

    private PdfAssembler pdfAssembler;

    private FtpHandler ftpHandler;

    public void sendPdf() throws IOException, ParseException {

        Map<String, String> files = ftpHandler.getData();
        if (files.isEmpty()) {
            throw new IllegalArgumentException("No data found on FTP server");

        List<Pdf> pdfList = processFTPData(files);
        Contexts.getEventContext().set("pdfList", pdfList);
        renderer.render("/pdf/sendPdf.xhtml");  //sends mail

    private List<Pdf> processFTPData(Map<String, String> files) throws ParseException {

        List<Pdf> pdfList = new ArrayList<Pdf>();
        for (final String location : files.keySet()) {
            final String data = files.get(location);
            if (StringUtils.isEmpty(data)) {
                throw new IllegalArgumentException("Empty data file for: " + location);
            pdfList.add(pdfAssembler.assemblePdf(location, data));

        return pdfList;

We just gather a bunch of data files via FTP, process them into a collection of DTOs representing the PDF structure and then add it to Seam's event context.  The DTOs are used to transfer data to the view (xhtml templates). Next we just "render" the mail with the attachments.

<?xml version="1.0" encoding="UTF-8"?>
<m:message xmlns=""

    <m:header name="X-Sent-From" value="PDFGenerator"/>
    <m:from name="PDF Generator" address="#{mailAddress}"/>
    <m:to name="Manuel Palacio">#{mailAddress}</m:to>
        <ui:repeat value="#{pdfList}" var="pdf">
            <m:attachment fileName="#{pdf.location}.pdf">
                <ui:include src="/pdf/pdf.xhtml"/>

Pdf.xhtml generates the sections of the document

<p:document xmlns:ui=""
            keywords="Report #{pdf.artNr}"
            subject="Report #{pdf.artNr}"

     <ui:repeat value="#{pdf.sections}" var="section" varStatus="status">
        <p:chapter number="#{status.index + 1}">
            <p:title><p:font size="18"><p:paragraph spacingAfter="12"

            <ui:repeat value="#{section.areas}" var="area">
                        <p:font size="8" style="bold"><p:paragraph
                    <p:paragraph spacingBefore="1" spacingAfter="0" leading="10" keepTogether="true">
                        <ui:include src="/pdf/displayObject.xhtml"/>


DisplayObject.xhtml generates the data in each section

<ui:repeat value="#{area.displayObjects}" var="displayObject" xmlns:ui=""
        <p:font size="8" style="bold">#{}</p:font>
        <p:font size="8">&#160;(#{displayObject.formattedId})</p:font>
        <p:font size="8" rendered="#{not empty displayObject.address}">&#160;#{displayObject.address}</p:font>
    <ui:repeat value="#{}" var="event">
            <p:font size="7">#{event.text}&#160;#{}</p:font>
    <p:paragraph spacingAfter="5"/>

It takes time to learn how to tweak all the parameters to make the PDF look the way you want but it's definitely much easier and intuitive than using the iText API directly. For very advances formatting you may want to look at jasperreports.

Now we could define a cron job that runs the sendPdf task at defined intervals.

public class SchedulerController {

    ScheduleProcessor processor;
    Method called when framework is initialized
    public void startScheduler(String cronExpression) throws IOException, ParseException, ExecutionException, InterruptedException {
        processor.createQuartzTimer(new Date(), cronExpression);

 * Timer class. The methods annotated as asynchronous will be called by Quartz or other implementations
 * as specified by @IntervalCron
public class ScheduleProcessor {

    private Log log;

    private PdfSender pdfSender;

    public QuartzTriggerHandle createQuartzTimer(@Expiration Date when, @IntervalCron String interval) throws IOException, ParseException, ExecutionException, InterruptedException {
       "[#0] Processing pdf document with interval #1", when, interval);

        return null;

In components.xml we make sure the cron job is started when Seam is initialized

<?xml version="1.0" encoding="UTF-8"?>
<components xmlns=""

    <core:init transaction-management-enabled="false"/>


    <mail:mail-session session-jndi-name="mail/pdfGeneratorSession"/>

    <component name="ftpHandler">
        <property name="ftpHost">localhost</property>
        <property name="ftpPort">2121</property>
        <property name="ftpUser">admin</property>
        <property name="ftpPassw">admin</property>


    <factory name="mailAddress" scope="STATELESS" value="xxx@xxx.xx" auto-create="true"/>

    <event type="org.jboss.seam.postInitialization">
        <action execute="#{schedulerController.startScheduler('0 0/1 * * * ?')}"/>


Seam has definitely made simple tasks like sending mail and generating PDFs even simpler and more elegant.

1 comment:

  1. Hi i have used template to generate pdf using seam. problem is the table copied into richTextEditor from word file doesn't display properly in pdf. I think because of mso classes. It has been raised as a major issue and release has been stopped. Please post the solution asap