# Tutorial: iText by Example

## Hello World

Creating a document in 5 steps.:
When I learned my first programming language (some old BASIC dialect on a TI-99/4A Home Compiter), one of the first programs I made was a 'Hello World' example. The year was 1982, my age: 12. Now, more than 20 years later, I am still writing the same program: a standalone example that prints 'Hello World', this time not on the cyan colored Texas Instruments screen, but in a PDF document file.
This example shows you the 5 basic steps you have to take for every new PDF document you are creating from scratch with iText:

- Step 1: Create an instance of com.lowagie.text.Document:
  Document document = new Document();
- Step 2: Create a Writer (for instance com.lowagie.text.pdf.PdfWriter) that listens to this document and writes the document to the OutputStream of your choice:
  PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
- Step 3: Open the document:
  document.open();
- Step 4: Add content to the document:
  document.add(new Paragraph("Hello World"));
- Step 5: Closes the document:
  document.close();

Example: java com.lowagie.examples.general.HelloWorld
Generates a simple 'Hello World' PDF file: see HelloWorld.pdf
In the following sections, we will take a closer look into each step.
Go to top of the page
step 1: the Document object:
Class com.lowagie.text.Document has 3 constructors:

    public Document();
    public Document(Rectangle pageSize);
    public Document(Rectangle pageSize,
       int marginLeft,
       int marginRight,
       int marginTop,
       int marginBottom);

The first constructor calls the second one, with PageSize.A4 as parameter. The second constructor calls the third one, with 36 as value for each margin.
Pagesize
The default PageSize is DIN A4 (iText is a European library; A4 is the most common format overhere), but for your convenience class com.lowagie.text.PageSize offers you a very complete list of standard PageSizes: A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA and FLSE.
Example: java com.lowagie.examples.general.DefaultPageSize
Generates a PDF document with the default page size and some other predefined standard pagesizes: see DefaultPageSize.pdf
Most these standard pageSizes are in PORTRAIT-format. To create a document in landscape format, just make the height smaller than the width. With the standard pagesizes all you have to do is rotate() the Rectangle:
Document document = new Document(PageSize.A4.rotate());
Example: java com.lowagie.examples.general.LandscapePortrait
Generates a PDF document with the first page in Lanscape; the second page in Portrait: see LandscapePortrait.pdf
Of course you aren't limited to this list. You can create pages of any size you want. (Although there is a maximum of 200 by 200 inches; 45 by 45 inches for Acrobat 3.0 compatibility). With the PageSize, there is also the possibility to define a backgroundcolor. In the following example, we create a long, narrow document with a yellowish backgroundcolor:
Example: java com.lowagie.examples.general.CustomPageSize
Generates a PDF document with a custom pagesize and backgroundcolor: see CustomPageSize.pdf
If you want to know more about the measurement unit, see the FAQ.
Margins
In step 4, you will be adding content to the document. If you use high level objects, you needn't worry about margins and page layout. The high level objects take care of that for you. Of course you will have to define the margins first. That is: if you want other margins than the standard 36 points (half an inch).
You can also change the margins while you are adding content. Remark that the changes will only be noticed on the NEXT page. If you want the margins mirrored (odd and even pages), you can do this with this method: setMarginMirroring(true).
Example: java com.lowagie.examples.general.Margins
Demonstrates the margin functionality: see Margins.pdf
If you want to know more about the measurement unit, see the FAQ.
Why getPagenumber doesn't work.
Class Document is all about content, not about presentation. Different writers can listen to the same Document object, so it makes absolutely no sense asking the Document object for its current pagenumber. Which number would the Document have to return? The pagenumber of the PDF representation or the one of the HTML (this makes even less sense)? In short: you should ask the specific writer for the pagenumber, NOT the Document object.
Go to top of the page
step 2: the Writer object:
Once our Document is created, we can create one or more instances of writers that listen to this document. All writers should be derived from the abstract class com.lowagie.text.DocWriter. For the moment there are three kinds of writers supported:

PdfWriter
  Generates documents in the Portable Document Format
RtfWriter
  Generates documents in RTF. Read more about this in the chapter 'RTF'
HtmlWriter
  Generates documents in HTML. This writer was initially written for debugging purposes (see Generating HTML with iText).

All these Writers are derived from the abstract class DocWriter. The constructors of the writer-classes are protected. You can only create an instance with a static method: PdfWriter.getInstance, RtfWriter2.getInstance or HtmlWriter.getInstance:
public static xxxWriter getInstance(Document document, OutputStream os) throws DocumentException
(xxx being Pdf, Rtf or Html). For instance:
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
It may surprise you that there seems to be 'no object'. You probably expect something like this:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
Actually there IS a writer object in both cases, but in simple applications you will never need it.
The first parameter of the getInstance method is the com.lowagie.text.Document object created in step 1. The second parameter can be any java.io.OutputStream object. In this tutorial we always use a java.io.FileOutputStream, but you can also use a java.io.ByteArrayOutputStream to create PDF files in memory or a javax.servlet.ServletOutputStream (see iText in a Web Application). You can even write output to System.out if you want to (but it's not very nice to look at):
Example: java com.lowagie.examples.general.HelloSystemOut
Writes PDF output to System.out: see HelloWorld.txt
Remark that you can have different writers listening to the same document at the same time. For instance: if you want to sent a PDF to a browser directly from a servlet, but keep a copy of the PDF in a file on the server, you could invoke getInstance twice with the same document-object, but a different output stream.
At Ghent University, we write sheets with information on Study Programmes for the Course Catalogue in 2 versions: one in HTML for the website and one in PDF for printing. This is done simultaneously using the same source code, even using the same document object. The only difference is that at some point, we pause the PdfWriter and we add a link from the HTML page to the PDF document. This is demonstrated in the next example:
Example: java com.lowagie.examples.general.HelloWorldMultiple
Writing to different writers at the same time; using pause() and resume(): see HelloWorldPdf.pdf HelloWorldRtf.rtf HelloWorldHtml.html
Go to top of the page
step 3: opening the document:
It is important to call Document.open(). iText will throw an exception if you try adding content before the document is open. This is a design choice. There are several initialisations that should be done BEFORE you open a Document. Most of them will be covered elsewhere in this tutorial. We have a quick glance at two of them now:
Simple encryption
if you want to generate an encrypted document, you should call setEncryption BEFORE opening the Document-object. If you try setting the encryption after Document.open(), a DocumentException will be thrown with the message Encryption can only be added before opening the document.
Example: java com.lowagie.examples.general.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': see HelloEncrypted.pdf
metadata
if we look at the Document Properties in Acrobat (under File in the menu), we see that several fields are empty by default:
Only two metadata methods are called by default: addProducer() and addCreationDate(). It's possible to change the producer and creation date, but you shouldn't.
We'll only document the methods to change the rest of the metadata in the 'Description' area:

Title: | addTitle(java.lang.String)
Author: | addAuthor(java.lang.String)
Subject: | addSubject(java.lang.String)
Keywords: | addKeywords(java.lang.String)
Application: | addCreator(java.lang.String)

This is a small code sample:

    document.addTitle("Hello World example");
    document.addAuthor("Bruno Lowagie");
    document.addSubject("This example explains how to add metadata.");
    document.addKeywords("iText, Hello World, step 3, metadata");
    document.addCreator("My program using iText");

Compare the result on this screenshot:
Example: java com.lowagie.examples.general.HelloWorldMeta
Adding metadata to a new PDF document: see HelloWorldMeta.pdf
If you study the API, you will see there is also a generic method addHeader(java.lang.String, java.lang.String). That method has no effect on PdfWriter, but you can use it with HtmlWriter.
Go to top of the page
step 4: adding content:
There are different ways to add content to a PDF file. The easiest way is to use high level objects such as Chunk, Phrase, Paragraph,... It is very important to realize that not all types of these objects are supported in all types of writers. For instance: the PdfPTable-object is only supported in PDF, not in RTF or HTML. If you add a PdfPTable to a Document, the listening RtfWriters or HtmlWriters will ignore this.
If you don't need RTF or HTML, you can also add content at absolute positions. A lot of the standard PDF syntax is supported in iText, so you can do some very powerful things with the library.
Adding content using the PdfGraphics2D-object (extends java.awt.Graphics2D) is also possible. You can read more about this elsewhere in the tutorial.
Go to top of the page
step 5: closing the document:
Closing the document is very important, because it flushes and closes the outputstream to which the writer is writing. The close-method is called in the finalize-method, but you shouldn't count on that. You should always close the document yourself!
Go to top of the page
Amazon books:
amazon.co.uk-link
amazon.co.uk-link
amazon.co.uk-link