iText Tutorial: Convert Data To PDF Report Using Java & iText

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This iText Tutorial Discusses how to Manipulate Bulk Data into a Secure, Single Form of PDF Report using Java and iText Library:

iText is the tool to generate a consolidated report where we can manipulate bulk data into the single form of entity that holds meaningful information.

iText is a Java PDF library used for creating and manipulating PDF documents by developing Java programs. Some of the features of the iText library include generating interactive PDF documents, adding bookmarks, save PDFs as image files, split and merge existing PDFs into multiple PDFs, etc.

itext

Why iText?

It works in a versatile environment of an Automated Report which is produced by specific servers such as Apache Tomcat, JBoss, Junit. It provides a user-defined document according to the user’s needs.

Is iText Security Oriented?

It offers ways with which documents could be retrieved based on security-related operations such as password-protected or validating inputs from the user like opening payslip by entering PAN details.

Nowadays, we generally prefer to save data in soft copies rather than hard copies. It’s better to store reports on servers than papers. Whenever you need the report just run the Java file and generate it then and there.

In this article, let us try to find the solution to the following questions:

  • Can we use multi-functionality?
  • Whether it is used only for preparing reports?
  • Where can we use Itext?
  • Whether it can create the new report?
  • I am a tester, is it helpful to me?

What Is iText?

The output of the iText tool is a PDF report integrated by Java. This inherits the PDF behaviors, components, and generates a compatible report.

iText is an open-source API with a cooperative environment, participation in full-fledge, Prism penetration of light, and the foundation of Report generation.

For Example: Consider an example of an Indian Railways ticket. Here, we want the print of the detailed summary of the ticket process starting from searching seat availability to booking the ticket.

Next, we will understand how iText can help us with this requirement.

Some of the characteristics are as follows:

  • Complete Summary of the Application (CSA)
  • Easy Tracking Details (ETD)
  • Easy Processing the Application (EPA)

How To Start The iText Report?

It is easy to approach the Itext through Java. It is illustrated with the help of an example.

Business Analyst (BA) gets Business Process Document (BPD) and Functional Specification Document (FSD) from the client which explains their expectations from the application.

Let us take a scenario. BA brought multiple requirements about report framing as well as how our base product can support this. Such specifications from reputed clients make us think not to lose the project anyhow because of multiple confusion and dilemma on how to achieve the report in a compatible manner.

Why such confusion arises in Reports generated?

This is because the data present in the application just showcases the reflection of data in the Report. It does not move to check each node in the application (Ex. as is done in the MRI Scan). Thus, it is the easiest way.

Yes, exactly. But our client expects the data to be dynamic. Based on the data available, the report should be generated in a dynamic way.

Let us discuss this with a real-time example.

Scenario 1: Static data could be hardcoded and generate reports. Here, the loan amount and the property value don’t change before disbursement.

Please find the image below for the above scenario:

Scenario 1: Static data

Scenario 2:  In this scenario, the property value increases day by day and the Loan Amount principal should be reduced every year, and thus the data predicted is dynamic.

A customer can come and approach us to provide the details for various financial years because he has changed the tenure and based on it the EMI had been varied. If you have hardcoded the data as shown in the below figure, you will be caught red-handed.

Scenario 2: dynamic data

Consider the case where the report is supposed to be dynamic. We can’t put it forward as it is. We have to do the technical inspection and walk through the requirements clearly before starting the development and testing.

We must focus very clearly on the design part where the approval is done from the Business Analyst. It is a good approach because any UAT issues raised later can’t be pointed out on to us. The solution for this problem of dynamic report generation is predicted to simply use Java concepts in generating a report.

How to call a Report?

The below diagram illustrates the process to generate a report:

calling of report Generation

How To Invoke Report Through JSP?

Wherever we call Java, it is necessary to do UI design as this will act as a guide map to proceed from the front end. It is an easy way as we can learn the Report call.

Let us consider an example:


<div id="dropmenu" class="dropmenudiv">
<A name="summary" href="#" onClick="getReportInSoftwareTesting('Sample Report');" class="linkwhite">Software Report</A>
</div>

We can configure the report in this way:

  • Report Name: Software Report (display in application)
  • Report Calling through JS: Sample Report
  • Drop Menu: Multiple reports can integrate
  • On click: JavaScript Function

How Can Testers Initiate Report?

Testers usually prefer Regression testing through automation scripts using the Cucumber framework, Keyword Driven framework, and Data-Driven framework.

To provide the report based on the client’s requirements, we can proceed with readymade architecture i.e. iText where the inbuilt tool inherits the properties and behavior of the reporter file as well as artifacts to be delivered.

Testers can make the consolidated Report such as Remaining Bug List (RBL), test deliverables percentage, bug id mapping based on the respective phases such as SIT, UAT, and Production testing by using iText Java.

Consider a scenario that needs to configure multiple reports.

The below code illustrates how to use in JSP which is what we look at in the front end. The following method is used:


<div id="dropmenu" class="dropmenudiv">
     <A name="summary" href="#" onClick="getReportInSoftwareTesting('Sample Report');" class="linkwhite">Software Report</A>
     <A name="summary" href="#" onClick="getReportInSoftwareTesting('Sample Report1');" class="linkwhite">Software Report1</A>
     <A name="summary" href="#" onClick="getReportInSoftwareTesting('Sample Report2');" class="linkwhite">Software Report2</A>
 </div>

How To Invoke In JavaScript (JS)?

Generally, we can do validations in JS, but you can do it even in Java. JavaScript executor has been included in our package for calling function and to invoke the program to generate a report which is very compatible.

It can be used to invoke (call) method with an owner object as an argument.

Function onload(){
   String ReportName=””;
   if(ReportName==' Sample Report'){
       var applnNum='<%= applnNum>';
       //It is passing Application Number from the session which is active
       var UrlToPass = SchedulerServlet?action=samplereport &SubAction=StandardRepose &ReportName="+ ReportName +"& applnNum ="+ applnNum
   }
}

The above method handles the onload() function which can be invoked in the application to be very versatile that triggers the URL to generate Report.

How To Build The Function In Java Report?

Java handles the alerts and exceptions in the program and also executes the report generation.

Let us illustrate this with the help of an example.

Document Doc =new Document ();

It is the way of creating the document and it is also the platform that integrates the report.

Doc.open();

The above command is used to open the document. It is important to include this command as if it is not included, it will throw document exception.

Doc.close();

The above command is used to close the document which indicates JVM that the document has accepted to stop writing. It is important to include this command as if it is not included, it will throw document exception.

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));

The above command shows the document that integrates the properties of the PDF through PDFWriter, call the document, and makes it as visible.

Paragraph para = new Paragraph ();

A paragraph writes the instance of the autofit contents and also write the bulk lines of the requirement.

Doc.setpercentage(%to be given);

In the above command, a document has been invoked in calling the PDF to be compatible as defined by the percentage included.

public static final String output FileName 
       = "sample output/Automation/sample report.pdf";

The above command displays the document name, included in the double-quotes, and the specified location to store the file once the report is clicked.

writer. setPdfVersion(PdfWriter.VERSION_1_9);

Here, it shows the way to set the PDF Version in the Report generation.

document. setPageSize (PageSize.A4);

We can also set the page size of how the report has to be delivered based on the requirements. The page size as A3, A4, A5, etc.

document. setMargins(24, 43, 34, 43);

We can use the above functionality to set the margins and we can use the autofit method to be fit it normally within the document.

document.setMarginMirroring(true);

The above command displays the method of the Margin mirror setting.

Handling Alerts And Exceptions

It is important to handle the alerts and exceptions in Java.

Some of the alerts that we come across during runtime are enlisted below:

  • NoSuchElement Exception
  • Null Pointer Exception
  • Array Index bound of Exception
  • Assertion Error
  • Unhandled Alert Exception
  • SQL Exception
  • Timeout Exception
  • Document Exception

Sometimes, the developer can also print the exception of a try-catch block. The exception is enclosed under the catch block.

Example:

try{
    Scanner in= new Scanner(System.in);
    Int n;
    System.out.println(“Enter the number to check:” +n); 
    n=in.nextInt();
         If(n%2==0){
               System.out.println(“Even Number ”);
          }else{
                        System.out.println(“ODD Number”);
                   }
      }catch(Exception e){ e.printstacktrace();
           System.out.println(“Exception occurred:” +e);
}

Sample Output: Positive Scenario
Enter the number to check: 2
Even Number

Sample Output: Negative Scenario
Enter the number to check: a
An exception occurred: Illegal Format Exception

Explanation:

A number must be given as input because we have defined ‘n’ as an Integer in the above code example. If we enter any alphabets where it tries to get the Remainder (% modulus used) then it will not retrieve any data and will just throw the exception using catch block.

The exact difference between Error and Exception in Java: 

An error will stop you from executing the program but an Exception will be caught while running the program while it won’t stop your execution.

Logging a File log: 

Writing the log for every method or module makes us identify where JVM stops executing. A Log usually showcase the value where it is stored in the specified log file and by what way the processor executes the Java Program in the application.

Difference between System.out.println (SOP) and Log:

Both prints the value or showcase whatever the content is entered in double-quotes. But the differences between these two are: While the program is running, the application prints the values on the console by SOP command. But once we have erased the contents of the console, it is hard to find the value. This also happens when we have multiple SOP’s.

Basically, the Log factory command could retrieve and update the values. We can view the log file at any cost because it writes each time at every run with system date and time.

Example:

private static Log logFile= LogFactory.getLog(SampleProgram.class);

Servers

Servers play an important role in the corporate as it can determine if the program execution is passed or not.

Local servers are the servers where we can execute the program in our local machine. We can use the following local servers:

  • Apache Tomcat
  • JBoss

Once the code is in Ready State, it should be deployed to the specified server and it requires a restart. We could use the following servers:

  • Oracle Weblogic
  • IBM Websphere

Sample Program:

Consider the program where it could process the iText implementation.


/****Importings Header Functions
package pkg_Name
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ommons.logging.Log;
import com.commons.logging.LogFactory;

/**
* Implementing Report for generating Report */
public class ReportsController extends HttpServlet
{
      private static Log Log = LogFactory.getLog(ReportsController.class);
/**

  * Default constructor Used in the method. */
public ReportsController() {
   TODO Auto-generated constructor stub } /** 
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
     doPost(request, response);
     }
/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/

public  void  doPost(HttpServletRequest  pRequest,  HttpServletResponse
pResponse) throws ServletException, IOException
      {
         String action = null;
         try
     {
         Action = pRequest.getParameter("action");
         if(Log.isDebugEnabled()) log.debug("action "+action);
         if(action != null)
        {
        Action = Action.trim();
        if(Action.equals("createReport"))
           {
                  createReport(pRequest,pResponse);
           }}}
   catch(Exception Ex)
      {
              Log.fatal("Exception in ReportsController: "+pEx.toString());
       }
}

// Get the Report name from UI
private void createReport(HttpServletRequest pRequest, HttpServletResponse pResponse) throws Exception
{
         if(log.isDebugEnabled()) log.debug("createReport ");
         String nameofReport = null;
         try
         {
              nameofReport = pRequest.getParameter("ReportName");
              if(log.isDebugEnabled()) log.debug("nameofReport "+nameofReport);
              if(nameofReport != null)
                     {
                          nameofReport = nameofReport.trim();
                          if(nameofReport.equals("FirstRepo"))
                                {
                                    getFirstRepo (pRequest,pResponse);
                                 }
                                 if(nameofReport.equals("SecondRepo"))
                                {
                                         getSecondRepo (pRequest,pResponse);
                                }}}

         catch(Exception pEx)
        {
              log.print("Exception in createReport - while getting Connection: "+pEx.toString());
        }
}

// Add for FirstRepo

private void getFirstRepo(HttpServletRequest pRequest, HttpServletResponse pResponse) throws Exception
{
       if(log.isDebugEnabled()) log.debug("getFirstRepo ");
       String Url = null;
       String Referno = null;
       String lproductDesc = null;
       String lFileName = null;
       RequestDispatcher requestDispatcherObj = null;
       try
      {
            Referno = pRequest.getParameter("ApplNum");
            productDesc=pRequest.getParameter("ProdDesc");
            if(log.isDebugEnabled()) log.debug("lReferno "+lReferno);
            if(log.isDebugEnabled()) log.debug("lproductDesc "+lproductDesc);
            RequestDispatcherObj.forward(pRequest, pResponse);
        }

        catch(Exception pEx)
        {
              log.fatal("Exception in createReport - while getting Connection: "+pEx.toString());
         }
}

Alignment In Itext Java

Generally, users need the report documents in a specific format because the reports must clearly represent what and how you want to show the results. IText helps you with this.

Sample Program

Package com. Softwaretesting.itext; 
Import java io.fileoutputstream;
Import com itext pdf.Text.Document;

//Through this I am including a paragraph in my PDF; 
Import com itextpdf.Text.Paragraph;

//use the below code to write in the PDF 

Import com. Itext pdf.pdfwriter;
Public class Alignmentpdf{

//class starts from here and Start writing in below specified file
Private static string file=” Alignmentpdf.pdf”; 
System out.println(“Document entered is…”+ file);

//JVM Starts executing from main method i.e. below code 
Public static void main (string [] args){

//JVM starts compiling from here
try {
        Document doc =new document (); 
        Pdfwriter.getInstance(doc, new file output stream (file));
// Below function which makes to open the document in the front end doc.open();
Paragraph para=new paragraph(“first para”);

//Paragraph usually maintains more than one sentence
//If Sentence needs to be aligned at Left, use below code
Para.setAlignment(Element.ALIGN_LEFT);
doc.add(para);

// If Sentence needs to be aligned at Right, use below code
Paragraph para1=new paragraph(“alignment should be done in second”);
Para1 set alignment (Element.ALIGN-RIGHT);
doc.add (para1);
/*you can create same paragraph object like para or para1 based on user convenience throughout the program. But I am using different object because of showing the difference for Reader Understanding*/
Paragraph para2 = new paragraph (“Alignment is in Centre”);

// If Sentence needs to be aligned at the center, use below code
Para2 set alignment (Element.Align_CENTER);
doc.add(para2);
doc.close();
}
Catch (DocumentException e){
e. printstacktrace();
System.out.println(“Printed Java Program”);
}}}

Is iText used for creating a new one or update an existing one?

A question may arise whether iText is used for only creating a new PDF? The answer is no, in addition to generating new PDF reports,  iText also provides some features such as updating an existing pdf and provide the consolidated output which includes the updated change.

Sample code:

// Reading Input file from where the need to copy
Private static string file-to-be-given=”D:/software/Existingpdf.pdf;”

// Reading Input file from where the need to paste
Private static string file-to-be-output=”D:/software/outputpdf pdf” doc.open();
pdfReader reader =new pdfReader (file-to-be-given); 
       //Getting Number of pages before enters into for Loop 
Int n= reader.getNopages();
PdfImportedpage pager;    //Reading all pages in pdf 
For (int i=1;i<=n; i++){ If(i==5)
{ 
     //I need to add only 5th Page in my new PDF 
     Pager=writer.getImportedpage(reader,i);
     Paragraph para= new paragraph (“Its adding”); 
     doc. add (para);
}
doc. close();
}

Chunk in iText Pdf:

Chunk is the new technique that fits in the available space in pdf and which would not require anything to accompany.

Sample Program:

doc.open():
doc.add(new chunk (“1<sup>st</sup> order”));
doc.add(new chunk(“2<sup>nd</sup> order”));
doc.add(new chunk(“3<sup>rd</sup> order”));
doc.close();

Who Can Use iText?

ProfileDevelopmentView Access
DevelopmentPossibleUser-Friendly
TesterPartially PossibleUser-Friendly
Business AnalystNot PossibleUser-Friendly
CustomerNot PossibleUser-Friendly

Conclusion

iTextpdf usually elaborates report contribution using Java towards application outcome

“iText is the Java, but it generates pdf which would fit as user-friendly and can generate crystal clear reports”

Advantages of iText:

  • High and low-level Application Processing Interface (API)
  • Compatibility in Provide End to End services (PEE)
  • Text Flow Recheck Availability for Mobile users (TFRAM)
  • Adaptability.
  • Cross-platform availability.

Disadvantages of iText:

  • It is not able to achieve specific designs.
  • Thorough knowledge of OOP’s concepts is required.

Was this helpful?

Thanks for your feedback!

Leave a Comment