How to Create PDF In Java – Working Code to Generate Salary Slip

Recently I came across a requirement that we have to generate a PDF payslip template. Even though there are tools available to generate PDF files quite easily without writing any code, just by creating layout and giving the data source is enough to create a PDF template, with data populated within an hour or so. But here I am going to show you how the same PDF templates or files can be generated, with any desired layout, using Java code. This can also be used to implement usual features like export to PDF where you might need to create PDF files in a certain format.

Pre-requisites

  1. Java SE 1.5 and above
  2. Editor/ IDE to write java code
  3. iText.jar Java API

Stepping into generating PDF Template

Before writing code, Developers need understand some basic things rather approach for generating PDF Template. So I will take you all through some basic ideas required before delving into the code.

Here I have shown a PDF Template for Payslip distributed to the employees. I will enlist what all are done in this template:

  1. PDF generation date is shown
  2. A Logo of Deslabs is attached
  3. Differenet tabular structures are created for showing information

Now first of all, we have to decide where we want to keep the generated PDF Template, upon deciding we have to think what kind of PDF Document we want to generate landscape or portrait and what would be the page sizeA�like A4, A3, B3 etc.

Document document = new Document(PageSize.A4);

Having decided all those, need to get an object ofA�PdfWriter which in turn will be fed byA�FileOutputStream to write into PDF file being opened.

Talking about the first point, a calender object is created and having formatted with suitable date format printed as PDF Generation Date. Here is the code snippet for the same:

String DATE_FORMAT_NOW = “dd-MM-yyyy HH:mm:ss”;
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String currDt = sdf.format(cal.getTime());

Then to print, the date in the PDF , need create a paragraph in turn added in the document.

Paragraph pCurrentDate = new Paragraph(currDt, fSmall);
pCurrentDate.setAlignment(Element.ALIGN_LEFT);

For Paragraph, followings can be done:

  • Paragraph can have multiple Fonts attached.
  • Paragraph can be aligned horizontally to LEFT, CENTER, RIGHT and
  • ParagraphA�can be aligned vertically to TOP, BOTTOM etc. too.

Here for Fonts, following properties can be set to:

  • Font family.
  • Font Size.
  • Font Type.
  • Font Color.

Example

static Font fSmall = FontFactory.getFont(FontFactory.HELVETICA, 5, Font.NORMAL,Color.orange);
static Font fMediumBold = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.BOLD, Color.PINK);

Now coming back to normal discussion,

Every time each object like Image, Paragraph, Table, Chunk etc. has to be added rather printed in the PDF document. The same can be accomplished by:

document.add(pCurrentDate);

Now, we will move on to the second point, adding an image to the PDF, its pretty simple. Before adding Image can be scaled to make fit for PDF.

Image image = Image.getInstance (“D:\\thehumanizer\\logo.jpg”);
image.scalePercent(325f / image.getDpiX() * 100);
image.scaleToFit(350, 50);
document.add(image);

To add blank line:

document.add(Chunk.NEWLINE);

Moving next, About Table I am going to discuss some interesting facts about table:

While Defining Table, number of columns contained by the table can be determined.like:

PdfPTable frame = new PdfPTable(2);

Here, the width of all columns will be same. but if Table with varying width is required, in that scenario, the table should be created like:

float widths[] = {1.5,2.0,2.5};
PdfPTable frame = new PdfPTable(widths);

Here table will contain 3 columns with varying widths.

Table Width can be set with respect to the Page using:

frame.setWidthPercentage(100);

Now, having declared Table structure, need to specify the property of the cell, how it will be like:

  • Font Properties.
  • Vertical Alignment.
  • Horizontal Alignment.
  • Border.
  • Background Color.
  • Border Color.

e.g:

String employeeNumber=”Employee Number”;
PdfPCell employeeNumberCell=
A� A� A� A� A� A� A� A�new PdfPCell(new Phrase( employeeNumber,FontFactory.getFont(FontFactory.HELVETICA, 8)));
employeeNumberCell.setBackgroundColor (new Color (233,238,238));

Default property for the cells can also be set:

e.g:

employeeNameTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BASELINE);
employeeNameTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

First Line is used to set vertical alignment of the cells those will be added to the table and second line to determine whether the cells will have border or not.

Having created cell , needs attached to the table and table in turn to the document.

PdfPTable frame=new PdfPTable(1);
String name=”Name”;
PdfPCell nameCell =A�new PdfPCell(new Phrase( name,FontFactory.getFont(FontFactory.HELVETICA, 8)));
employeeNumberCell.setBackgroundColor (new Color (233,238,238));
frame2.addCell(nameCell);
document.add(frame);

Now to add new page in the PDF Document,

document.newPage();

Last but not the least it is mandatory to close the document, otherwise a Document Creation Exception will be thrown. Command to close the document is:

document.close();

Now, PDF Template will be generated once successfully compiled followed by executing the class file. Here is the sample output attached how the Payslip PDF Template looks like:

Code is attached here in the .java file, can be downloaded and reused.

Leave a Reply

Your email address will not be published. Required fields are marked *

Show my latest post here