Press enter to see results or esc to cancel.


How to Create PDF dynamically with Images using JAVA


In this video tutorial I have shown how you can generate PDF using JAVA.

This project need the jar itextpdf-5.1.0 jar to be added in Class path

  1. Project Structure
    
    
  2. Code to create simple PDF File
    Create_PDF.java

    package com.chillyfacts.com;
    import java.io.File;
    import java.io.FileOutputStream;
    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.PdfWriter;
    public class Create_PDF {
        public static void main(String[] args) {
        	String FILE_NAME = "E:\\java_pdf\\chillyfacts.pdf";
            Document document = new Document();
            try {
                PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_NAME)));
                document.open();
                Paragraph p = new Paragraph();
                p.add("Text 1");
                p.setAlignment(Element.ALIGN_CENTER);
                document.add(p);
                Paragraph p2 = new Paragraph();
                p2.add("Text 2"); //no alignment
                document.add(p2);
                Font f = new Font();
                f.setStyle(Font.BOLD);
                f.setSize(8);
                document.add(new Paragraph("This is my paragraph 3", f));
                document.add(Image.getInstance("E:\\java_pdf\\chillyfacts.png"));
                document.close();
                System.out.println("Done");
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }
    

    The above code will generate Image in location E:\\java_pdf\\chillyfacts.pdf.

  3. Create PDF file using data from MySQL Database.
    Connection class will connect to a database ‘test’ from MySQL
    DBConnection.java

    package com.chillyfacts.com;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class DBConnection {
        public Connection getConnection() {
            Connection connection = null;
            System.out.println("Connection called");
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }
    

    Create_PDF_FROM_DB.java

    package com.chillyfacts.com;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.PdfWriter;
    public class Create_PDF_FROM_DB {
        public static void main(String[] args) {
            String FILE_NAME = "E:\\java_pdf\\chillyfacts_DB.pdf";
            Document document = new Document();
            try {
                PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_NAME)));
                document.open();
                Paragraph p = new Paragraph();
                p.add("Text 1");
                p.setAlignment(Element.ALIGN_CENTER);
                document.add(p);
                Paragraph p2 = new Paragraph();
                p2.add("Text 2"); //no alignment
                document.add(p2);
                Font f = new Font();
                f.setStyle(Font.BOLD);
                f.setSize(8);
                document.add(new Paragraph("This is my paragraph 3", f));
                document.add(Image.getInstance("E:\\java_pdf\\chillyfacts.png"));
                DBConnection obj_DBConnection = new DBConnection();
                Connection connection = obj_DBConnection.getConnection();
                String query = "select * from date_time";
                Statement stmt = null;
                stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                Paragraph p3 = null;
                while (rs.next()) {
                    p3 = new Paragraph();
                    p3.add(rs.getString("date_time"));
                    document.add(p3);
                }
                document.close();
                System.out.println("Done");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    The above code will generate a PDF with data from Database.

    
    
  4. Create simple pdf in JSP Page.
    <%@page import="com.itextpdf.text.pdf.PdfWriter"%>
    <%@page import="com.itextpdf.text.Image"%>
    <%@page import="com.itextpdf.text.Font"%>
    <%@page import="com.itextpdf.text.Element"%>
    <%@page import="com.itextpdf.text.Paragraph"%>
    <%@page import="com.itextpdf.text.Document"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    response.setContentType("application/pdf");
    Document document = new Document();
    PdfWriter writer=PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    Paragraph p = new Paragraph();
    p.add("Text 1");
    p.setAlignment(Element.ALIGN_CENTER);
    document.add(p);
    Paragraph p2 = new Paragraph();
    p2.add("Text 2"); //no alignment
    document.add(p2);
    Font f = new Font();
    f.setStyle(Font.BOLD);
    f.setSize(8);
    document.add(new Paragraph("This is my paragraph 3", f));
    document.add(Image.getInstance("E:\\java_pdf\\chillyfacts.png"));
    document.close();
    %>
    </body>
    </html>
    

    http://localhost:8080/Create_Pdf/Create_PDF.jsp

    
    
  5. Create PDF in JSP page with data from MySQL database
    Create_PDF_DB.jsp

    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.Statement"%>
    <%@page import="java.sql.Connection"%>
    <%@page import="com.chillyfacts.com.DBConnection"%>
    <%@page import="com.itextpdf.text.pdf.PdfWriter"%>
    <%@page import="com.itextpdf.text.Image"%>
    <%@page import="com.itextpdf.text.Font"%>
    <%@page import="com.itextpdf.text.Element"%>
    <%@page import="com.itextpdf.text.Paragraph"%>
    <%@page import="com.itextpdf.text.Document"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    response.setContentType("application/pdf");
    Document document = new Document();
    PdfWriter writer=PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    Paragraph p = new Paragraph();
    p.add("Text 1");
    p.setAlignment(Element.ALIGN_CENTER);
    document.add(p);
    Paragraph p2 = new Paragraph();
    p2.add("Text 2"); //no alignment
    document.add(p2);
    Font f = new Font();
    f.setStyle(Font.BOLD);
    f.setSize(8);
    document.add(new Paragraph("This is my paragraph 3", f));
    document.add(Image.getInstance("E:\\java_pdf\\chillyfacts.png"));
    DBConnection obj_DBConnection=new DBConnection();
    Connection connection=obj_DBConnection.getConnection();
    String query="select * from date_time"; 
    Statement stmt = null;
    stmt = connection.createStatement(); 
    ResultSet rs=stmt.executeQuery(query);
    Paragraph p3=null;
    while(rs.next()){
     p3 = new Paragraph();
     p3.add(rs.getString("date_time")); 
     document.add(p3);
    }
    document.close();
    %>
    </body>
    </html>
    
    
    
  6. Designed PDF page with Table and Borders added.
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@page import="com.itextpdf.text.Document"%>
    <%@page import="com.itextpdf.text.pdf.PdfWriter"%>
    <%@page import="com.itextpdf.text.Paragraph"%>
    <%@page import="com.itextpdf.text.pdf.PdfDocument"%>
    <%@page import="java.io.File"%>
    <%@page import="com.itextpdf.text.pdf.PdfPage"%>
    <%@page import="com.itextpdf.text.pdf.PdfPTable"%>
    <%@page import="java.io.FileOutputStream"%>
    <%@page import="com.itextpdf.text.Element"%>
    <%@page import="com.itextpdf.text.Image"%>
    <%@page import="java.net.URL"%>
    <%@page import="com.itextpdf.text.Font"%>
    <%@page import="com.itextpdf.text.Phrase"%>
    <%@page import="com.itextpdf.text.Chunk"%>
    <%@page import="com.itextpdf.text.Rectangle"%>
    <%@page import="com.itextpdf.text.pdf.PdfContentByte"%>
    <%@page import="com.itextpdf.text.pdf.BaseFont"%>
    <%@page import="java.util.List"%>
    <%@page import="java.util.Iterator"%><html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <center>
    <%
    response.setContentType("application/pdf");
    Rectangle pageSize = new Rectangle(780, 525);
    Document document = new Document(pageSize);
    PdfWriter writer=PdfWriter.getInstance(document, response.getOutputStream());
    //PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    //document.addHeader("jinu","jawad");
    float[] colsWidth1 = {1f, 1f, 1f,1f,1f}; // Code 1
    //Image image = Image.getInstance(path+"employee/payslip/view/fly-hind.jpg");
    PdfPTable table = new PdfPTable(colsWidth1);
    table.getDefaultCell().setBorder(0);
    table.setWidthPercentage(100); // Code 2
    table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
    table.addCell("");
    table.addCell("");
    table.addCell("Pay Slip For The Month December");
    table.addCell("");
    table.addCell("");
    document.add(table);
    document.add( Chunk.NEWLINE );
    document.add( Chunk.NEWLINE );
    float[] colsWidth_main = {1f, 1f, 1f}; // Code 1
    table = new PdfPTable(colsWidth_main);
    table.getDefaultCell().setBorder(0);
    table.setWidthPercentage(100); // Code 2
    table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
    table.addCell("");
    table.addCell(Image.getInstance("E:\\java_pdf\\chillyfacts.png"));
    table.addCell("");
    document.add(table);
    float[] colsWidth = {1f, 1f, 1f, 1f}; // Code 1
    table = new PdfPTable(colsWidth);
    table.getDefaultCell().setBorder(0);
    table.setWidthPercentage(100); // Code 2
    table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
    table.addCell("Employee ID");
    table.addCell("00000");
    table.addCell("Name");
    table.addCell("00000");
    table.addCell("Department");
    table.addCell("00000");
    table.addCell("Designation");
    table.addCell("00000");
    table.addCell("Date Of Joining");
    table.addCell("00000");
    table.addCell("PF Account No");
    table.addCell("00000");
    table.addCell("Days Worked");
    table.addCell("00000");
    table.addCell("ESI Account Number");
    table.addCell("00000");
    table.addCell("Casual Leave");
    table.addCell("00000");
    table.addCell("Adhar Number");
    table.addCell("00000");
    table.addCell("PAN Number");
    table.addCell("00000");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    document.add(table);
    document.add( Chunk.NEWLINE );
    document.add( Chunk.NEWLINE );
    Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    PdfPTable table1 = new PdfPTable(colsWidth);
    table1.setWidthPercentage(100); // Code 2
    table1.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
    Phrase Earnings = new Phrase("Earnings", boldFont );
    Phrase Amount = new Phrase("Amount", boldFont );
    Phrase Deductions = new Phrase("Deductions", boldFont );
    Phrase Amount1 = new Phrase("Amount1", boldFont );
    Phrase total_earnings = new Phrase("Total Earning", boldFont );
    Phrase total_deductions = new Phrase("Total Deductions", boldFont );
    table1.addCell(Earnings);
    table1.addCell(Amount);
    table1.addCell(Deductions);
    table1.addCell(Amount);
    table1.addCell("Basic Pay");
    table1.addCell("00000");
    table1.addCell("PF");
    table1.addCell("00000");
    table1.addCell("HRA");
    table1.addCell("00000");
    table1.addCell("ESI");
    table1.addCell("00000");
    table1.addCell("Festival Allowance");
    table1.addCell("00000");
    table1.addCell("Professional Taxes");
    table1.addCell("00000");
    table1.addCell("Others");
    table1.addCell("00000");
    table1.addCell("Others");
    table1.addCell("00000");
    table1.addCell(total_earnings);
    table1.addCell("00000");
    table1.addCell(total_deductions);
    table1.addCell("00000");
    document.add(table1);
    PdfPTable table2 = new PdfPTable(colsWidth);
    table2.setWidthPercentage(100); // Code 2
    table2.getDefaultCell().setBorder(0);
    table2.setHorizontalAlignment(Element.ALIGN_MIDDLE);//Code 3
    Phrase employers_signature = new Phrase("Employer's Signature", boldFont );
    Phrase employees_signature = new Phrase("Employee's Signature", boldFont );
    document.add( Chunk.NEWLINE );
    table2.addCell(" ");
    table2.addCell(" ");
    table2.addCell(" ");
    table2.addCell(" ");
    table2.addCell(employers_signature);
    table2.addCell("");
    table2.addCell(employees_signature);
    table2.addCell("");
    document.add( Chunk.NEWLINE );
    document.add(table2);
    PdfContentByte cb = writer.getDirectContent();
    cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 24);
    cb.setLineWidth(3);
    cb.moveTo(10, 515);
    cb.lineTo(770,515 );
    cb.moveTo(10, 10);
    cb.lineTo(770,10 );
    cb.moveTo(770, 515);
    cb.lineTo(770, 10);
    cb.moveTo(10, 515);
    cb.lineTo(10, 10);
    cb.stroke();
    document.close();
    %>
    </center>
    </body>
    </html>
    

    The above code will generate PDF image in JSP page as,

  7. Download the Complete project here

    Create_Pdf.rar

Comments

Leave a Comment