Document document = new Document();
document.open();
It is very important to do any changes to page size or margins etc. BEFORE opening the document. Otherwise, the defaults will be used for the first page and any alterations will only be effective from the second page onwards.
//Correct
Document document = new Document(PageSize.A5, 32 ,76 ,100, 200);
document.open();
//Wrong
Document document = new Document();
document.open();
document.setMargins(32, 76, 100, 200);
The reason for this is many document types keep meta data including page setup and version information in the file header which is created before the document itself.
The meta data of a PDF document can be set by using the accessor methods within the Document class. This includes:
- addTitle("Title")
- addSubject("Subject")
- addKeywords("Metadata, iText")
- addCreator("Lilpinkthings Program")
- addAuthor("Lilpinkthing")
- addHeader("ValidFrom, 0")
Don't change the producer and creation date meta values. They will tell you what version of iText was used to create the file if support is needed later on. These values must be set before opening the document.
It is possible also possible to tell a PdfWriter which pdf version to use - the default is 1.4.
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Output.pdf");
writer.setPdfVersion(PdfWriter.VERSION_1_6);
document.open();
Again this MUST be called before opening the document, because it goes into the header file.
This gives us 6 basic steps of PDF creation which look like this:
- Create a Document
- Create a PdfWriter and associate the Document and an OutputStream with it
- Set all meta data, version and page setup information
- Open the Document
- Add content
- Close the document
Code Example:
Document document = new Document(); //step 1
PdfWriter.getInstance(document, new FileOutputStream("Output.pdf") ); //step 2
document.addKeywords("hello, world, pdf, iText"); //step 3
document.addAuthor("lilpinkthing"); //step 3
document.open(); //step 4
document.add(new Paragraph("Hello there")); //step 5
document.close(); //step 6
The document.close() line here is VERY important. If you forget to add this you will probably get some crazy error similar to "There was an error opening this document. The file is damaged and could not be repaired." Don't panic, just close the document.
In-depth iText information can be found in Bruno Lowagie's excellent book iText In Action http://www.manning.com/lowagie2/
No comments:
Post a Comment