在Java中使用OpenPDF生成PDF教程
如果我们必须使用Java程序生成PDF,则想到的第一个选择就是iText。尽管使用iText的Java中的PDF是最好的选择之一,但是却有一个小问题。尽管iText是开源的,但它使用AGPL许可证,这意味着我们需要在同一AGPL许可证下免费共享整个应用程序。如果这对我们来说是个问题,那么另一种选择是使用OpenPDF在Java中生成PDF。
PDFBox是用于用Java生成PDF的另一个选项。有关使用PDFBox的示例,请查看本文。使用PDFBox教程在Java中生成PDF。
OpenPDF许可
OpenPDF是具有LGPL和MPL许可证的开源软件。需要注意的一点是,OpenPDF是iText版本4的分支。从iText版本5.0开始,开发人员已转向AGPL以提高其销售商业许可证的能力。
OpenPDF的Maven依赖
OpenPDF的最新版本是1.2.17版,我们需要添加以下依赖性以获得最新的OpenPDF版本。
<dependency> <groupId>com.github.librepdf</groupId> <artifactId>openpdf</artifactId> <version>1.2.17</version> </dependency>
使用Java和OpenPDF的HelloWorld PDF
我们将首先创建一个简单的HelloWorld PDF,它还会显示内容的字体和文本颜色设置。使用OpenPDF创建PDF包含以下步骤。
创建一个Document实例。
获取包装文档并将PDF流定向到文件的PDFWriter实例。
打开文件
在文档中添加内容(段落)
关闭文件
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://theitroad//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(); } }
使用OpenPDF将文本文件转换为PDF
在Java示例中,有一个文本文件(Test.txt),可使用OpenPDF转换为PDF。
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://theitroad//result//Test.txt"; public static final String CREATED_PDF = "F://theitroad//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(); } }
使用OpenPDF和表格的PDF
在此示例中,我们将使用Bean类Employee,雇员列表在使用Java程序的PDF表格中显示。
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://theitroad//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("Hyman", "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; } }
使用OpenPDF将图像添加到PDF
将图像添加到存储在图像文件夹中的PDF。
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://theitroad//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(); } }
使用OpenPDF在Web应用程序中渲染PDF
为了使用OpenODF将PDF呈现给浏览器,需要使用ServletOutputStream作为PDFWriter的参数。我们可以从HTTPResponse获取此OutputStream。
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(); }
使用OpenPDF将列表添加到PDF
如果我们想将列表项添加到PDF中,可以使用
创建列表项的ListItem类。
List类可创建一个保存列表项的List。
在List类中,可以使用一些常量(例如ORDERED,NUMERICAL,ALPHABETICAL)对列表项进行编号。
我们还可以使用setListSymbol()方法为列表项设置符号。
还有专门的类RomanList和GreekList,它们扩展了List类并分别支持罗马字母和希腊字母。
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://theitroad//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(); } }