Tutorial: iText by Example

Table of Contents

Introduction:
iText is a library that allows developers to extend the capabilities of their web server (and other JAVA) applications with dynamic PDF document generation. In this tutorial, you will find lots of standalone examples to learn how to use most of the iText functionality and features. It should be easy to integrate most of the solutions in a Servlet, a Java Web Start application or some other Java program. This tutorial is far from complete, but it will be updated on a regular basis.


Part I: General Use of iText
Hello WorldHow-to generate a PDF document with iText in 5 easy steps.
Sections
Examples
HelloWorld
Generates a simple 'Hello World' PDF file
Output:
DefaultPageSize
Generates a PDF document with the default page size and some other predefined standard pagesizes
Output:
LandscapePortrait
Generates a PDF document with the first page in Lanscape; the second page in Portrait
Output:
CustomPageSize
Generates a PDF document with a custom pagesize and backgroundcolor
Output:
Margins
Demonstrates the margin functionality
Output:
HelloSystemOut
Writes PDF output to System.out
Output:
HelloWorldMultiple
Writing to different writers at the same time; using pause() and resume()
Output:
HelloEncrypted
Again a PDF with the text 'Hello World', but this time the document is encrypted. To read it, you need to know the userpassword: 'Hello'
Output:
HelloWorldMeta
Adding metadata to a new PDF document
Output:
ANT script (all examples):
iText in a Web ApplicationHow-to use iText in Web Applications.
Sections
Examples
HelloWorldServlet
Generates a simple 'Hello World' file from a servlet (PDF, HTML or RTF)
Extra jars needed:
  • servlet.jar
Servlets/JSP:
OutSimplePdf
Generates a simple PDF file from a servlet. The file is buffered and served with the extension .pdf
Extra jars needed:
  • servlet.jar
Servlets/JSP:
UserAgent.jsp
Looks at the user-agent: if MSIE on Windows, embed the PDF; if another browser, redirect to the servlet
Servlets/JSP:
GetPost.jsp
Shows that PDF generation works with GET and POST
Servlets/JSP:
ProgressServlet
Shows how to avoid receiving a timeout in your browser if generating the PDF takes a really long time.
Extra jars needed:
  • servlet.jar
Servlets/JSP:
SilentPrintServlet
Explains how to print silently via Servlet/Browser.
Extra jars needed:
  • servlet.jar
Servlets/JSP:
HelloWorld.jsp
Generates a simple 'Hello World' file from a JSP page
Servlets/JSP:
ANT script (all examples):
Manipulating existing PDF documentsHow-to copy/manipulate existing PDF documents.
Sections
Examples
TwoOnOne
Combines 2 pages on 1
Input:
Output:
AddWatermarkPageNumbers
Adds pagenumbers and a watermark to an existing document
Input:
Output:
EncryptorExample
Encrypts an existing PDF file
Input:
Output:
Concatenate
Concatenates existing PDF files
Argument(s):
  • ChapterSection.pdf
  • Destinations.pdf
  • SimpleAnnotations1.pdf
  • concatenated.pdf
Input:
Output:
ANT script (all examples):
Frequently Asked QuestionsThis is a basic technical reference that answers some frequently asked questions.
Sections
Examples
Measurements
Demonstrates the measurement system (points, inches, centimeters)
Output:
NewPage
Shows how to go to a new page or insert a blank page
Output:
iTextVersion
Shows the iText version that was used to generate this example
Output:
PdfVersion
Change the PDF version of a document
Output:
ANT script (all examples):
Go to top of the page
Part II: Using High Level Objects
Basic Text ObjectsSome basic text objects that are used in iText.
Sections
Examples
Chunks
Demonstrates some Chunk functionality
Output:
DifferentFonts
A Paragraph can contain text in different fonts
Output:
Paragraphs
Demonstrates some Paragraph functionality
Output:
SpaceWordRatio
Space Word Ratio
Output:
ParagraphAttributes
Demonstrates some more Paragraph functionality
Output:
Phrases
Demonstrates the different constructors of class Phrase
Output:
NegativeLeading
Shows the effect of a negative leading
Output:
SymbolSubstitution
Demonstrates how special characters are substituted by Symbols with Phrase.getInstance
Output:
FontSelection
Selects the appropriate fonts that contain the glyphs needed to render text correctly
Output:
Lists
Demonstrates some List functionality
Output:
FancyLists
Demonstrates some List with Roman numerals, Greek letters, zapfdingbats,...
Output:
ANT script (all examples):
The Chunk ObjectDescribes the functionality of the Chunk object.
Sections
Examples
Lines
Demonstrates how to add lines under, through,... a Chunk
Output:
SubSupScript
Demonstrates the use of sub- and superscript
Output:
Background
How to change the background color of a Chunk
Output:
ChunkColor
Changing the color of a Chunk
Output:
Rendering
Some special rendering functionality
Output:
Skew
Skewing Chunks
Output:
Generic
Using the Generic tag to add styles
Output:
Glossary
Other use of the Generic tag: register keywords for a glossary
Output:
Width
How to measure and scale the width of a Chunk
Output:
EndOfLine
What happens when the end of the line is reached?
Output:
SplitChar
Defining Split Characters
Output:
Hyphenation
Using auto-hyphenation
Extra jars needed:
  • itext-hyph-xml.jar
Output:
ANT script (all examples):
Anchors, Actions and AnnotationsDeals with all the RemoteGoto, LocalGoto, Action, Annotation,... functionality
Sections
Examples
LocalGoto
Creates a document with a local goto and a local destination
Output:
LocalDestination
Creates a document that jumps to a local destination upon opening
Output:
RemoteGoto
Creates two documents with links to eachother and to an external URL
Output:
AHref
Using the Anchor object
Output:
NamedActions
Creates a document with named actions.
Output:
JavaScriptAction
Creates a document with a Javascript action.
Output:
Actions
Creates a document with some goto actions
Output:
ChainedActions
Creates a document with chained actions.
Output:
OpenApplication
Creates a document with a link to open an external application.
Argument(s):
  • C://windows/
Output:
SimpleAnnotations
Creates two documents with different types of annotations
Input:
Output:
Annotations
Creates a document with some PdfAnnotations
Input:
Output:
ANT script (all examples):
Viewerpreferences, Pagelabels, Optional Content and BookmarksDeals with all the PDF Viewerpreferences, Bookmarks, Outlines, Destinations,... functionality
Sections
Examples
ViewerPreferences
Creates five versions of the same document, but with different viewerpreferences
Output:
PageLabels
Creates a document with pagelabels
Output:
Layers
Creates a document with text in different layers
Output:
Bookmarks
Creates a document with Bookmarks for every new Paragraph that is added
Output:
Destinations
Creates a document with destinations that can be called from Bookmarks
Output:
OutlineActions
Creates a document with external destinations or actions that can be called from Bookmarks
Output:
ChapterSection
Creates a document with Chapters and Sections (automatic outlines)
Output:
HtmlIndex
Creates an HTML index of a file that has bookmarks
Output:
ANT script (all examples):
ImagesDeals with all types of images that are supported by iText
Sections
Examples
Images
Adds different formats of images to a document.
Input:
Output:
RawData
Using raw image data to construct an Image object.
Input:
Output:
AwtImage
Using a java.awt.Image object to construct an Image object.
Input:
Output:
ImagesAlignment
Alignment and wrapping of images.
Input:
Output:
ImageSequence
Adds images to a document, once respecting the order in which they were added, once in the default order.
Input:
Output:
AbsolutePositions
Adding an Image at absolute positions.
Input:
Output:
Scaling
Scaling images.
Input:
Output:
DvdCover
Make a DVD Cover.
Argument(s):
  • dvdcover.pdf
  • My Sunflower Movie
  • 808080
  • sunflower-front.jpg
  • sunflower-back.jpg
Input:
Output:
Rotating
Rotating images.
Input:
Output:
AnnotatedImage
images and annotations.
Input:
Output:
ImageChunks
Images wrapped in a Chunk.
Input:
Output:
ImageMasks
Applying a mask to an image.
Input:
Output:
ANT script (all examples):
Selected examples: EPS, TIFF, BarcodesSelected examples: Embedding PostScript, importing TIFF files, Barcodes
Sections
Examples
Tiff2Pdf
Converts some tiff files to PDF
Argument(s):
  • 12.tif
  • 338814-00.tif
  • even.tif
  • odd.tif
Input:
Output:
OddEven
Combines 2 tiffs, one with odd, another with even pages into 1 combined PDF
Argument(s):
  • odd.tif
  • even.tif
  • combined.pdf
Input:
Output:
Barcodes
List with different barcodes
Output:
ExampleEAN128
Example barcode ean128
Output:
ExamplePDF417
Example barcode pdf417
Output:
ANT script (all examples):
TablesHow to organize text and data in tables with iText
Sections
Examples
MyFirstTable
Use a PdfPTable to add a table to a PDF document
Output:
TableWidthAlignment
Changing the width and the alignment of the complete table
Output:
TableSpacing
Defining the spacing between the table and other content
Output:
CellWidths
Changing the widths of columns
Output:
DefaultCell
Using getDefaultCell to change the default style
Output:
NestedTables
Using nested tables
Output:
ImageCell
Adding an Image to a table
Input:
Output:
CellHeights
Playing with heights of PdfPCells
Output:
CellAlignment
Changing the alignment of the contents of a PdfPCell
Output:
CellPaddingLeading
Changing the padding and the leading of the contents of a PdfPCell
Output:
CellColors
Using some Rectangle methods on PdfPCell
Output:
TableBorders
Demonstrates different borderstyles
Output:
AddBigTable
A very big table added with document.add()
Output:
SplitRows
Add a table to a PDF with document.add() and if the cell doesn't fit, the row is split in two parts
Output:
ANT script (all examples):
PdfPTableSome extra PdfPTable functionality
Sections
Examples
WriteSelectedRows
Demonstrates the writeSelectedRows method
Output:
Tables
Adds a table to an absolute position
Output:
SplitTable
Demonstrates how to split a Table in two sections of columns
Output:
FragmentTable
Break one large Table up into different smaller tables with the same header
Argument(s):
  • 50
Output:
CellEvents
Demonstrates what one can do with cell events
Input:
Output:
TableEvents1
Demonstrates what one can do with table events
Output:
TableEvents2
Demonstrates what one can do with table events (cells with colspan > 1)
Output:
FloatingBoxes
Demonstrates how to simulate cellspacing as in HTML
Output:
VerticalTextInCells
Demonstrates how to add vertical text in a cell
Output:
ANT script (all examples):
Alternatives for PdfPTableSome alternative ways to create a Table
Sections
Examples
JTable2Pdf
Print a Swing jTable to a PDF file
Output:
OldTable
Generates a table with the Table object
Output:
LargeCell
Trying to fit a Cell on a page
Output:
TablePdfPTable
Generates a table with the TableAttributes object
Output:
PaddingBorders
Generates tables with different padding, bordercolors and borderwidths
Output:
MyFirstTable
Generate a table with the Table/PdfPTable object
Output:
SpecificCells
Adding Cells at specific positions
Output:
RepeatingTable
Shows how a table is split if it doesn't fit the page
Output:
NestedTables
Nested tables
Output:
TableWithImage
Generate a table with the Table object containing Images
Input:
Output:
ANT script (all examples):
ColumnTextHow to organize text and data in columns with iText
Sections
Examples
Column
Defining a simple single object ColumnText object
Output:
ColumnSimple
Adding phrases to a simple ColumnText object
Output:
ColumnObjects
Adding different objects to a simple ColumnText object
Input:
Output:
ColumnIrregular
Defining an irregular ColumnText object
Input:
Output:
MultiColumnSimple
Defining a simple MultiColumnText object
Output:
MultiColumnR2L
Defining a MultiColumnText object that adds its columns from right to left
Output:
MultiColumnIrregular
Defining an irregular MultiColumnText object
Output:
ANT script (all examples):
Go to top of the page
Part III: Fonts
The Font objectsDescribes the different Font objects in iText.
Sections
Examples
StandardType1Fonts
Sums up the 14 Standard Type 1 Fonts
Output:
FontFactoryType1Fonts
Sums up the 14 Standard Type 1 Fonts (using the FontFactory)
Output:
TrueType
Using a True Type font
Output:
FullFontNames
Retrieving the full font name
Output:
ListEncodings
Asking the font for its available encodings
Output:
FontEncoding
Using a True Type font that will be embedded in the PDF
Output:
UnicodeExample
Using BaseFont.IDENTITY_H as 'encoding'
Output:
EncodingFont
Using an encoding to display characters from other alphabets
Output:
ANT script (all examples):
Font characteristicsChanging the style of a Font.
Sections
Examples
WidthHeight
Asking a font for the width/height of a textstring
Output:
FixedFontWidth
Changing the width of the font glyphs
Output:
FontStylePropagation
Explains the mechanism of Font Style Propagation
Output:
ExtraStyles
Demonstrates how to underline or strike through text
Output:
FontColor
Shows how to change the color of a font
Output:
RightToLeft
Writing text from left to right
Output:
ComplexText
Writing text from left to right at absolute positions
Output:
Vertical
Writing vertical text
Extra jars needed:
  • iTextAsian.jar
Output:
ANT script (all examples):
Getting fontsOverview of the different types of fonts supported by iText.
Sections
Examples
TrueType
Using a True Type font
Output:
RegisterFont
Registering Fonts with the FontFactory
Output:
FontFactoryStyles
Changing the style of a fontfactory font
Output:
UsingFontFactory
Sums up the Fonts that are available in some standard font directories on your system
Output:
OpenTypeFont
Using an Open Type Font with Compact Font Format (CFF) data only (no true type outlines)
Input:
Output:
ChineseJapaneseKorean
Using CJK Fonts
Extra jars needed:
  • iTextAsian.jar
Output:
ANT script (all examples):
Go to top of the page
Part IV: Direct Content
Direct ContentAdd content directly to the PDF file using the PdfContentByte class.
Sections
Examples
Layers
Explains the concept of PdfContentByte layers in iText
Input:
Output:
Templates
Using templates
Output:
TemplateImages
Templates used as image
Output:
ANT script (all examples):
Coordinate SystemsCoordinate Systems - changing the Current Transformation Matrix (CTM)
Sections
Examples
XandYcoordinates
Puts some marks at specific X and Y coordinates; connects the marks with a line and puts some text next to the marks
Output:
UpsideDown
Same example as above, but now the origin is in the upper left corner
Output:
AffineTransformation
Same example as above, but now the X and Y coordinates are scaled
Output:
Transformations
Add a template using different transformation matrices
Output:
TransformImage
Add an image using different transformation matrices
Input:
Output:
ANT script (all examples):
Graphics StateAdd graphics directly to the PDF file using the PdfContentByte class.
Sections
Examples
Literal
Writing PDF Syntax directly to iText
Output:
State
Changing the Graphics State with saveState and restoreState
Output:
GState
Changing the Graphics State with setGState
Output:
Circles
Draws some concentric circles
Output:
Shapes
Draws some shapes
Output:
ANT script (all examples):
ColorsColors, Transparency, Spotcolors, Patterns and Shading.
Sections
Examples
SpotColors
Using spotcolors.
Output:
Pattern
A stencil example (you define a shape and a default color).
Output:
Patterns
Colored patterns.
Input:
Output:
Shading
Shading.
Output:
ShadingPattern
Shading pattern.
Output:
Transparency
Reproducing PLATE 16 on p1053 in the PDF Reference Manual
Output:
Groups
Making images transparent.
Output:
SoftMask
Making images transparent.
Input:
Output:
ANT script (all examples):
TextAdd text content directly to the PDF file using the PdfContentByte class.
Sections
Examples
Text
Adding text at absolute positions
Output:
Logo
Draws the iText logo
Output:
ANT script (all examples):
Page EventsAdd content directly to the PDF file using the PdfContentByte class.
Sections
Examples
EndPage
Headers and footers in an EndPage event
Output:
PageNumbersWatermark
Making a document with a header containing 'page x of y' and with a watermark on every page.
Input:
Output:
Bookmarks
Using paragraph events
Output:
Events
Using PageEvents
Extra jars needed:
  • crimson.jar
Input:
Output:
ANT script (all examples):
Optional ContentAdd optional content to a PDF file.
Sections
Examples
OrderedLayers
Ordering Optional Content Groups
Output:
ContentGroups
Grouping Optional Content
Output:
OptionalContent
Changing the visibility using an Action
Input:
Output:
NestedLayers
Nesting Optional Content
Output:
Automatic
Automatic grouping and nesting of Optional Content
Output:
Layers
Zooming and radio groups
Output:
ANT script (all examples):
Graphics2DIf you don't want to read all the chapters on PDF syntax, just use the JAVA API
Sections
Examples
G2D
A Simple Graphics2D example
Output:
ArabicText
Drawing arabic text using the Graphics2D object
Output:
JFreeChartExample
Some JFreeChart examples
Extra jars needed:
  • jfreechart.jar
  • jcommon.jar
Output:
ANT script (all examples):
Go to top of the page
Part V: Interactive Features (AcroForms)
Under Construction
Go to top of the page
Part VI: the iText Toolbox explained
Under Construction
Go to top of the page
Part VII: RTF
Rich Text FormatHow-to generate RTF documents using iText.
Sections
Examples
HelloRtf
Generates a simple 'Hello World' RTF file
Argument(s):
  • World
Output:
RtfSpecialFont
Special fonts
Output:
RtfWithHeadersFooters
Headers/footers and page numbers
Output:
RtfTOCandCellborders
Table of contents and cell borders
Output:
RtfTest
The TestSuite used to test RtfWriter2 functionality
Input:
Output:
ANT script (all examples):
Go to top of the page
Part VIII: HTML
Generating HTML with iTextHow-to generate a HTML documents with iText
Sections
Examples
HelloHtml
Generates a simple 'Hello World' HTML file
Output:
HelloWorldMeta
Generates an HTML file with metadata
Output:
JavaScriptAction
Generates an HTML file with JavaScript
Output:
ImagesURL
Adds images to an HTML file using the complete URL.
Output:
ANT script (all examples):
Go to top of the page
Part IX: XML
Under Construction
Go to top of the page
Part X: Under the hood
Under Construction
Go to top of the page



Amazon books:
amazon.co.uk-link