If you have to generate a PDF using a Java program first option that comes to mind or even in search is iText. Though PDF in Java using iText is one of the best option but there is one hiccup; though iText is open source it uses AGPL license which means you need to share your entire application for free under the same AGPL license. If that is a problem for you then another option is to use OpenPDF to generate PDF in Java.
PDFBox is another option for generating PDF in Java. For examples using PDFBox check this post- Generating PDF in Java Using PDFBox Tutorial
OpenPDF licensing
OpenPDF is open source software with a LGPL and MPL license. One thing to note is that OpenPDF is a fork of iText version 4. Beginning with version 5.0 of iText, the developers have moved to the AGPL to improve their ability to sell commercial licenses.
Maven Dependency for OpenPDF
You need to add the following dependency to get the latest OpenPDF version (Please check the current version).
<dependency> <groupId>com.github.librepdf</groupId> <artifactId>openpdf</artifactId> <version>1.3.27</version> </dependency>
Examples of PDF generation using OpenPDF and Java given in this post.
HelloWorld PDF using Java and OpenPDF
We’ll start with creating a simple HelloWorld PDF which also shows font and text color settings for the content. Creating PDF using OpenPDF consists of following steps.
- Create an instance of Document.
- Get PDFWriter instance that wraps the document and directs a PDF-stream to a file.
- Open the document
- Add content (paragraph) to the document
- Close the document
import java.awt.Color; 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.Paragraph; import com.lowagie.text.pdf.PdfWriter; public class HelloWorldPDF { public static final String CREATED_PDF = "F://knpcode//result//OpenPDF//HelloWorld.pdf"; public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document,new FileOutputStream(CREATED_PDF)); document.open(); // font and color settings Font font = new Font(Font.TIMES_ROMAN, 18, Font.NORMAL, Color.MAGENTA); Paragraph para = new Paragraph("Hello World PDF created using OpenPDF", font); document.add(para); } catch (DocumentException | IOException de) { System.err.println(de.getMessage()); } document.close(); } }
Converting text file to PDF using OpenPDF
In the Java example there is a text file (Test.txt) which is converted to a PDF using OpenPDF.
import java.awt.Color; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; 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 HelloWorldPDF { public static final String SOURCE_FILE = "F://knpcode//result//Test.txt"; public static final String CREATED_PDF = "F://knpcode//result//OpenPDF//Content.pdf"; public static void main(String[] args) { Document document = new Document(); try { BufferedReader br = new BufferedReader(new FileReader(SOURCE_FILE)); PdfWriter.getInstance(document,new FileOutputStream(CREATED_PDF)); document.open(); // font and color settings Font font = new Font(Font.COURIER, 15, Font.NORMAL, Color.BLUE); String line; while ((line = br.readLine()) != null) { document.add(new Paragraph(line, font)); } br.close(); } catch (DocumentException | IOException de) { System.err.println(de.getMessage()); } document.close(); } }
PDF with table using OpenPDF
For this example we’ll use a bean class Employee and the list of employees is presented in a table in the PDF using Java program.
public class Employee { private String name; private String dept; private int salary; Employee(String name, String dept, int salary){ this.name = name; this.dept = dept; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } }
import java.awt.Color; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import com.lowagie.text.Cell; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Phrase; import com.lowagie.text.Table; import com.lowagie.text.alignment.HorizontalAlignment; import com.lowagie.text.alignment.VerticalAlignment; import com.lowagie.text.pdf.PdfWriter; public class PDFWithTable { public static final String CREATED_PDF = "F://knpcode//result//OpenPDF//PDFWithTable.pdf"; public static void main(String[] args) { Document document = null; try { document = new Document(); PdfWriter.getInstance(document,new FileOutputStream(CREATED_PDF)); Font font = new Font(Font.HELVETICA, 12, Font.BOLD); Table table = new Table(3); table.setPadding(5); table.setSpacing(1); table.setWidth(100); // Setting table headers Cell cell = new Cell("Employee Information"); cell.setHeader(true); cell.setVerticalAlignment(VerticalAlignment.CENTER); cell.setHorizontalAlignment(HorizontalAlignment.CENTER); cell.setColspan(3); cell.setBackgroundColor(Color.LIGHT_GRAY); table.addCell(cell); table.addCell(new Phrase("Name", font)); table.addCell(new Phrase("Dept", font)); table.addCell(new Phrase("Salary", font)); table.endHeaders(); // Employee information to table cells List<Employee> employees = getEmployees(); for(Employee emp : employees) { table.addCell(emp.getName()); table.addCell(emp.getDept()); table.addCell(Integer.toString(emp.getSalary())); } document.open(); document.add(table); document.close(); } catch (DocumentException | FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // create a list of employees private static List<Employee> getEmployees() { List<Employee> employees = new ArrayList<>(); employees.add(new Employee("Jack", "HR", 12000)); employees.add(new Employee("Liza", "IT", 5000)); employees.add(new Employee("Jeremy", "Finance", 9000)); employees.add(new Employee("Frederick", "Accounts", 8000)); return employees; } }
Adding image to PDF using OpenPDF
Adding image to PDF which is stored in the images folder.
import java.awt.Color; 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.PdfWriter; public class ImagePDF { public static final String CREATED_PDF = "F://knpcode//result//OpenPDF//Image.pdf"; public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(CREATED_PDF)); Font font = new Font(Font.HELVETICA, 12, Font.NORMAL, Color.RED); // Image instance Image image = Image.getInstance("images//Image OpenPDF.png"); document.open(); document.add(new Paragraph("In this PDF which is created using OpenPDF an image is added", font)); document.add(image); document.close(); } catch (DocumentException | IOException de) { System.err.println(de.getMessage()); } document.close(); } }
Render PDF in web application using OpenPDF
For rendering PDF to the browser using OpenODF requires using ServletOutputStream as a parameter with PDFWriter. You can get this OutputStream from HTTPResponse.
try{ response.setContentType("application/pdf"); Document doc = new Document(); PdfWriter.getInstance(doc, response.getOutputStream()); //Font settings Font font = new Font(Font.TIMES_ROMAN, 15, Font.BOLD, Color.BLUE); doc.open(); Paragraph para = new Paragraph("This PDF is rendered as a web response using OpenODF.", font); doc.add(para); doc.close(); }catch(Exception e){ e.printStackTrace(); }
Adding list to PDF using OpenPDF
If you want to add list items to a PDF you can do that using-
- ListItem class that creates list items.
- List class to create a List that holds the list items.
With in List class there are some constants like ORDERED, NUMERICAL, ALPHABETICAL that can be used for numbering the list items.
You can also set a symbol for list items by using setListSymbol()
method.
There are also specialized classes RomanList
and GreekList
that extends List class and provides
support for Roman letters and Greek letters respectively.
import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.List; import com.lowagie.text.ListItem; import com.lowagie.text.Paragraph; import com.lowagie.text.RomanList; import com.lowagie.text.pdf.PdfWriter; public class ListItems { public static final String CREATED_PDF = "F://knpcode//result//OpenPDF//List.pdf"; public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(CREATED_PDF)); document.open(); document.add(new Paragraph("List with Numbers")); List list = new List(List.ORDERED); list.setIndentationLeft(15); list.add(new ListItem("Item1")); list.add(new ListItem("Item2")); list.add(new ListItem("Item3")); document.add(list); document.add(new Paragraph("List with Alphabets Uppercase")); list = new List(false, List.ALPHABETICAL); list.setIndentationLeft(15); list.add(new ListItem("Item1")); list.add(new ListItem("Item2")); list.add(new ListItem("Item3")); document.add(list); document.add(new Paragraph("List with Roman Numerals")); List romanList = new RomanList(List.UPPERCASE, 14); // Add ListItem objects romanList.add(new ListItem("Item1")); romanList.add(new ListItem("Item2")); romanList.add(new ListItem("Item3")); document.add(romanList); document.add(new Paragraph("List with Nested List")); list = new List(false, List.ALPHABETICAL); list.setIndentationLeft(15); list.add(new ListItem("Item1")); // Nested List List nestedList = new List(); nestedList.setIndentationLeft(20); nestedList.setListSymbol("\u2022"); nestedList.add(new ListItem("Item2")); nestedList.add(new ListItem("Item3")); list.add(nestedList); list.add(new ListItem("Item4")); document.add(list); document.close(); } catch (DocumentException | IOException de) { System.err.println(de.getMessage()); } document.close(); } }
That's all for the topic Generating PDF in Java Using OpenPDF Tutorial. If something is missing or you have something to share about the topic please write a comment.
You may also like
No comments:
Post a Comment