Monday, October 25, 2004

Creating PDF documents in Java

Everyday I see more of those pdf-icons, on web-pages, that link to a pdf version of the document. It's a very nice feature. It's very useful if you want to save the document for later reference, or even for printing.

I just experimented with a tool to create PDF documents in Java: iText. It's very simple to use, although the documentation could be better (I have to remember this feeling the next time I don't feel like writing documentation). I just used a few simple options to generate a PDF from a text-only article. However, it also supports graphics, and for what I've seen from their website, I think it supports just about everything you'd need to create a PDF. For me, I just needed the following lines to show a title and a body text (yes, my requirements were simple) :


Font chapterFont = FontFactory.getFont(
FontFactory.HELVETICA, 24, Font.NORMAL, new Color(0, 0, 0));
Paragraph title = new Paragraph(article.getTitle(), chapterFont);
Paragraph body = new Paragraph(article.getBody());
document.add(title);
document.add(body);

Well, in fact you'll need more code to initialize and to generate the actual PDF. Unless you're using Spring. Spring MVC has a very nice integration with iText. By using Spring MVC, a PDF document is just another way of showing the content. It's another kind of view, like a JSP or a XSLT. And it's resolved just like a JSP, by the View Resolver (you'll probably have to use ResourceBundleViewResolver, as, for example, InternalResourceViewResolver seems to be more suited to JSP pages). So I added the following to my "views.properties":
articlePDF.class=view.pdf.ArticlePdfPage
This specifies the class that generates the view to the client. Now, instead of forwarding to a JSP in the Controller, I forward to a PDF page, but for the controller it's completely transparent. I just need to tell it to forward to articlePDF view.

As for the class, it must extend AbstractPdfView. Below is the full class that I used :

public class ArticlePdfPage extends AbstractPdfView {

protected void buildPdfDocument(Map model, Document document,
PdfWriter writer, HttpServletRequest request,
HttpServletResponse response) throws Exception {

ArticleBean article = (ArticleBean) model.get("article");

Font chapterFont = FontFactory.getFont(
FontFactory.HELVETICA, 24, Font.NORMAL,
new Color(0, 0, 0));

Paragraph title = new Paragraph(article.getTitle(),
chapterFont);
Paragraph body = new Paragraph(article.getBody());
document.add(title);
document.add(body);
}
}
iText seems good if you need to dynamically create PDF documents. However it may not be the best solution for every situation. It depends on what kind of content you have and how complex the final document should be. For example, if you already have a XML version of the document, there are simpler ways of generating a PDF from it (Apache FOP, for example).

0 comentários: