Monday, October 8, 2018

How to Create PDF in Java Using OpenPDF

In the post Creating PDF in Java Using iText we have already seen how to use iText library to generate a PDF in Java. Itext is one of the best way to generate PDF in Java, has many features but there is one problem; it is AGPL licensed which means you must distribute all source code, including your own product and web-based applications. Many times the idea to use iText is shot down by the clients because of this reason. So, in this post we’ll see one alternative of using iText for generating PDF in Java. That option is OpenPDF for generating PDF.

OpenPDF for creating PDF in Java

OpenPDF is a free Java library for creating and editing PDF files with a LGPL and MPL open source license. OpenPDF is based on a fork of iText. In fact you will find the code for generating PDF using OpenPDF quite similar to iText API till version 5. OpenPDF is actively maintained and a very good option for creating PDF in Java.

Maven dependecy

For using OpenPDF library you must add the following dependencies to your pom.xml file.

For Java 8 onward-

  <dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.2.4</version>
  </dependency>
Java 7 compatible branch-
  <dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.2.3.java7</version>
  </dependency>

Creating PDF in Java using OpenPDF – Hello World

First lets see a simple example where “Hello world” is written to the PDF using a Java program. This example also shows how to set font and text color for the content written to PDF using OpenPDF.

import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class PDFGenerator {
 public static final String DEST = "./Test/hello.pdf";
 public static void main(String[] args) {
  
  try {
   Document doc = new Document();
   PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(DEST));
   //setting font family, color
   Font font = new Font(Font.HELVETICA, 16, Font.BOLDITALIC, Color.RED);
   doc.open();
   Paragraph para = new Paragraph("Hello! This PDF is created using openPDF", font);
   doc.add(para);
   doc.close();
   writer.close();   
  } catch (DocumentException | FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }   
 }
}

Created PDF

creating PDF in Java using openpdf

Generating PDF in Java using OpenPDF – Content in a Table

This example shows how to present content as a table in PDF from your Java program using OpenODF. Example uses a bean class User, fields of object of type User are displayed in the table.

User.java

public class User {

  private String firstName;
  private String lastName;
  private String email;
  private Date dob;

  public User() {
   
  }
  public User(String firstName, String lastName, String email, Date dob) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.email = email;
   this.dob = dob;
  }
  
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName(String firstName) {
   this.firstName = firstName;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName(String lastName) {
   this.lastName = lastName;
  }
  public String getEmail() {
   return email;
  }
  public void setEmail(String email) {
   this.email = email;
  }
  public Date getDob() {
   return dob;
  }
  public void setDob(Date dob) {
   this.dob = dob;
  }
}

Class used for creating PDF showing data in a table.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.netjs.Model.User;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PDFTableExample {
  public static void main(String[] args) {
    new PDFTableExample().createTablePDF("./Test/table.pdf");
  }
  private void createTablePDF(String PDFPath){
    try {
      Font font = new Font(Font.HELVETICA, 12, Font.BOLDITALIC);
      Document doc = new Document();
      PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(PDFPath));
      PdfPTable table = new PdfPTable(4);
      table.setWidthPercentage(100);
      // setting column widths
      table.setWidths(new float[] {6.0f, 6.0f, 6.0f, 6.0f});
      PdfPCell cell = new PdfPCell();
      // table headers
      cell.setPhrase(new Phrase("First Name", font));
      table.addCell(cell);
      cell.setPhrase(new Phrase("Last Name", font));
      table.addCell(cell);
      cell.setPhrase(new Phrase("Email", font));
      table.addCell(cell);
      cell.setPhrase(new Phrase("DOB", font));
      table.addCell(cell);
      List<User> users = getListOfUsers();
      // adding table rows
      for(User user : users) {
        table.addCell(user.getFirstName());
        table.addCell(user.getLastName());
        table.addCell(user.getEmail());
        table.addCell(new SimpleDateFormat("dd/MM/yyyy").format(user.getDob()));
      }
      doc.open();
      // adding table to document
      doc.add(table);
      doc.close();
      writer.close();
      System.out.println("PDF using OpenPDF created successfully");
    } catch (DocumentException | FileNotFoundException | ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() throws ParseException {
    List<User> users = new ArrayList<User>();
    Calendar dob = Calendar.getInstance();
    dob.set(1975,6,12);
    users.add(new User("Jack", "Reacher", "abc@xyz.com", dob.getTime()));
    // Using LocalDate from new time&date API Java 8 onward
    LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
    users.add(new User("Remington", "Steele", "rs@cbd.com",
      Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())));
    dob.set(1965,12,6);
    users.add(new User("Jonathan", "Raven", "jr@sn.com", dob.getTime()));
    return users;
  }
}

Created PDF

Table in PDF using OpenPDF

Creating PDF in Java using OpenPDF – Adding background image to PDF

This example shows how you can add a background image to PDF by controlling its transparency.

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfWriter;

public class ImageInPDF {

 public static void main(String[] args) {
  new ImageInPDF().setImageInPDF("./Test/image.pdf");
 }
 
 private void setImageInPDF(String PDFPath){
  try {
      Font font = new Font(Font.HELVETICA, 12, Font.ITALIC, java.awt.Color.BLUE);
      Document doc = new Document();
      PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(PDFPath));
      Image image = Image.getInstance("resources//netjs.png");
      doc.open();
      PdfContentByte canvas = writer.getDirectContentUnder();
      image.scaleAbsolute(300, 200);
      image.setAbsolutePosition(0, 600);
      canvas.saveState();
      PdfGState state = new PdfGState();
      state.setFillOpacity(0.1f);
      canvas.setGState(state);
      canvas.addImage(image);
      canvas.restoreState();
      doc.add(new Paragraph("Adding image to PDF Example", font));
      doc.close();
      writer.close();
  } catch (DocumentException | IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Created PDF

Adding image to PDF using openPDF

Creating PDF in Java using OpenPDF – Adding image to PDF

This example shows how you can add an image to PDF.

public class ImageInPDF {
 public static void main(String[] args) {
  new ImageInPDF().setImageInPDF("./Test/image.pdf");
 }
 
 private void setImageInPDF(String PDFPath){
  try {
      Font font = new Font(Font.HELVETICA, 12, Font.ITALIC, java.awt.Color.BLUE);
      Document doc = new Document();
      PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(PDFPath));
      Image image = Image.getInstance("resources//netjs.png");
      image.scaleAbsolute(300, 200);
      image.setAbsolutePosition(0, 0);
      doc.open();
      doc.add(new Paragraph("Adding image to PDF Example", font));
      doc.add(image);
      doc.close();
      writer.close();
  } catch (DocumentException | IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Creating PDF in Java using OpenPDF – Adding List to PDF

If you want to show a list of items in PDF then you can create a List and add ListItems to it. Symbol used for marking ListItems can be passed using setListSymbol() method where you can pass a unicode character. List constructor has options for numbered or lettered list. For Roman numbers there is a separate class RomanList.

public class ListInPDF {

 public static void main(String[] args) {
  new ListInPDF().setListInPDF("./Test/list.pdf");
 }
 private void setListInPDF(String PDFPath){
  try {
        
   Document document = new Document();
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
   document.open();
   Font headingFont = new Font(Font.HELVETICA, 12, Font.BOLD);
   document.add(new Paragraph("Choices Are (Using Numbers)", headingFont));
   List list = new List(List.ORDERED);
   list.setIndentationLeft(20);
   // Add ListItem objects
   list.add(new ListItem("Aerobic"));
   list.add(new ListItem("Anaerobic"));
   list.add(new ListItem("Flexibility Training"));
   // Add the list
   document.add(list);
      
   document.add(new Paragraph("Choices Are (Unordered List)", headingFont));
   list = new List(List.UNORDERED, 14);
   // Add ListItem objects
   list.add(new ListItem("Aerobic"));
   list.add(new ListItem("Anaerobic"));
   list.add(new ListItem("Flexibility Training"));
   // Add the list
   document.add(list);
      
   document.add(new Paragraph("List with a nested list", headingFont));
   Font font = new Font(Font.HELVETICA, 12, Font.ITALIC, java.awt.Color.BLUE);
   list = new List(false, List.ALPHABETICAL);
   list.add(new ListItem("Aerobic"));
   List childList = new List();
   // bullet symbol for nested list
   childList.setListSymbol("\u2022");
   childList.setIndentationLeft(20);
   childList.add(new ListItem("Running", font));
   childList.add(new ListItem("Skipping", font));
   // adding nested list
   list.add(childList);
   // Add ListItem objects
      
   list.add(new ListItem("Anaerobic"));
   list.add(new ListItem("Flexibility Training"));
   // Add the list
   document.add(list);
      
   document.add(new Paragraph("List with Roman Numerals", headingFont));
      
   List romanList = new RomanList(List.LOWERCASE, 14);
   // Add ListItem objects
   romanList.add(new ListItem("Aerobic"));
   romanList.add(new ListItem("Anaerobic"));
   romanList.add(new ListItem("Flexibility Training"));
   document.add(romanList);
   document.close();
   writer.close();
      
  } catch (DocumentException | IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Created PDF

PDF list using OpenPDF in Java

Creating PDF in Java using OpenPDF – Password protected PDF with user permissions

You can encrypt the created PDF, there are two types of passwords you can set-

  • User password
  • Owner password

The userPassword and the ownerPassword can be null or have zero length.

You can also set user permissions (operation permitted when the PDF document is opened with the user password). Available user permissions are defined in the PdfWriter class.

  • DO_NOT_ENCRYPT_METADATA
  • EMBEDDED_FILES_ONLY
  • ALLOW_PRINTING
  • ALLOW_MODIFY_CONTENTS
  • ALLOW_COPY
  • ALLOW_MODIFY_ANNOTATIONS
  • ALLOW_FILL_IN
  • ALLOW_SCREENREADERS
  • ALLOW_ASSEMBLY
  • ALLOW_DEGRADED_PRINTING
public class PDFGenerator {
 public static final String DEST = "./Test/hello.pdf";
 public static void main(String[] args) {
  final String USER_PWD="user";
  final String OWNER_PWD="owner";
  try {
   Document doc = new Document();
   PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(DEST));

   writer.setEncryption(USER_PWD.getBytes(), OWNER_PWD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); 
   //setting font family, color
   Font font = new Font(Font.HELVETICA, 16, Font.BOLDITALIC, Color.RED);
   doc.open();
   Paragraph para = new Paragraph("Hello! This PDF is created using openPDF", font);
   doc.add(para);
   doc.close();
   writer.close();   
  } catch (DocumentException | FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }   
 }
}

If you open the created PDF it will ask for the password, If you open it using the user password then you won’t be able to copy the content as per the user permission settings.

Creating PDF in Java using OpenPDF – Rendered to browser as web response

PDFWriter constructor accepts an OutputStream as parameter. If you want to write a web application, then you can pass a ServletOutputStream.

  try{
   response.setContentType("application/pdf");
   Document doc = new Document();
   PdfWriter writer = PdfWriter.getInstance(doc, response.getOutputStream());
   //setting font family, color
   Font font = new Font(Font.HELVETICA, 16, Font.BOLDITALIC, Color.RED);
   doc.open();
   Paragraph para = new Paragraph("Hello! This PDF is created using openPDF as a web response", font);
   doc.add(para);
   doc.close();
   writer.close();
  }catch(Exception e){
      e.printStackTrace();
  }
 }
PDF as webresponse using openpdf

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic Creating PDF in Java Using OpenPDF. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Create PDF From XML Using Apache FOP
  2. Spring MVC PDF Generation Example
  3. How to Untar a File - Java Program
  4. How to Read Excel File in Java Using Apache POI
  5. Converting String to float - Java Program

You may also like-

  1. If Given String Sub-Sequence of Another String - Java Program
  2. Matrix Multiplication - Java Program
  3. How to Convert Date to String in Java
  4. How to Compile Java Program at Runtime
  5. Externalizable Interface in Java
  6. DatabaseMetaData Interface in Java-JDBC
  7. Try-With-Resources in Java Exception Handling
  8. Internationalization (i18n) Using MessageSource in Spring