Friday, February 3, 2012

PDF In Android

Here is an application to create a pdf in android using iText file
First download the iText jar file the iTextxtra jar is not needed and then use the following code to create a table view pdf


package com.myapp.qr;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFCreator {
public static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
public static ArrayList headings = new ArrayList();
public static ArrayList contents = new ArrayList();

public static void create() {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
// addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void addMetaData(Document document) {
document.addTitle("Bill");

}

private static void addContent(Document document) throws DocumentException {
createTable(document);

}

private static void createTable(Document subCatPart)
throws DocumentException {
PdfPTable table = new PdfPTable(3);

for (int i = 0; i < headings.size(); i++) {
String heading = headings.get(i);
PdfPCell c1 = new PdfPCell(new Phrase(heading));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

}

table.setHeaderRows(1);

for (int i = 3; i < contents.size(); i++) {
String conStr = contents.get(i);

table.addCell(conStr);
}

subCatPart.add(table);

}

}

No comments:

Post a Comment