Excel to PDF – Java Servlet Program Example

You are in part 3 of the tutorial. In this part we will provide the complete Java servlet program, that converts XLS / XLSX format files to PDF document using Java. We have also designed a HTML form in Part 1, and identified all the JAR files required to support conversion in Part 2. You can refer to the related post section at the bottom of this post, if you are keen to grab them.

Full Java Servlet Example – Excel to PDF

The complete Java servlet code that converts XLS / XLSX document to PDF is given below. The servlet is fully commented, so that you can understand the code easily. The code has some assumptions built in. You can tweak the code to support to your needs.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//used to read XLSX uploaded files
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.apache.poi.xssf.usermodel.XSSFSheet;
//used to read XLS uploaded files
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
//to read user uploaded file
import org.apache.commons.io.FilenameUtils; 
import java.io.InputStreamReader;
import java.util.*;
//This class is required to handle the uploaded file in server
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
//to loop through the excel sheet
import java.util.Iterator;
//itext libraries to create PDF table 
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;

public class xlstopdfservlet extends HttpServlet {
public xlstopdfservlet() {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        OutputStream out = response.getOutputStream();  
        try {
                //set InputStream object that accepts uploaded file
                InputStream filecontent=null;              
                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                //assume default input type as XLS
                String inputtype="1"; 
                for (FileItem item : items) {
                        if (item.isFormField()) {                               
                                String fieldname = item.getFieldName();
                                if (fieldname.equals("element_2")) {
                                //identifies type of input required
                                inputtype = item.getString(); 
                                //the value can be 1 for XLS conversion, 2 for XLSX conversion
                        } else {
                        //The uploaded file is processed in this section
                        String fieldname = item.getFieldName();
                        String filename = FilenameUtils.getName(item.getName());
                        filecontent = item.getInputStream();
                        //Uploaded Excel file is obtained into Inputstream object at this step                
         //we have obtained the user uploaded Excel file till this step.
         // we also know the output is a PDF.
         // we can now write the servlet code that converts the file.
         HSSFWorkbook my_xls_workbook=null;
         HSSFSheet my_worksheet=null;
         XSSFWorkbook my_xlsx_workbook=null;
         XSSFSheet my_worksheet_xlsx=null;
         //set the output format i.e. pdf         
         Document document = new Document();
         PdfWriter.getInstance(document, out);
         //we create a PDF table that can hold XLS data
         //assumption is excel sheet is holding two columns only.
         //you can make this dynamic
         PdfPTable my_table = new PdfPTable(2);
         PdfPCell table_cell;
         //the object below loops through the excel document rows
         Iterator<Row> rowIterator = null;
         //read xls
         if (inputtype.equals("1")){
         my_xls_workbook = new HSSFWorkbook(filecontent); 
         my_worksheet = my_xls_workbook.getSheetAt(0);
         //read xlsx
         if (inputtype.equals("2")){
         my_xlsx_workbook = new XSSFWorkbook(filecontent); 
         my_worksheet_xlsx = my_xlsx_workbook.getSheetAt(0);
         while(rowIterator.hasNext()) {
                        Row row = rowIterator.next(); 
                        Iterator<Cell> cellIterator = row.cellIterator();
                                while(cellIterator.hasNext()) {
                                        Cell cell = cellIterator.next(); //Fetch CELL
                                        switch(cell.getCellType()) { //Identify CELL type
                                        case Cell.CELL_TYPE_STRING:
                                                //Push the data from Excel to PDF Cell
                                                 table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));                                                
                                        //next line
        // add table to PDF document        
        //close document..returns output to server
        catch (Exception e) {
               System.err.println(e.toString()); /* Throw exceptions to log files */
         finally {
                 out.close();/* Close the output stream */
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
        doGet(request, response);

A sample compilation example for the code is given below

javac -Xlint:unchecked -classpath  .;poi-3.8.jar;opencsv-2.3.jar;p
mmons-fileupload-1.2.2.jar;commons-io-2.4.jar xlstopdfservlet.java

Note that the above code also handles the file uploaded into a form and posted to a servlet. Apache commons file upload / commons IO library are used to handle uploaded file in a servlet. You can clip the fragment of the code and use it for a different requirement, if you need so.

In the final part of the tutorial, we will explain how to configure the servlet and see the code in action.
This Tutorial Series: Convert Excel to PDF – Java Servlet Example
Keywords: Excel to PDF, Java Servlet, Apache POI, Itext, Convert XLS to PDF Example
All parts:
1. HTML Form Design to support XLS to PDF Conversion.
2. JAR Files required for conversion and their use.
3. Handling uploaded file in a servlet./ Complete Java code to convert Excel to PDF through a servlet.
4. Servlet Configuration / Testing.

No comments: