Generating complex type PDF in JAVA using iText

Last days I was searching for generating a PDF in android using iText, I found some of posts but all these posts were containing some sort of basic hello PDF reports and my requirements was to generate a complex type PDF for client reporting purpose.

So I came across the solution and want to share the source code and stuff for audience time saving purpose. Hope this helps some body :).

Note: This source code works on any java platform and not specific to Android only.



The PDF contains almost all components such as drawing tables, images, lines, different types alignments, strike through text, underline texts, different fonts and page division etc. Looks like:

PDF using iText
You can customize the below code according to your own needs.

GeneratePDF.java



public class GeneratePDF {
 
    public static String FILE = "D:/" + getUniqueFileName();
    private static Font largeBold = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
    private static Font mediumNormal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
    private static Font smallNormal = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.BOLD);
 
    static PdfWriter writer;
    static Document document;
    static PdfPCell table_cell;

    public GeneratePDF(){
        try {
            Log.v("GeneratePDF", "GeneratePDF Started...");
            document = new Document(PageSize.A4, 60, 60, 60, 60);
            writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));
            document.open();
         
            addMetaData(document);       
            addTitlePage(document);
         
            document.close();
            Log.v("GeneratePDF Called", "GeneratePDF Ended...");

        } catch (Exception e) {
            e.printStackTrace();
        }
   }
 
    private static void addMetaData(Document document) {
        document.addTitle("Android");
        document.addSubject("Loan Calculator");
        document.addKeywords("Java, Android");
        document.addAuthor("Naeem Shah");
        document.addCreator("Naeem Shah");
    }

    private static void addTitlePage(Document document) throws DocumentException, IOException {
        Paragraph preface = new Paragraph();
        // Lets write a big header
        preface.add(new Paragraph("Your Main Title Here.", largeBold));
     
        // Add empty line
        addEmptyLine(preface, 4);
     
        // Will create: Report generated by: _name, _date
        //preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), smallNormal));
     
        document.add(preface);
     
        String imagePath = "D:/logosmall.png";

        Image image = null;
        try {
            image = Image.getInstance(imagePath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
     
        image.setAbsolutePosition(450f, 710f);
        document.add(image);
     
        createTable1();
     
        Paragraph volkswagen = new Paragraph();
        volkswagen.add(new Paragraph("naeemgik.blogspot.com", largeBold));
        addEmptyLine(volkswagen, 2);
        document.add(volkswagen);
     
            
        PdfContentByte cb = writer.getDirectContent();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 24);
        cb.moveTo(60, 580);
        cb.lineTo(400, 580);
        cb.setLineWidth(0.80f);
        cb.stroke();
     
        Paragraph pricePara = new Paragraph();
     
        PdfPTable priceTable = new PdfPTable(3);
        priceTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        priceTable.setWidthPercentage(70);
        priceTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        priceTable.addCell(new Paragraph("PRICE", mediumNormal));
        priceTable.addCell(new Paragraph("50000" + " AZN", mediumNormal));
        priceTable.addCell(new Paragraph("55000" + " AZN", new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.STRIKETHRU)));
     
        priceTable.addCell(new Paragraph("DISCOUNT", mediumNormal));
        priceTable.addCell(new Paragraph("5", mediumNormal));
        priceTable.addCell("");
      
        pricePara.setAlignment(Element.ALIGN_LEFT);
        pricePara.setIndentationLeft(0);
        pricePara.add(priceTable);
        addEmptyLine(pricePara, 2);
        document.add(pricePara);
     
        PdfContentByte cb1 = writer.getDirectContent();
        cb1.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 30);
        cb1.moveTo(60, 515);
        cb1.lineTo(400, 515);
        cb1.setLineWidth(1.5f);
        cb1.stroke();
     
        Paragraph loanPara = new Paragraph();
     
        PdfPTable  loanTable = new PdfPTable(3);
        loanTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        loanTable.setWidthPercentage(70);
        loanTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        loanTable.addCell(new Paragraph("LOAN_AMOUNT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("300" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("AMOUNT_OF_INTEREST", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("300"+ " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("DURATION", mediumNormal));
        table_cell = new PdfPCell(new Paragraph(ShowCalculation.calcMonths + " Months", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell("\n");
        table_cell = new PdfPCell(new Paragraph("\n", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("MONTHLY_FEE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("20"+ " AZN / " + ShowCalculation.lastMonthFee + " AZN (last Month)", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanTable.addCell(new Paragraph("INIT_PAYMENT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("50"+ " AZN",  new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.UNDERLINE)));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        loanTable.addCell(table_cell);
     
        loanPara.setAlignment(Element.ALIGN_LEFT);
        loanPara.add(loanTable);
        addEmptyLine(loanPara, 2);
        document.add(loanPara);
     
        PdfContentByte cb2 = writer.getDirectContent();
        cb2.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 20);
        cb2.moveTo(60, 385);
        cb2.lineTo(400, 385);
        cb2.setLineWidth(0.80f);
        cb2.stroke();
     
        Paragraph detailPara = new Paragraph();
     
        PdfPTable  detailTable = new PdfPTable(3);
        detailTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        detailTable.setWidthPercentage(70);
        detailTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        detailTable.addCell(new Paragraph("FIRST_INSTALLMENT", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("20"+ " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("CMPR_INSURANCE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("10" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("BANK_FEE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("10" + " AZN / ", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("CMP_INSURANCE", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("500" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
     
        detailTable.addCell(new Paragraph("DYP_REG", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("500" + " AZN", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        detailTable.addCell(table_cell);
      
        detailPara.setAlignment(Element.ALIGN_LEFT);
        detailPara.add(detailTable);
        addEmptyLine(detailPara, 2);
        document.add(detailPara);
     
        PdfContentByte cb3 = writer.getDirectContent();
        cb3.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 10);
        cb3.moveTo(60, 270);
        cb3.lineTo(400, 270);
        cb3.setLineWidth(0.25f);
        cb3.stroke();
     
        Paragraph gracePeriodPara = new Paragraph();
     
        PdfPTable  gracePeriodTable = new PdfPTable(3);
        gracePeriodTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        gracePeriodTable.setWidthPercentage(70);
        gracePeriodTable.setHorizontalAlignment(Element.ALIGN_LEFT);
     
        gracePeriodTable.addCell(new Paragraph("GRACE_PERIOD", mediumNormal));
        table_cell = new PdfPCell(new Paragraph("0 Months", mediumNormal));
        table_cell.setColspan(2);
        table_cell.setBorder(0);
        gracePeriodTable.addCell(table_cell);
     
        gracePeriodPara.setAlignment(Element.ALIGN_LEFT);
        gracePeriodPara.add(gracePeriodTable);
        addEmptyLine(gracePeriodPara, 1);
        document.add(gracePeriodPara);
     
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }
 
    private static String getUniqueFileName() {
         String uniqueFileName = "";
         Date date = new Date();
         uniqueFileName = date.toString();
         uniqueFileName = uniqueFileName.replace(':', ' ');
         uniqueFileName = uniqueFileName.replace('+', ' ');
         uniqueFileName += " Report";
      
         return uniqueFileName + ".pdf";
    }
 
    private static void createTable1() throws DocumentException{
       Paragraph personalInfo = new Paragraph();
     
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(65);
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
     
        table.addCell(new Paragraph(getCurrentDate(), smallBold));
        table.addCell(new Paragraph("Date", smallBold));
     
        table.addCell(new Paragraph("PHONE_NUMBER", smallNormal));
        table.addCell(new Paragraph("Phone", smallNormal));
     
        table.addCell(new Paragraph("FAX_NUMBER", smallNormal));
        table.addCell(new Paragraph("Fax", smallNormal));
     
        table.addCell(new Paragraph("EMAIL", smallNormal));
        table.addCell(new Paragraph("E-Mail", smallNormal));
     
        personalInfo.setAlignment(Element.ALIGN_RIGHT);
        personalInfo.setIndentationLeft(200);
        personalInfo.add(table);
        document.add(personalInfo);
    }
   
    public static void main(String [] args){
       GeneratePDF generatePDF = new GeneratePDF();
    }
   
     // used to get current date of the device
       public static String getCurrentDate() {
              int year;
              int month;
              int day;
             
              String currentDate = "";
              Date d1 = null;
              final Calendar c = Calendar.getInstance();
              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

              year = c.get(Calendar.YEAR);
              month = c.get(Calendar.MONTH) + 1;
              day = c.get(Calendar.DAY_OF_MONTH);
              currentDate = "" + year + "-" + month + "-" + day + "";
              try {
                     d1 = dateFormat.parse(currentDate);
              } catch (ParseException e) {
                     e.printStackTrace();
              }

              return dateFormat.format(d1);
        }
}


Note(s):

This source code uses iText as external API so import itextpdf-5.2.1.jar

2 comments:

  1. This source code has been tested and works fine. If you have any queries regarding source code feel free to add your valuable comments

    ReplyDelete
  2. thanks. U made my life easier man :)

    ReplyDelete