DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Simple PDF Creation With IText
Simple class which illustrates usage of iText to create a PDF file.
package testrecorder;
import java.io.FileOutputStream;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfWriter;
/**
*
* @author ditch182
*/
class createPDF {
private static Font catFont = new Font(Font.FontFamily.HELVETICA, 18);
private static Font redFont = new Font(Font.FontFamily.HELVETICA, 12);
private static Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
private Object thistest;
public createPDF(Test test) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(test.getControlNo().toString() + ".pdf"));
document.open();
addMetaData(document, test);
addContent(document, test);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void addMetaData(Document document, Test thisTest) {
document.addTitle(thisTest.getControlNo().toString());
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Richard Hibbitts");
document.addCreator("Automated Test Recorder");
}
private void addContent(Document document, Test thisTest) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");
// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));
subPara = new Paragraph("Subcategory 2", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));
// Add a little list
//createList(subCatPart);
// Add a small table
//createTable(subCatPart);
// Now a small table
// Now add all this to the document
document.add(catPart);
// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");
// Second parameter is the number of the chapter
catPart = new Chapter(new Paragraph(anchor), 1);
subPara = new Paragraph("Subcategory", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("This is a very important message"));
// Now add all this to the document
document.add(catPart);
}
}




