©2018 by ITEvol7777.

PDF Generation on Java

October 19, 2018

On any project or application is almost certain that the client is going to ask a PDF file generation, the most common way to do it is through the use or integration of Jasper Report with the framework.

 

However there is another option more integrated in the Java technology and it is quite easier to maintain once you get hang of it because you  have to change just your java code unlike other solutions.

 

I am going to to do it in Oracle ADF Framework, but this solution can be implemented in any JSF or Java framework.

 

Here there are the steps:

 

1. First  the Application need to be create, so with a click "New Application..."  on the  "Application navigator"  the next option will show up. "

 

 

"ADF Fusion Web Application"  has to be selected.

 

2. Then we copy the image that we are are going to use in our file in a location inside the root of the server where we are going to aim from the App.

 

  

 

3.  Now  it is time to download the java libraries for PDF Generating.

 

You can download them on the next link.

 

Then you have to put it on any physical root .

 

In my case they would be on the location  shown on the next image:

 

 

4. Then the PDF java Libraries that contain all the jars need to  generate the file  to be added to the specific project on the java framework.

 

In the case of ADF the library dependency is add as shown below:

 

Double click in the "viewController Project" and then in "Libraries and Classpath" option and then in "Add Library".

 

 

Then in the next window  the "New" button has to be clicked.

 

 

Then click make sure to check "Deploy by Default" option to make sure that the library jars are deployed in the server and packed inside the application,  then click  "Add Entry" button.

 

 

Then select all the jars on the location they are stored and click "Open" Button.

 

 

Now we have all the jars package in  a Library which name is "PDFGenerator".

 

 

Finally we have our library added to our project.

 

 

 

 5.  It is time to create the JSF page add the button  that will launch the java method that will generate the PDF file,

 

To make this blog shorter I will assume that you know how to create and ADF page,  create a button and link it to the managed bean. 

 

If you do not know you can watch  on the next links:

 

Create ADF Page 1.

Create ADF Page 2.

 

Then you have the page an the button that launch a manage bean method from an Action event. This is in case of JSF and ADF frameworks.

 

 

This is the jsf code that form the button:

 

 <af:button

text="Generate PDF" id="b1" inlineStyle="margin: 15px;"
actionListener=

"#{pageFlowScope.PDFGeneratorBean.generarPDF}"/>

 

6.  Now here is the part or code that can be used in any java framework:

 

First we list the imports of the classes needed to create this file, the imports that you will need will depend on the file that you creating, for example if it contains images, tables, etc.

 

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

 

Here we have the java method needed to the file creation.

 

/**
     *  Method that is called by a button click
  */

public void generatePDF(ActionEvent ae) {
// Add event code here...

 

try {
this.generateCert("167754222", "Derick Brown","Database", LocalDate.now());
 } catch (IOException e) {
 e.printStackTrace();
 }

} // end of generatePDF Method

 

public void generateCert(String certId, String personName, String certProduct, LocalDate ApprovedDate) throws IOException {

 

//  Document object to store the file on cache is created.
 Document document = new Document();

String enterpriseName = "ITEVOL";

try {

String downloadCertRoot = "/home/oracle/" + "Cert" + "-" + certId + ".pdf";

 

//This  is a sentence to create the File where

//downloadCertRoot Location indicates


 //This has to be a valid location in the server where the app is //deploy.


PdfWriter.getInstance(document, new FileOutputStream(downloadCertRoot));

} catch (DocumentException e) {
//In case it fails on the file creation
e.printStackTrace();
}


try {

 

// Set the orientation page as horizontal

document.setPageSize(PageSize.LETTER.rotate());

logger.warning("PDF is created");
document.open();

logger.warning("It will open the doc to edit and make changes inside the PDF");


// You create an image object to attach an image to your pdf //file.

 

 //The image object is obtain from the location where we put //the image on the server

com.itextpdf.text.Image img =com.itextpdf.text .Image.

getInstance("/home/oracle/Pictures/logo-uni-cert.png");


logger.warning("The image object is : " + img);
           

// this statements give the image  the size  and position in the //page.

img.scaleAbsoluteHeight(83f);
img.scaleAbsoluteWidth(229f);
img.setSpacingBefore(0);
img.setSpacingAfter(0);
img.setAbsolutePosition(0f, 514f);
           

//Attatch  the image to the file document.add(img);

           

//Now it is time to set the font-type and font-size of the //different texts
           

// that are going to be  in the file ass titles and paragraphs
           

Font fTitulo = FontFactory.getFont(FontFactory.TIMES_ROMAN, 20, BaseColor.BLACK);


Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, BaseColor.BLACK);
           

Font fBold = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD, BaseColor.BLACK);

 


// Chunck variable that contains the text that will stay on the //file

Chunk cTitle = new Chunk("CERTIFICATION OF " + certProduct, fTitulo);


Chunk cCertDescription =new Chunk("Congratulations for obtain the badge that  " + "certified you as a " + certProduct +
" implement specialist. " + "The certification Id " + certId);

            

Chunk cEnterpriseName = new Chunk(enterpriseName, fBold);
           

Chunk cEnterpris1 = new Chunk(" Awarded recognition ", font);
           

Chunk cText2 = new Chunk("Granted to " + personName, fBold);

           

Chunk cText3 = new Chunk(" with a " + certProduct + " specialist badge. ", font);

 


//    Chunk certProductC = new Chunk("(" + certProduct + ")", //fBold);

           

Chunk cBody =new Chunk("This badge means complete" + "understanding  of all PL-SQL operations and handling" +
 " of all trigers, store procedures and functions operations among others concepts.");

 

Chunk cFooter = new Chunk("Granted on "+ApprovedDate.toString() + ".", font);

 

//Then  on the paragraph objects you need to store the chunck objects


//this is mainly beacuse paragraphs are the objects that you add to the document object
           

// because they can be align
Paragraph paraTit = new Paragraph(cTitle);
paraTit.setAlignment(Paragraph.ALIGN_RIGHT);

paraTit.setPaddingTop(-20f);
paraTit.setSpacingAfter(100);
document.add(paraTit);

Paragraph paraCertDescription = new Paragraph(cCertDescription);            paraCertDescription.setAlignment(Paragraph.ALIGN_JUSTIFIED);
 paraCertDescription.setSpacingAfter(50);
document.add(paraCertDescription);

 Paragraph paragraphEnterprise = new Paragraph();

paragraphEnterprise.add(cEnterpriseName);
paragraphEnterprise.add(cEnterpris1);
paragraphEnterprise.add(cText2);

paragraphEnterprise.add(cText3);

 

// paragraphEnterprise.add(certProductC);            paragraphEnterprise.setAlignment(Paragraph.ALIGN_CENTER);
paragraphEnterprise.setSpacingAfter(50);
document.add(paragraphEnterprise);

Paragraph paraBody = new Paragraph(cBody);
paraBody.setAlignment(Paragraph.ALIGN_JUSTIFIED);
paraBody.setSpacingAfter(35);
document.add(paraBody);

Paragraph paraFooter = new Paragraph(cFooter);
 paraFooter.setAlignment(Paragraph.ALIGN_CENTER);
 paraFooter.setSpacingBefore(15);
 document.add(paraFooter);

document.close();
} catch (DocumentException e) {

logger.warning("It failed");

            e.printStackTrace();
 } catch (FileNotFoundException e) {
            e.printStackTrace();

} catch (MalformedURLException e) {

            e.printStackTrace();
} catch (IOException e) {

            e.printStackTrace();

}


}// end of method

 

7. Now its time to run the app and see how the java method works.

 

To fire the java method just click the button.

 

 

 

Once the you click the button, you can check out the PDF file creation in the location server that it is set in the java code:

 

"PdfWriter.getInstance(document,

new FileOutputStream(downloadCertRoot));".

 

 

Now its time to check out how the pdf Style looks like.

 

 

 

The image does not look as it should be, so to make the logo look nicer, the width and height of the image object need to be modified.

 

So the code lines change from:

 

img.scaleAbsoluteHeight(83f);
img.scaleAbsoluteWidth(229f);

 

to:

 

img.scaleAbsoluteHeight(100f);
img.scaleAbsoluteWidth(200f);

 

Now generating the PDF file again we will see that the logo looks better.

 

 

 This PDF file is simple and it can seem to be raw, but whatever is the requirement of the client you can do it with this PDF java libraries  (tables, complex designs and huge documents among others) and it is easy to maintain once you get the hang of it.

 

This is the simplest example of PDF generation because it is just a demonstrative one.

 

Let  me know if you need help with more complex PDF files as files with tables or large documentation and params so I can help you out posting another blog or giving some tricks.

 

PD: To Download the ADF Application click here.

 

 

 

 

 

Please reload

Our Recent Posts

March 29, 2019

Please reload

Archive

Please reload

Tags