Wednesday 13 April 2016

Convert Lists into tables in pdf documents

In my previous post, I explained how to convert csv file to table in PDF, In this post, I am going to explain how to convert List<String> to pdf file.

Following step-by-step procedure explains how to convert list of data into table in pdf format.


Step 1: Initialize PDDocument object.
PDDocument doc = new PDDocument()


Step 2: Initialize and create a landscape page.
PDPage page = new PDPage();
page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(),PDRectangle.A4.getWidth()));


Step 3: Add pdf page to document.
doc.addPage(page);


Step 4: 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);


Step 5: Add list to table.
dataTable.addListToTable(data, hasHeader);
baseTable.draw();


Step 6: Save result.
File result = new File(destination);


Following is the complete working application.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import java.security.SecureRandom;
import java.math.BigInteger;

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());
      return Optional.empty();
    }
  }

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

}

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> 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");

  }
}



Previous                                                 Next                                                 Home

3 comments:

  1. can i get the jar file for abobe code pls

    ReplyDelete
  2. can i get the jar file for above code pls*

    ReplyDelete
  3. Dependencies are documented here...https://self-learning-java-tutorial.blogspot.com/2016/03/introduction-to-apache-pdfbox.html?m=1

    ReplyDelete