To create PDF dynamically we need header, footer ,left and right of a document (can work with any one or one or combinations of any of them)

We are using iText library to create PDF from html content dynamically.

We are taking all these images as user input. We could also take margin of left and right from the user if required.

We could calculate the coordinates i.e x and y of all images dynamically or we could hard code these values.

DTO for PDF is :

public class PDFImagesTo {
String header;
String footer;
String left;
String right;
Float leftMargin;
Float rightMargin;

public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getFooter() {
return footer;
}
public void setFooter(String footer) {
this.footer = footer;
}
public String getLeft() {
return left;
}
public void setLeft(String left) {
this.left = left;
}
public String getRight() {
return right;
}
public void setRight(String right) {
this.right = right;
}
public Float getLeftMargin() {
return leftMargin;
}
public void setLeftMargin(Float leftMargin) {
this.leftMargin = leftMargin;
}
public Float getRightMargin() {
return rightMargin;
}
public void setRightMargin(Float rightMargin) {
this.rightMargin = rightMargin;
}
}

createPDF method of CreatePdfDocument class used for creating PDF.

Points to be taken care of while creating PDF:

  1. Handling margins of document based on images or without images and also handles the blank content.
  2. Handling X and Y coordinates of all images.
  3. Handling the width and height of images in document(width and height can be calculated or hard coded).

import com.itextpdf.text.*;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringReader;

public class CreatePdfDocument {

public static void main(String... args) throws FileNotFoundException, DocumentException {
String k = "";

PDFImagesTo to=new PDFImagesTo();
to.setHeader("D:/header.PNG");
to.setFooter("D:/footer.PNG");
to.setLeft("D:/left.PNG");
to.setRight("D:/right.PNG");
String outputPath="D:/HeaderFooter7.pdf";
CreatePdfDocument pdf = new CreatePdfDocument();
pdf.createPDF(to, k,outputPath);
}

public String createPDF(PDFImagesTo to,String content,String outputPath){
try{
Float headerMargin = 90f;
Float footerMargin = 36f;
Float leftMargin = 36f;
Float rightMargin = 36f;
Image headerImage = null;
Image footerImage = null;
Image leftImage = null;
Image rightImage = null;
//adding image for header
if((to.getHeader()!=null) && !to.getHeader().trim().isEmpty()){
File file =new File(to.getHeader());
if(file.exists()){
headerImage = Image.getInstance(to.getHeader());
System.out.println(PageSize.A4.getWidth()+" "+PageSize.A4.getHeight());
headerImage.scaleToFit(PageSize.A4.getWidth(),200);
//Setting Y coordinate of header image according to header image height
Float effectiveHeaderY=PageSize.A4.getHeight() - headerImage.getPlainHeight();
headerImage.setAbsolutePosition(0,effectiveHeaderY);
headerMargin=headerImage.getPlainHeight()+10;
}else{
return "Header image does not exists";
}
}

//adding image for footer
if((to.getFooter()!=null) && !to.getFooter().trim().isEmpty()){
File file = new File(to.getFooter());
if(file.exists()){
footerImage = Image.getInstance(to.getFooter());
footerImage.scaleToFit(PageSize.A4.getWidth(),200);
footerImage.setAbsolutePosition(0, 0);
footerMargin=footerImage.getPlainHeight()+10;
}else{
return "Footer image does not exists";
}
}

//adding image for left side
if((to.getLeft()!=null) && !to.getLeft().trim().isEmpty()){
File file = new File(to.getLeft());
if(file.exists()){
leftImage = Image.getInstance(to.getLeft());
leftImage.scaleAbsolute(leftImage.getPlainWidth(),leftImage.getPlainHeight());
//Setting X and Y coordinate of Left image according to footer
Float effectiveLeftY=(footerImage!=null ? footerImage.getPlainHeight() : 0);
leftImage.setAbsolutePosition(0, effectiveLeftY);
leftMargin = leftImage.getPlainWidth()+((to.getLeftMargin()!=null && to.getLeftMargin()>=0) ? to.getLeftMargin() : 2);
}else{
return "Left image does not exists";
}
}else{
leftMargin = ((to.getLeftMargin()!=null && to.getLeftMargin()>=0)? to.getLeftMargin() : leftMargin);
}

//adding image for right side
if((to.getRight()!=null) && !to.getRight().trim().isEmpty()){
File file = new File(to.getRight());
if(file.exists()){
rightImage = Image.getInstance(to.getRight());
rightImage.scaleAbsolute(rightImage.getPlainWidth(),rightImage.getPlainHeight());
Float effectiveLeftX=PageSize.A4.getWidth() - rightImage.getPlainWidth();
Float effectiveRightY=(footerImage!=null ? footerImage.getPlainHeight() : 0);
rightImage.setAbsolutePosition(effectiveLeftX, effectiveRightY);
rightMargin= rightImage.getPlainWidth()+((to.getRightMargin()!=null && to.getRightMargin()>=0) ? to.getRightMargin() : 2);
}else{
return "Right image does not exists";
}
}else{
rightMargin = ((to.getRightMargin()!=null && to.getRightMargin()>=0) ? to.getRightMargin() : rightMargin);
}
Document document = new Document(PageSize.A4, leftMargin, rightMargin, headerMargin , footerMargin);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));

// add header and footer
HeaderFooterPageEvent event = new HeaderFooterPageEvent();
if(headerImage!=null){
event.setHeader(headerImage);
}
if(footerImage!=null){
event.setFooter(footerImage);
}
if(leftImage!=null){
event.setLeft(leftImage);
}
if(rightImage!=null){
event.setRight(rightImage);
}
writer.setPageEvent(event);
// write to document
document.open();
if(content.trim().isEmpty()){
document.newPage();
writer.setPageEmpty(false);
}
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(content));
document.close();
}
catch(Exception e){
e.printStackTrace();
}
return "success";
}
}

HeaderFooterPageEvent  is the event class which is called for every new page. We are adding header,footer,left and right image in this class only. We can write conditions here if we want header,footer,left and right image on different pages.


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class HeaderFooterPageEvent extends PdfPageEventHelper {

private PdfTemplate t;
private Image total;
private Image header=null;
private Image footer=null;
private Image left=null;
private Image right=null;
Font FONT = new Font(Font.FontFamily.COURIER, 40, Font.NORMAL, new GrayColor(0.50f));
public void onOpenDocument(PdfWriter writer, Document document) {

}

@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
PdfContentByte cb = writer.getDirectContent();
// adding image for header
if(getHeader()!=null){
cb.addImage(getHeader());
}
// adding image for footer
if(getFooter()!=null){
cb.addImage(getFooter());
}
// adding image for left
if(getLeft()!=null){
cb.addImage(getLeft());
}
// adding image for right
if(getRight()!=null){
cb.addImage(getRight());
}
//ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new Phrase("Page "+writer.getPageNumber()), 300, 5, 0);
} catch (Exception e) {
// TODO: handle exception
}
}

public void onCloseDocument(PdfWriter writer, Document document) {

}

public Image getHeader() {
return header;
}

public void setHeader(Image header) {
this.header = header;
}

public Image getFooter() {
return footer;
}

public void setFooter(Image footer) {
this.footer = footer;
}

public Image getLeft() {
return left;
}

public void setLeft(Image left) {
this.left = left;
}

public Image getRight() {
return right;
}

public void setRight(Image right) {
this.right = right;
}
}
Creating PDF document dynamically from HTML using iText in JAVA

One thought on “Creating PDF document dynamically from HTML using iText in JAVA

  • September 25, 2017 at 11:00 am
    Permalink

    Very Informative.

    Reply

Leave a Reply

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