iText HTML Generation in Java

Monday, July 27, 2009

iText is a freely available Java library from Lowagie.com (see Resources). The iText library is powerful and supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. You can choose from a variety of fonts to be used in the document. Also, the structure of iText allows you to generate any of the above-mentioned types of documents with the same code.

The iText library contains classes to generate PDF text in various fonts, generate tables in PDF document, add watermarks to pages, and so on. There are many more features available with iText. It would not be possible to demonstrate all of them in a single article. We will cover the basics required for PDF generation.

For this application you need following jars file
Text-2.1.6.jar
iText-rtf-2.1.6.jar
Text-rups-2.1.6.jar

HTMLWritter.java


/**
* File Name : HTMLWritter.java
* Created By : Nagaraju v
* Created Date : Jun 19, 2009
* Purpose :
*/
package com.raj.iTextPDF;

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.html.HtmlWriter;

/**
* @author nagarajuv
*
*/
public class HTMLWritter {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("--> resulting HTML: HelloWorldHTMLMultiple");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2: we create a writer
HtmlWriter.getInstance(document,new FileOutputStream("HelloWorldHTMLMultiple.htm"));

// step 3: we open the document
document.open();

// step 4: we add a paragraph to the document
Font font = new Font(Font.COURIER, 10, Font.BOLD);
font.setColor(new Color(0xEE, 0xEE, 0xEE));
Chunk fox = new Chunk("HTML Writer", font);
float superscript = 8.0f;
fox.setTextRise(superscript);
fox.setBackground(new Color(0xa5, 0x2a, 0x2a));
Chunk jumps = new Chunk(" Example ", new Font());
Chunk dog = new Chunk("Nagaraju", new Font(Font.TIMES_ROMAN,
14, Font.ITALIC));
float subscript = -8.0f;
dog.setTextRise(subscript);
dog.setUnderline(new Color(0xFF, 0x00, 0x00), 3.0f, 0.0f, -5.0f
+ subscript, 0.0f, PdfContentByte.LINE_CAP_ROUND);
document.add(fox);
document.add(jumps);
document.add(dog);
document.add(new Paragraph(" Paaaaaaaaaaragraph"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

// step 5: we close the document
document.close();
}
}

Enjoy with this is nice example
Image Hosted by ImageShack.us
Image Hosted by ImageShack.us

0 comments: