Wednesday, 13 April 2016

Utility class to convert csv file, lists data to tables in PDF

employee.csv
Employee Id, First Name, Last Name
1,Hari Krishna,Gurram
2,Kiran Kumar,Darsi
3,Rama Krishna,Gurram
4,Gopi,Battu
5,Sudheer,Ganji

country.csv
Country,Capital
India,New Delhi
Uganda,Kampala
Switzerland,Bern
Guyana,Georgetown

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.quodlibet.boxable.BaseTable;
import be.quodlibet.boxable.datatable.DataTable;

public class PDFUtil {
  private final static Logger logger = LoggerFactory.getLogger(PDFUtil.class);

  private static final SecureRandom random = new SecureRandom();

  private static String getRandomString() {
    return new BigInteger(128, random).toString(32);
  }

  /**
   * Read file data as string
   * 
   * @param url
   * @return on success read file data as string and return Optional<String>,
   *         else return Optional.empty().
   */
  private static Optional<String> getFileDataAsString(String filePath) {
    if (Objects.isNull(filePath)) {
      logger.error("filePath shouldn't be null");
      return Optional.empty();
    }

    File file = new File(filePath);

    try (InputStream in = new FileInputStream(file);) {
      return Optional.of(IOUtils.toString(in));
    } catch (IOException e) {
      logger.error("Unable to read file " + file);
      logger.error(e.getMessage());
      logger.error(getStackTrace(e));
      return Optional.empty();
    }
  }

  private static PDPage addNewPage(PDDocument doc) {
    PDPage page = new PDPage();
    doc.addPage(page);
    return page;
  }

  private static String getStackTrace(Throwable t) {
    StringWriter sw = new StringWriter();
    t.printStackTrace(new PrintWriter(sw));
    return sw.toString();
  }

  /**
   * 
   * @param csvFile
   * @param hasHeader
   *            : true represent csv file has header
   * @param separator
   * @param destination
   *            : Destination pdf file
   * @return On success return Optional<String>,else return Optional.empty().
   * @throws IOException
   */
  public static Optional<String> getPDFFromCSV(String csvFile,
      boolean hasHeader, char separator, String destination)
      throws IOException {
    Optional<String> fileData = getFileDataAsString(csvFile);

    if (!fileData.isPresent()) {
      logger.error("Unable to read file " + csvFile);
      return Optional.empty();
    }

    String data = fileData.get();

    /* Initialize PDDocument */
    try (PDDocument doc = new PDDocument()) {

      /* Initialize and create a landscape page */
      PDPage page = new PDPage();
      page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
          PDRectangle.A4.getWidth()));

      /* Add page to PDDocument */
      doc.addPage(page);

      /* Initialize DataTable */
      float margin = 10;
      float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
      float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
      float yStart = yStartNewPage;
      float bottomMargin = 20;
      BaseTable baseTable = new BaseTable(yStart, yStartNewPage,
          bottomMargin, tableWidth, margin, doc, page, true, true);
      DataTable dataTable = new DataTable(baseTable, page);

      /* Add csv data to table */
      dataTable.addCsvToTable(data, hasHeader, separator);
      baseTable.draw();

      File result;
      if (Objects.isNull(destination)) {
        String tempFile = getRandomString().concat(".pdf");
        result = new File(tempFile);
      } else {
        result = new File(destination);
      }

      doc.save(result);
      return Optional.of(result.getAbsolutePath());
    }

  }

  public static Optional<String> getPDFFromList(List<List> data,
      boolean hasHeader, String destination) throws IOException {

    if (Objects.isNull(data)) {
      logger.error("data shouldn't be empty");
      return Optional.empty();
    }
    /* Initialize PDDocument */
    try (PDDocument doc = new PDDocument();) {

      /* Initialize and create a landscape page */
      PDPage page = new PDPage();
      page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
          PDRectangle.A4.getWidth()));

      /* Add page to PDDocument */
      doc.addPage(page);

      /* Initialize DataTable */
      float margin = 10;
      float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
      float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin);
      float yStart = yStartNewPage;
      float bottomMargin = 0;

      BaseTable baseTable = new BaseTable(yStart, yStartNewPage,
          bottomMargin, tableWidth, margin, doc, page, true, true);
      DataTable dataTable = new DataTable(baseTable, page);

      /* Add list to table */
      dataTable.addListToTable(data, hasHeader);
      baseTable.draw();

      File result;
      if (Objects.isNull(destination)) {
        String tempFile = getRandomString().concat(".pdf");
        result = new File(tempFile);
      } else {
        result = new File(destination);
      }

      doc.save(result);
      return Optional.of(result.getAbsolutePath());
    }
  }

  /**
   * Add multiple csv files to a pdf document. Each csv file has one table.
   * 
   * @param csvFiles
   * @param hasHeader
   * @param separator
   * @param destination
   * @return
   */
  public static Optional<String> addMultipleCSVstoPDF(List<String> csvFiles,
      boolean hasHeader, char separator, String destination) {
    if (Objects.isNull(csvFiles)) {
      logger.error("csvFiles shouldn't be null");
      return Optional.empty();
    }

    /* Initialize PDDocument */
    try (PDDocument doc = new PDDocument();) {
      File result;
      if (Objects.isNull(destination)) {
        String tempFile = getRandomString().concat(".pdf");
        result = new File(tempFile);
      } else {
        result = new File(destination);
      }

      for (String csvFile : csvFiles) {
        Optional<String> fileData = getFileDataAsString(csvFile);

        if (!fileData.isPresent()) {
          logger.error("Unable to read file " + csvFile
              + " processing other files");
          continue;
        }

        String data = fileData.get();

        /* Initialize and create a landscape page */
        PDPage page = addNewPage(doc);
        page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
            PDRectangle.A4.getWidth()));

        /* Initialize DataTable */
        float margin = 10;
        float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
        float yStartNewPage = page.getMediaBox().getHeight()
            - (2 * margin);
        float yStart = yStartNewPage;
        float bottomMargin = 20;
        BaseTable baseTable;
        try {
          baseTable = new BaseTable(yStart, yStartNewPage,
              bottomMargin, tableWidth, margin, doc, page, true,
              true);
          DataTable dataTable = new DataTable(baseTable, page);

          /* Add csv data to table */
          dataTable.addCsvToTable(data, hasHeader, separator);
          baseTable.draw();

          doc.save(result);
        } catch (IOException e) {
          logger.error(e.getMessage());
          logger.error(getStackTrace(e));
        }

      }
      return Optional.of(result.getAbsolutePath());
    } catch (IOException e1) {
      logger.error(e1.getMessage());
      logger.error(getStackTrace(e1));
      return Optional.empty();
    }

  }

  /**
   * Add multiple tables to a pdf document. Each csv file has one table.
   * 
   * @param csvFiles
   * @param hasHeader
   * @param separator
   * @param destination
   * @return
   */
  public static Optional<String> addMultipleListsToPDF(
      List<List<List>> lists, boolean hasHeader, String destination) {
    if (Objects.isNull(lists)) {
      logger.error("csvFiles shouldn't be null");
      return Optional.empty();
    }

    /* Initialize PDDocument */
    try (PDDocument doc = new PDDocument();) {
      File result;
      if (Objects.isNull(destination)) {
        String tempFile = getRandomString().concat(".pdf");
        result = new File(tempFile);
      } else {
        result = new File(destination);
      }

      for (List<List> data : lists) {
        /* Initialize and create a landscape page */
        PDPage page = addNewPage(doc);
        page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),
            PDRectangle.A4.getWidth()));

        /* Initialize DataTable */
        float margin = 10;
        float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
        float yStartNewPage = page.getMediaBox().getHeight()
            - (2 * margin);
        float yStart = yStartNewPage;
        float bottomMargin = 20;
        BaseTable baseTable;
        try {
          baseTable = new BaseTable(yStart, yStartNewPage,
              bottomMargin, tableWidth, margin, doc, page, true,
              true);
          DataTable dataTable = new DataTable(baseTable, page);

          /* Add csv data to table */
          dataTable.addListToTable(data, hasHeader);
          baseTable.draw();

          doc.save(result);
        } catch (IOException e) {
          logger.error(e.getMessage());
          logger.error(getStackTrace(e));
        }

      }
      return Optional.of(result.getAbsolutePath());
    } catch (IOException e1) {
      logger.error(e1.getMessage());
      logger.error(getStackTrace(e1));
      return Optional.empty();
    }

  }
}

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Test {
  private static final String employeeCSV = "/Users/harikrishna_gurram/employee.csv";
  private static final String countryCSV = "/Users/harikrishna_gurram/country.csv";

  public static void testAddMultipleListsToPDF() {
    // Create the data
    List<List> employees = new ArrayList<>();
    employees.add(new ArrayList<>(Arrays.asList("Employee Id",
        "First Name", "LastName")));
    for (int i = 1; i <= 10; i++) {
      String empId = "" + i;
      String firstName = "first_name" + i;
      String lastName = "lastName" + i;

      employees.add(new ArrayList<>(Arrays.asList(empId, firstName,
          lastName)));
    }

    List<List> students = new ArrayList<>();
    students.add(new ArrayList<>(Arrays.asList("Id", "Name")));

    for (int i = 1; i <= 10; i++) {
      String id = "" + i;
      String name = "name" + i;

      students.add(new ArrayList<>(Arrays.asList(id, name)));
    }

    List<List<List>> lists = Arrays.asList(employees, students);

    Optional<String> result = PDFUtil.addMultipleListsToPDF(lists, true,
        "resultAddMultipleListsToPDF.pdf");

    if (result.isPresent()) {
      System.out.println(result.get());
      return;
    }

    System.out.println("Unable to process the request");

  }

  public static void testGetPDFFromCSV() throws IOException {
    Optional<String> pdfFile = PDFUtil.getPDFFromCSV(employeeCSV, true,
        ',', "resultTestGetPDFFromCSV.pdf");

    if (!pdfFile.isPresent()) {
      System.out.println("Error while processing, go through logs");
    }

    System.out.println("PDF file is saved at " + pdfFile.get());

  }

  public static void testAddMultipleCSVstoPDF() {
    List<String> csvFiles = new ArrayList<>();
    csvFiles.add(employeeCSV);
    csvFiles.add(countryCSV);

    Optional<String> result = PDFUtil.addMultipleCSVstoPDF(csvFiles, true,
        ',', "resultaddMultipleCSVstoPDF.pdf");
    System.out.println("Result is saved to " + result.get());

  }

  public static void testGetPDFFromList() throws IOException {
    // Create the data
    List<List> data = new ArrayList<>();
    data.add(new ArrayList<>(Arrays.asList("Employee Id", "First Name",
        "LastName")));
    for (int i = 1; i <= 100; i++) {
      String empId = "" + i;
      String firstName = "first_name" + i;
      String lastName = "lastName" + i;

      data.add(new ArrayList<>(Arrays.asList(empId, firstName, lastName)));
    }
    Optional<String> result = PDFUtil.getPDFFromList(data, true,
        "result.pdf");

    if (result.isPresent()) {
      System.out.println(result.get());
      return;
    }

    System.out.println("Unable to process the request");

  }

  public static void main(String args[]) throws IOException {
    testAddMultipleListsToPDF();
    testGetPDFFromCSV();
    testAddMultipleCSVstoPDF();
    testGetPDFFromList();
  }

}


Previous                                                 Next                                                 Home

No comments:

Post a Comment