Wednesday 13 April 2016

Add multiple csvs to same pdf document

Suppose employee.csv, country.csv has following data.

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

Following application writes both the files into single pdf document. Each csv file has its own table.
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();
  }

  /**
   * 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();
    }

  }
}

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

public class Test {
  public static void main(String args[]) throws IOException {
    List<String> csvFiles = new ArrayList<>();
    csvFiles.add("/Users/harikrishna_gurram/employee.csv");
    csvFiles.add("/Users/harikrishna_gurram/country.csv");

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment