iText and OpenPDF Example (Wiki forum at Coderanch) (original) (raw)
This example demonstrates a few basic features of the iText library. It creates a 2-page PDF document using various fonts, adds a header (containing the page number) and a footer, draws simple graphics (a couple of lines), and adds text both at an absolute position, and sequentially in a natural flow. It also adds a table that shows various table features, and finally, rotated text.
Note that there are two different versions of iText - iText 5 (iText 7 in its latest version), the current version that is still being developed, and iText 2 (jar file, javadocs).
iText 5 is published under a less permissive license (the GNU Affero GPL license) than iText 2 (which uses the GNU Lesser GPL) and may require you to obtain a license; see here for some discussion of that. There's also less documentation freely available on the net - you'd really need to buy a copy of iText in Action to get the most out of it (which is a good book, though, and will pay itself back in no time by saving you from hunting for information on the net). (If you're using iText 2, then you should get the first edition of the book.)
An alternative to iText that is available under the more business-friendly Apache license is PDFBox. It's not as full-featured as iText, though. PDFBox Example shows how to use it to create a PDF.
There is also an alternative to iText2 named OpenPDF - it is API-compatible, but has progressed since iText 2 and is licensed under a business-friendly license.
The iText API changed substantially from iText 2 to iText 5. This is the code for iText 2:
And this is the code for iText 5. Headers and footers are added through page events, the package names have changed, and the Table/Cell classes have been removed in favor of PdfPTable/PdfPCell.
An additional difficulty with iText 5 is that 5.x releases are not necessarily backwards source compatible to earlier 5.x releases. For example, the BaseColor(java.awt.Color) constructor that existed in iText 5.1 is no longer available in iText 5.2. While in this case it's easy to adapt the code, there may be other incompatible changes for which the upgrade isn't as straightforward.