Generate PDF Reports using iText

Hi,

In this blog I would like to show how to create PDF report using iText API. Below is working code to generate PDF.

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;

import java.net.MalformedURLException;


public class PDFReportGeneration {
    public PDFReportGeneration() {
        super();
    }

    public static void main(String[] args) {
        PDFReportGeneration pDFReportGeneration = new PDFReportGeneration();
        pDFReportGeneration.buildPDFReport("C:\\Users\\drongali\\Downloads\\temp\\FirstPdf.pdf");
    }
    
    private void buildPDFReport(String path) {
    Document doc = new Document(PageSize.A4.rotate());
        PdfWriter docWriter = null;

    try {

        //special font sizes
        Font bfBold12 =
            new Font(FontFamily.HELVETICA, 11, Font.BOLDITALIC, new BaseColor(0,
                                                                              0,
                                                                              0));
        Font bfBold11 =
            new Font(FontFamily.HELVETICA, 10, Font.BOLDITALIC, new BaseColor(0,
                                                                              0,
                                                                              0));
        Font bf12 = new Font(FontFamily.HELVETICA, 10);
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
        HeaderFooter event = new HeaderFooter();
        docWriter.setBoxSize("art", new Rectangle(0, 0, 559, 788));
        docWriter.setPageEvent(event);
        //document header attributes
        doc.addAuthor("dileep");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("dileep");
        doc.setPageSize(PageSize.LETTER);
        //open document
        doc.open();

        //create a paragraph
        Paragraph paragraph = new Paragraph();

        //specify column widths
        float[] columnWidths =
        { 1.9f, 0.9f, 1.9f, 1.9f, 2.3f, 0.5f, 1.5f, 2.4f, 3f, 2.3f, 2f,
          0.5f, 2.6f, 3.8f };
        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(107f);

        /**
     * Creating Header section
     */
        //First Row
        //merge the cells to create a Header ISQL Number for that section
        insertCell(table, "Roll Number:", Element.ALIGN_LEFT, 3, bfBold12);
        insertCell(table, "12345", Element.ALIGN_LEFT, 11, bf12);

        //Second Row
        //merge the cells to create a Header ISQL Number for that section
        insertCell(table, "Grade:", Element.ALIGN_LEFT, 3, bfBold12);
            insertCell(table, "A", Element.ALIGN_LEFT, 11, bf12);


        //Thrid Row
        insertCell(table, "First Name:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Dileep", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Middle Name:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Kumar", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Last Name", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Rongali", Element.ALIGN_LEFT, 3, bf12);

        insertCell(table, "DOB:", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "##-##-####", Element.ALIGN_LEFT, 1, bf12);

        //Fourth Row
        insertCell(table, "Location:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Hyderabad", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Address Line1:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Address Line2:", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 3, bf12);

        insertCell(table, "Address Line 3:", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 1, bf12);

        //Five Row
        insertCell(table, "Door#:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "City:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Pincode:", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 3, bf12);

        insertCell(table, "Street:", Element.ALIGN_LEFT, 1, bf12);
       insertCell(table, "", Element.ALIGN_LEFT, 1, bf12);

        //Sixth Row
        insertCell(table, "Date of Joining:", Element.ALIGN_LEFT, 2, bf12);
         insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Medium:", Element.ALIGN_LEFT, 2, bf12);
         insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);

        insertCell(table, "Section:", Element.ALIGN_LEFT, 1,
                   bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 3, bf12);

        insertCell(table, "Class:", Element.ALIGN_LEFT, 1,
                   bf12);
         insertCell(table, "", Element.ALIGN_LEFT, 1, bf12);

        //Row Seven
        insertCell(table, "Remarks:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 7, bf12);
        insertCell(table, "Comments:", Element.ALIGN_LEFT, 3, bf12);
        insertCell(table, "None", Element.ALIGN_LEFT, 2, bf12);

        //Row Eight
        insertCell(table, "", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 12, bf12);
        /**
     * End of Header Section Creation
     */

        /**
     * Subject Section Start
     */
        insertCell(table, "Subjects", Element.ALIGN_LEFT, 14,
                   bfBold11);

        // First Row
       
            insertCell(table, "A", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Telugu", Element.ALIGN_LEFT, 4,
                   bf12);

        
            insertCell(table, "B", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "English",
                   Element.ALIGN_LEFT, 3, bf12);

       
            insertCell(table, "B+", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Hindi", Element.ALIGN_LEFT, 3,
                   bf12);

        // Second Row
       
            insertCell(table, "A", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Sports", Element.ALIGN_LEFT,
                   4, bf12);

        
            insertCell(table, "D", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Science",
                   Element.ALIGN_LEFT, 3, bf12);

       
            insertCell(table, "A", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Social Science", Element.ALIGN_LEFT, 3,
                   bf12);

        // Third Row
       
            insertCell(table, "B+", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "Maths", Element.ALIGN_LEFT, 4,
                   bf12);

      
            insertCell(table, "C", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Drawing",
                   Element.ALIGN_LEFT, 3, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table, "", Element.ALIGN_LEFT, 3, bf12);

        //Fourth empty row
        insertCell(table, "", Element.ALIGN_LEFT, 14, bf12);

        /**
     * End Subject Section
     */


        /**
     * Sports Section Start
     */
        //Carrier Issues Header
        insertCell(table, "Sports", Element.ALIGN_LEFT, 14,
                   bfBold11);

        // First Row
        insertCell(table, "Cricket:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table,"A",
                   Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Basket Ball:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table,"C",
                   Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Ping Pong:", Element.ALIGN_LEFT, 1, bf12);
        insertCell(table,"B",
                   Element.ALIGN_LEFT, 2, bf12);
        insertCell(table, "Swimming:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table,"A+",
                   Element.ALIGN_LEFT, 1, bf12);

        // Second Row
        insertCell(table, "Total:", Element.ALIGN_LEFT, 2, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 12, bf12);

        //Fourth empty row
        insertCell(table, "", Element.ALIGN_LEFT, 14, bf12);
        /**
     * Sport Section End
     */

    
        //Fourth empty row
        insertCell(table, "", Element.ALIGN_LEFT, 14, bf12);
        insertCell(table, "Total Working days", Element.ALIGN_LEFT, 4, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 10, bf12);
        insertCell(table, "Number of Holidays", Element.ALIGN_LEFT, 4, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 10, bf12);
        insertCell(table, "Total days present", Element.ALIGN_LEFT, 4, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 10, bf12);
        insertCell(table, "Total days absent", Element.ALIGN_LEFT, 4, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 10, bf12);
        insertCell(table, "Number of leaves", Element.ALIGN_LEFT, 4, bf12);
        insertCell(table,"",
                   Element.ALIGN_LEFT, 10, bf12);

        insertCell(table, "", Element.ALIGN_LEFT, 14, bf12);
      
        //add the PDF table to the paragraph
        paragraph.add(table);
        // add the paragraph to the document
        doc.add(paragraph);


    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            //close the document
            doc.close();
        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }
    }
    //return out.toByteArray();
    }
    
    private void insertCell(PdfPTable table, String text, int align, int colspan, Font font){
       
      //create a new cell with the specified Text and Font
      PdfPCell cell = new PdfPCell(new Phrase(text.trim(), font));
      //set the cell alignment
      cell.setHorizontalAlignment(align);
      //set the cell column span in case you want to merge two or more cells
      cell.setColspan(colspan);
      //in case there is no text and you wan to create an empty row
      if(text.trim().equalsIgnoreCase("")){
       cell.setMinimumHeight(10f);
      }
      cell.setPaddingLeft(7f);
      table.addCell(cell);
       
     }
    
    /** Inner class to add a header and a footer. */
    class HeaderFooter extends PdfPageEventHelper {
        /** Alternating phrase for the header. */
        private PdfPTable header;
        float[] columnWidths = { 9f, 4f };
        PdfPTable pdfPTable = new PdfPTable(columnWidths);

        public HeaderFooter() {
            super();

            //create a new cell with the specified Text and Font
            Font bfBold12 =
                new Font(FontFamily.HELVETICA, 12, Font.BOLD, new BaseColor(0,
                                                                            0,
                                                                            0));
            PdfPCell cell =
                new PdfPCell(new Phrase("Generate PDF Report Using iText".trim(),
                                        bfBold12));
            cell.setBorderWidth(0f);
            cell.setPaddingLeft(150f);
            pdfPTable.addCell(cell);
            this.header = pdfPTable;
            this.header.setHorizontalAlignment(Element.ALIGN_CENTER);
            this.header.setWidthPercentage(130F);
            this.header.setSpacingAfter(30F);
            System.out.println("build done1");
        }


        /**
         * Increase the page number.
         * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
         */
        public void onStartPage(PdfWriter writer, Document document) {
            
            Image image = null;
            try {
                image = Image.getInstance("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (image != null) {
                try {

                    // add logo
                    image.scaleAbsolute(120f, 30f);
                    image.setSpacingAfter(10f);
                    PdfPCell cell2 = new PdfPCell(image, false);
                    cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell2.setBorderWidth(0f);
                    pdfPTable.addCell(cell2);
                    //document.add(mystoreLogo);
                    document.add(pdfPTable);
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * Adds the header and the footer.
         *
         *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
         */
        public void onEndPage(PdfWriter writer, Document document) {

        }
    }
}

Output: 



Comments

  1. Poker Baccarat - A Beginner's Guide To Baccarat
    I'll be writing about งานออนไลน์ the poker game that was invented in 바카라 America in 1787. Poker 제왕카지노 is a game played with a two card poker hand, which is referred to as a

    ReplyDelete
  2. Borgata to build new $1,400-a-night room tower - DRMCD
    ATLANTIC CITY, 대전광역 출장마사지 N.J. (AP) — Borgata 밀양 출장안마 will spend 김해 출장마사지 the 사천 출장마사지 first $1,400-a-night room tower from Thursday to Saturday. 사천 출장마사지

    ReplyDelete

Post a Comment

Popular posts from this blog

BEA-000362 Server failed. Reason: [Management:141268]Parsing Failure in config.xml

Oracle OIM - Search and Update Organization using java API

Trim Leading and Trailing spaces from InputText on tab out.