iText是Java中用于创建和操作PDF文件的开源库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。
注:本文本分内容参照了rensanning的博客:http://rensanning.iteye.com/blog/1538689
http://itextpdf.com/
版本:itextpdf-5.5.3.jar
1、生成我的第一个PDF文件
public class ITextDemo {
public static void main(String[] args) {
ITextDemo pdf = new ITextDemo();
String fileName = "D:/temp/myFirstPDF.pdf";
pdf.createPDF(fileName);
}
//生成PDF文件中的内容
public void createPDF(String fileName){
File file = new File(fileName);
FileOutputStream out = null ;
Document document = new Document(PageSize.A4,50,50,50,50);
try{
//实例化文档对象
out = new FileOutputStream(file);
//创建写入器
@SuppressWarnings("unused")
PdfWriter writer = PdfWriter.getInstance(document,out);
//打开文档准备写入内容
document.open();
document.add(new Paragraph("Hello World!"));
//关闭文档
document.close();
System.out.println("PDF文件生成成功,PDF文件名:"+file.getAbsolutePath());
} catch(DocumentException e){
System.out.println("PDF文件"+file.getAbsolutePath()+"生成失败!"+e);
e.printStackTrace();
} catch(IOException ee){
System.out.println("PDF文件"+file.getAbsolutePath()+"生成失败!"+ee);
ee.printStackTrace();
} finally{
if(out!=null){
try{
//关闭输出文件流
out.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}
}
得到结果:
2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords
//页面大小
Rectangle rect = new Rectangle(PageSize.B5.rotate());
//页面背景色
rect.setBackgroundColor(BaseColor.ORANGE);
Document doc = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(doc, out);
//PDF版本(默认1.4)
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
//文档属性
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");
//页边空白
doc.setMargins(10, 20, 30, 40);
doc.open();
doc.add(new Paragraph("Hello World"));
结果如下:
3、设置密码
此处需要用到Bouncy Castle-轻量级密码术包(bcprov-jdk15on-151.jar),可以到网站:http://www.bouncycastle.org/java.html下载最新的Jar包
否则会出现如下错误:Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable:即无法找到相关密码术的包。
否则会出现如下错误:Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable:即无法找到相关密码术的包。
PdfWriter writer = PdfWriter.getInstance(doc, out);
// 设置用户密码为:"World" 主人密码:"Hello"
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.STANDARD_ENCRYPTION_128);
doc.open();
doc.add(new Paragraph("Hello World"));
结果如下:
4、添加Page
document.open();
document.add(new Paragraph("First page"));
document.add(new Paragraph("Next page will be empty!"));
document.newPage();
writer.setPageEmpty(false); //Use this method to make sure a page is added, even if it's empty
document.newPage();
document.add(new Paragraph("New page"));
5、添加水印(图片水印和文字水印)
/**
*
* @param inPdfFile 要加水印的pdf文件路径
* @param outPdfFile 加了水印后要输出的pdf文件路径
* @param markImagePath 水印图片路径
* @throws Exception
*/
public static void addPdfMark(String inPdfFile, String outPdfFile, String markImagePath) throws Exception{
//图片水印
PdfReader reader = new PdfReader(inPdfFile, "PDF".getBytes());
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
Image img = Image.getInstance(markImagePath);
img.setAbsolutePosition(50, 100);
PdfContentByte under = stamp.getUnderContent(1); //第一页加水印图
under.addImage(img);
//文字水印
PdfContentByte over = stamp.getOverContent(2); //第二页加水印文字
over.beginText();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
BaseFont.EMBEDDED);
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
over.endText();
//背景图
Image img2 = Image.getInstance(markImagePath);
img2.setAbsolutePosition(50, 100);
int pageSize = reader.getNumberOfPages(); //取得Pdf文件的总页数
for(int i = 3 ; i <= pageSize ; i++ ){
PdfContentByte under2 = stamp.getUnderContent(i); //第三页开始以后每一页都加水印图片
under2.addImage(img2);
}
stamp.close();
reader.close();
}
6、插入Chunk, Phrase, Paragraph, List
//Chunk对象: a String, a Font, and some attributes
document.add(new Chunk("China"));
document.add(new Chunk(" "));
Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id = new Chunk("chinese", font);
id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.setTextRise(6);
document.add(id);
document.add(Chunk.NEWLINE);
document.add(new Chunk("Japan"));
document.add(new Chunk(" "));
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id2 = new Chunk("japanese", font2);
id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.setTextRise(6);
id2.setUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);
//Phrase对象: a List of Chunks with leading
document.newPage();
document.add(new Phrase("Phrase page"));
Phrase director = new Phrase();
Chunk name = new Chunk("China");
name.setUnderline(0.2f, -2f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk("chinese"));
director.setLeading(24);
document.add(director);
Phrase director2 = new Phrase();
Chunk name2 = new Chunk("Japan");
name2.setUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk("japanese"));
director2.setLeading(24);
document.add(director2);
//Paragraph对象: a Phrase with extra properties and a newline
document.newPage();
document.add(new Paragraph("Paragraph page"));
Paragraph info = new Paragraph();
info.add(new Chunk("China "));
info.add(new Chunk("chinese"));
info.add(Chunk.NEWLINE);
info.add(new Phrase("Japan "));
info.add(new Phrase("japanese"));
document.add(info);
//List对象: a sequence of Paragraphs called ListItem
document.newPage();
List list = new List(List.ORDERED);
for (int i = 0; i < 10; i++) {
ListItem item = new ListItem(String.format("%s: %d movies",
"country" + (i + 1), (i + 1) * 100), new Font(
Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
List movielist = new List(List.ORDERED, List.ALPHABETICAL);
movielist.setLowercase(List.LOWERCASE);
for (int j = 0; j < 5; j++) {
ListItem movieitem = new ListItem("Title" + (j + 1));
List directorlist = new List(List.UNORDERED);
for (int k = 0; k < 3; k++) {
directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
"Name2" + (k + 1)));
}
movieitem.add(directorlist);
movielist.add(movieitem);
}
item.add(movielist);
list.add(item);
}
document.add(list);
7、插入Anchor, Image, Chapter, Section
//Anchor对象: internal and external links 表示 HTML 超链接
Paragraph country = new Paragraph();
Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
dest.setName("CN");
dest.setReference("http://www.china.com");//external
country.add(dest);
country.add(String.format(": %d sites", 10000));
document.add(country);
document.newPage();
Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
toUS.setReference("#CN");//internal
document.add(toUS);
//Image对象
document.newPage();
Image img = Image.getInstance("resource/test.jpg");
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(1000, 72);//大小
img.setRotationDegrees(-30);//旋转
document.add(img);
//Chapter, Section对象(目录)
document.newPage();
Paragraph title = new Paragraph("Title");
Chapter chapter = new Chapter(title, 1);
title = new Paragraph("Section A");
Section section = chapter.addSection(title);
section.setBookmarkTitle("bmk");
section.setIndentation(30);
section.setBookmarkOpen(false);
section.setNumberStyle(
Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
Section subsection = section.addSection(new Paragraph("Sub Section A"));
subsection.setIndentationLeft(20);
subsection.setNumberDepth(1);
document.add(chapter);
8、画图
//左右箭头
document.add(new VerticalPositionMark() {
public void draw(PdfContentByte canvas, float llx, float lly,
float urx, float ury, float y) {
canvas.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
canvas.setFontAndSize(bf, 12);
// LEFT
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
// RIGHT
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
canvas.endText();
}
});
//直线
Paragraph p1 = new Paragraph("LEFT");
p1.add(new Chunk(new LineSeparator()));
p1.add("R");
document.add(p1);
//点线
Paragraph p2 = new Paragraph("LEFT");
p2.add(new Chunk(new DottedLineSeparator()));
p2.add("R");
document.add(p2);
//下滑线
LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
p3.add(UNDERLINE);
document.add(p3);
9、设置段落
Paragraph p = new Paragraph("In the previous example, you added a header and footer with the showTextAligned() method. This example demonstrates that it’s sometimes more interesting to use PdfPTable and writeSelectedRows(). You can define a bottom border for each cell so that the header is underlined. This is the most elegant way to add headers and footers, because the table mechanism allows you to position and align lines, images, and text.");
//默认
p.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(p);
document.newPage();
p.setAlignment(Element.ALIGN_JUSTIFIED);
p.setIndentationLeft(1 * 15f);
p.setIndentationRight((5 - 1) * 15f);
document.add(p);
//居右
document.newPage();
p.setAlignment(Element.ALIGN_RIGHT);
p.setSpacingAfter(15f);
document.add(p);
//居左
document.newPage();
p.setAlignment(Element.ALIGN_LEFT);
p.setSpacingBefore(15f);
document.add(p);
//居中
document.newPage();
p.setAlignment(Element.ALIGN_CENTER);
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);
document.add(p);
10、插入表格
//插入表格
//创建表格
int colNums = 2 ; //创建一个两列的表格
PdfPTable table = new PdfPTable(colNums);
int[] widths = {50,50} ; //percentage
table.setWidths(widths); //设置列宽度
//边框属性
table.getDefaultCell().setBorderColor(new BaseColor(220,155,100)); //边框颜色
table.getDefaultCell().setPadding(1); //space between content and border
table.getDefaultCell().setSpaceCharRatio(1); // Sets the ratio between the extra word spacing and the extra character spacing when the text is fully justified.
table.getDefaultCell().setBorderWidth(1); //Sets the borderwidth of the table.
//设置可以在PDF中输入汉字的字体
BaseFont bfChinese = BaseFont.createFont("C:\\WINDOWS\\Fonts\\SIMHEI.TTF",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
Font font21 = new Font(bfChinese,12,Font.NORMAL);
font21.setColor(0,0,0);
//添加表头信息
table.addCell(new Phrase("方法名称",font21));
table.addCell(new Phrase("用法",font21));
table.setHeaderRows(0);
//添加表格内容
table.addCell(new Phrase("public Boolean canw()"));
table.addCell(new Phrase("测试这个文件是否可以读?",font21));
table.addCell(new Phrase("public Boolean canwrite()"));
table.addCell(new Phrase("测试这个文件是否可写?",font21));
table.addCell(new Phrase("public Boolean createNewFile()"));
table.addCell(new Phrase("看这个文件或目录是否存在,如有此文件则返回false,如果没有这个文件则创建这个类的对象",font21));
table.addCell(new Phrase("public Boolean delete()"));
table.addCell(new Phrase("删除当前对象所指的文件,删除成功则返回true,否则返回false",font21));
document.add(table);
显示结果如下:
*************by jixiangrurui 转载请注明出处*************