CSV to PDF Converter – Full Java Servlet Program

We are covering the Java techniques to convert a CSV file to PDF in this series. In this part, we will provide the full Java servlet code that accepts CSV file input from the form we designed in part-2 (refer links below) and creates a PDF output from it. Before getting to the servlet code, you need to make sure you have a copy of the following JAR files.

CSV to PDF – Servlet JAR Files


To compile and run the servlet successfully, you need a copy of the following JAR files:
  • opencsv-2.3.jar
  • itextpdf-5.3.4.jar
  • servlet-api.jar
  • commons-fileupload-1.2.2.jar
  • commons-io-2.4.jar
The last two files are required to convert the uploaded file to InputStream object.

CSV to PDF – Full Java Servlet Program


The complete Java servlet code that converts CSV file to PDF table is provided below:
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 user uploaded CSV file.
import au.com.bytecode.opencsv.CSVReader; 
//read uploaded file
import org.apache.commons.io.FilenameUtils; 
import java.io.InputStreamReader;
import java.util.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
//itext libraries to create PDF table 
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;


public class csv2pdfServlet extends HttpServlet {
public csv2pdfServlet() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        OutputStream out = response.getOutputStream();  
        
        try {
                InputStream filecontent=null; //Initialize the input stream that accepts the user uploaded CSV file             
                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);          
                for (FileItem item : items) {
                        if (item.isFormField()) {                               
                                String fieldname = item.getFieldName();
                                //not applicable in this example, we don't 
                                //have any form fields
                                
                        } else {
                        //The uploaded file is processed in this section
                        String fieldname = item.getFieldName();
                        String filename = FilenameUtils.getName(item.getName());
                        filecontent = item.getInputStream();
                        //Uploaded file is obtained into Inputstream object at this step                
                        }
                }
         // We know the output type and have the file in the input stream now. We can now convert CSV to XLSX and return response back to server

         CSVReader reader = new CSVReader(new InputStreamReader(filecontent)); //reads the input CSV file in the servlet
         String [] nextLine;
         int lnNum = 0;
         
         Document my_pdf_data = new Document();
         PdfWriter.getInstance(my_pdf_data, out);
         my_pdf_data.open();
         //Assuming CSV file will have two column data
         //Expand this if you need more
         PdfPTable my_first_table = new PdfPTable(2);
         PdfPCell table_cell;
        
         while ((nextLine = reader.readNext()) != null) {
                        lnNum++;        
                        table_cell=new PdfPCell(new Phrase(nextLine[0]));
                        my_first_table.addCell(table_cell);
                        table_cell=new PdfPCell(new Phrase(nextLine[1]));
                        my_first_table.addCell(table_cell);                                             
        }
        response.setContentType("application/pdf");
        my_pdf_data.add(my_first_table);                       
        my_pdf_data.close();
       
        
        }
        catch (Exception e) {
               System.err.println(e.toString()); 
         }
         finally {
                 out.close();
         }
        
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
        doGet(request, response);
         }
}


Compile the servlet and generate the class files. For the servlet to be in action, you have to set the configuration right. Follow a reference tutorial here that will explain how to configure a servlet in TomCat.
This series: Convert CSV to PDF using Java
Keywords: Convert CSV to PDF, Java Example Program, OpenCSV, iText, Java Servlet Example
All Parts:
1. Convert CSV to PDF– Standard Java Program Example
2. CSV to PDF Servlet Conversion – HTML Form Design
3. CSV to PDF Converter – Full Java Servlet Program

No comments:

Post a Comment