Generating PDF from a Servlet

Problem

You want to make a printer-friendly document using a format like Adobe PDF.

Solution

Use response.setContentType("application/pdf") and a third-party Java API that can generate PDF.

Discussion

Portable Document Format (PDF) is a file format created by Adobe Systems Inc. PDF gives you full control over how your document looks, much more so than HTML, XML, or even Java’s printing routines (see Chapter 12). Adobe Acrobat is a set of programs for reading and writing PDF. Adobe itself does not publish a Java API for generating PDF from scratch, but it does publish the file format specification (Adobe Portable File Format Specification) and explicitly gives everyone permission to write software to generate and/or process PDF files. PDF is a good fit for processing by an object-oriented language like Java, as it’s an object-based text format. As a result, there are several PDF APIs available for Java, both free and commercial:

  • Sitraka/KL Group (http://www.klg.com) has a PDF API as well as charting and other widgets, and JProbe, a leading tuning tool.

  • StyleWriterEE (see http://www.InetSoftCorp.com).

  • PDFLib GmbH (http://www.pdflib.com/pdflib/) produces PDFLib. PDFLib is mostly in C, with a Java wrapper; it also has bindings for several other popular languages.The source code is distributed, making it very cross-platform. It’s free for noncommercial use; for commercial use, a small licensing fee is required.

  • ReportLab (http://www.reportlab.com) is not for ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.