使⽤iText库创建PDF⽂件
前⾔
译⽂连接:
对于excel⽂件的读写操作,相信⼤家都⽐较熟悉,使⽤apache的POI库即可。本篇⽂章,我将基于iText库编写各式各样的代码⽰例去创建PDF⽂件。这些例⼦会按它们各⾃的功能分类,为了使⼤家能更加形象的看到代码所⽣成的PDF⽂件内容,每⼀个例⼦我都会附加上⼀张PDF⽂件截图。我已经尽可能的把我能到的有⽤的例⼦放在这⾥,如果你觉得我错过了⼀些⽤例,随时在评论⾥留下你的建议,我会把这些例⼦添加进去。
iT e x t库概述
好的⼀⾯是,iText是开源的API,但是需要注意,虽然iText是开源,如果你出于商业⽬的使⽤它,仍然需要购买商业许可证。你可以从itextpdf上免费获取iText的Java类库,iText库⾮常强⼤,⽀持HTML、RTF、XML以及PDF⽂件的⽣产,你可以在⽂档中使⽤各种各样的字体,并且,还可以使⽤同样的代码⽣成上述不同类型的⽂件,这真的是⼀个很棒的特性,不是吗?
iText库包含⼀系列接⼝,可以⽣成不同字体的PDF⽂件,在PDF中创建表格,添加⽔印等等功能。当然,i
Text还有许许多多其它的功能,这将留给读者去探索。
如果你的项⽬是maven⼯程的话,在l⽂件中添加如下依赖,即可以给⾃⼰的应⽤程序添加iText库⽀持。
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
当然,你也可以⾃⼰去下载最新的jar⽂件,然后添加到⼯程⾥,。
iT e x t库常⽤类
让我们先列出⼏个接下来例⼦中要⽤到的重要的类,熟悉熟悉。
Document:这是iText库中最常⽤的类,它代表了⼀个pdf实例。如果你需要从零开始⽣成⼀个PDF⽂件,你需要使⽤这个Document类。⾸先创建(new)该实例,然后打开(open)它,并添加(add)内容,最后关闭(close)该实例,即可⽣成⼀个pdf⽂件。
Paragraph:表⽰⼀个缩进的⽂本段落,在段落中,你可以设置对齐⽅式,缩进,段落前后间隔等。
Chapter:表⽰PDF的⼀个章节,他通过⼀个Paragraph类型的标题和整形章数创建。
Font:这个类包含了所有规范好的字体,包括family of font,⼤⼩,样式和颜⾊,所有这些字体都被声明为静态常量。
List:表⽰⼀个列表;
pdf.PDFPTable:表⽰⼀个表格;
Anchor:表⽰⼀个锚,类似于HTML页⾯的链接。
pdf.PdfWriter:当这个PdfWriter被添加到PdfDocument后,所有添加到Document的内容将会写⼊到与⽂件或⽹络关联的输出流中。
pdf.PdfReader:⽤于读取PDF⽂件;
iT e x t He llo Wor ld⽰例
让我们先从简单的“Hello World”程序开始,在这个程序中,我将会创建⼀个PDF⽂件,⾥⾯的内容为⼀条简单的语句。
package cn.edu.hdu.chenpi.cpdemo.itext;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import Document;
import DocumentException;
import Paragraph;
import pdf.PdfWriter;
public class JavaPdfHelloWorld {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter writer = Instance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
给PD F⽂件设置⽂件属性
这个例⼦将展⽰如何给PDF⽂件设置各种属性,如作者名字,创建⽇期,创建者,或者标题。
Document document = new Document();
try
{
PdfWriter writer = Instance(document, new FileOutputStream("SetAttributeExample.pdf"));            document.open();
document.add(new Paragraph("Some content here"));
//Set attributes here
document.addAuthor("Lokesh Gupta");
document.addCreationDate();
document.addCreator("HowToDoInJava");
document.addTitle("Set Attribute Example");
java创建文件document.addSubject("An example to show how attributes can be added to pdf files.");
document.close();
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
PD F中添加图⽚
下⾯例⼦展⽰如何往PDF⽂件中添加图⽚。例⼦中图⽚来源包含了两种⽅式:本地图⽚或URL。
并且,我添加了⼀些代码,⽤于设置图⽚在⽂档中的位置。
Document document = new Document();
try
{
PdfWriter writer = Instance(document, new FileOutputStream("AddImageExample.pdf"));            document.open();
document.add(new Paragraph("Image Example"));
//Add Image
Image image1 = Instance("C:\\temp.jpg");
//Fixed Positioning
image1.setAbsolutePosition(100f, 550f);
//Scale to new height and new width of image
image1.scaleAbsolute(200, 200);
//Add to document
document.add(image1);
String imageUrl = "/xtend/images/java8_logo.png";            Image image2 = Instance(new URL(imageUrl));
document.add(image2);
document.close();
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
PD F中创建表格
以下代码展⽰了如何在PDF⽂件中创建表格
Document document = new Document();
try {
PdfWriter writer = Instance(document,
new FileOutputStream("AddTableExample.pdf"));
document.open();
PdfPTable table = new PdfPTable(3); // 3 columns.
table.setWidthPercentage(100); // Width 100%
table.setSpacingBefore(10f); // Space before table
table.setSpacingAfter(10f); // Space after table
/
/ Set Column widths
float[] columnWidths = { 1f, 1f, 1f };
table.setWidths(columnWidths);
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
cell1.setBorderColor(BaseColor.BLUE);
cell1.setPaddingLeft(10);
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
cell2.setBorderColor(BaseColor.GREEN);
cell2.setPaddingLeft(10);
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
cell3.setBorderColor(BaseColor.RED);
cell3.setPaddingLeft(10);
cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
// To avoid having the cell border and the content overlap, if you
// are having thick cell borders
// cell1.setUserBorderPadding(true);
// cell2.setUserBorderPadding(true);
/
/ cell3.setUserBorderPadding(true);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
PD F中创建列表
这个例⼦将会帮助你理解iText库是如何在PDF⽂件⾥创建列表的。
Document document = new Document();
try
{
PdfWriter writer = Instance(document, new FileOutputStream("ListExample.pdf"));            document.open();
document.add(new Paragraph("List Example"));
//Add ordered list
List orderedList = new List(List.ORDERED);
orderedList.add(new ListItem("Item 1"));
orderedList.add(new ListItem("Item 2"));
orderedList.add(new ListItem("Item 3"));
document.add(orderedList);
//Add un-ordered list
List unorderedList = new List(List.UNORDERED);
unorderedList.add(new ListItem("Item 1"));
unorderedList.add(new ListItem("Item 2"));
unorderedList.add(new ListItem("Item 3"));
document.add(unorderedList);
//Add roman list
RomanList romanList = new RomanList();
romanList.add(new ListItem("Item 1"));
romanList.add(new ListItem("Item 2"));
romanList.add(new ListItem("Item 3"));
document.add(romanList);
//Add Greek list
GreekList greekList = new GreekList();
greekList.add(new ListItem("Item 1"));
greekList.add(new ListItem("Item 2"));
greekList.add(new ListItem("Item 3"));
document.add(greekList);
//ZapfDingbatsList List Example
ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
zapfDingbatsList.add(new ListItem("Item 1"));
zapfDingbatsList.add(new ListItem("Item 2"));
zapfDingbatsList.add(new ListItem("Item 3"));
document.add(zapfDingbatsList);
//List and Sublist Examples
List nestedList = new List(List.UNORDERED);
nestedList.add(new ListItem("Item 1"));
List sublist = new List(true, false, 30);
sublist.setListSymbol(new Chunk("", Font(FontFactory.HELVETICA, 6)));
sublist.add("A");
sublist.add("B");
nestedList.add(sublist);
nestedList.add(new ListItem("Item 2"));
sublist = new List(true, false, 30);
sublist.setListSymbol(new Chunk("", Font(FontFactory.HELVETICA, 6)));
sublist.add("C");
sublist.add("D");
nestedList.add(sublist);
document.add(nestedList);
document.close();
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
View Code
PD F中设置样式/格式化输出
让我们来看⼀些给PDF⽂件内容设置样式的例⼦,例⼦中包含了字体、章、节的使⽤。
Font blueFont = Font(FontFactory.HELVETICA, 8, Font.NORMAL, new CMYKColor(255, 0, 0, 0));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。