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.
import java.awt.Color;
import java.io.FileOutputStream;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class iTextExample
{
public static void main (String[] args)
{
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("iTextExample.pdf"));
BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);
HeaderFooter footer = new HeaderFooter(
new Phrase("This is page: ", new Font(bf_courier)), true);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);
HeaderFooter header = new HeaderFooter(
new Phrase("This is a header without a page number", new Font(bf_symbol)), false);
header.setAlignment(Element.ALIGN_CENTER);
document.setHeader(header);
document.open();
int y_line1 = 650;
int y_line2 = y_line1 - 50;
int y_line3 = y_line2 - 50;
PdfContentByte cb = writer.getDirectContent();
cb.setLineWidth(0f);
cb.moveTo(250, y_line3 - 100);
cb.lineTo(250, y_line1 + 100);
cb.moveTo(50, y_line1);
cb.lineTo(400, y_line1);
cb.moveTo(50, y_line2);
cb.lineTo(400, y_line2);
cb.moveTo(50, y_line3);
cb.lineTo(400, y_line3);
cb.stroke();
cb.beginText();
cb.setFontAndSize(bf_helv, 12);
String text = "Sample text for alignment";
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, y_line1, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, y_line2, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, y_line3, 0);
cb.endText();
document.newPage();
document.add(new Paragraph("Hello World, paragraph 1"));
document.add(new Paragraph("Hello World, paragraph 2"));
cb.beginText();
cb.setFontAndSize(bf_times, 14);
cb.setTextMatrix(100, 400);
cb.showText("Text at position 100, 400.");
cb.endText();
document.close();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}
OtherOpenSourceProjectsFaq CategoryCodeSamples CodeBarn
|