Wednesday 13 April 2016

Convert multiple Lists into tables in pdf document


In my previous post, I explained how to add multiple csv files as tables in PDF document, in this post, I am going to show you how to add multiple lists as 
tables in PDF document.
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.ArrayList;
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 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 {
  public static void main(String args[]) throws IOException {
    // 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,
        "result.pdf");

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

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

  }

}



Previous                                                 Next                                                 Home

No comments:

Post a Comment