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:即无法找到相关密码术的包。
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 emptydocument.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);// LEFTcanvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);// RIGHTcanvas.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  转载请注明出处*************

iText操作PDF之学习笔记相关推荐

  1. 使用ITEXT操作PDF文件

    2019独角兽企业重金招聘Python工程师标准>>> 使用ITEXT操作PDF文件 pom.xml <dependency><groupId>com.ite ...

  2. itext操作pdf文档

    关于itext操作pdf文档 pdf基本操作 自己点击链接去看下就会了 java使用itext生成pdf 再不行,去看官方文档 itext Api 直接找到com.itextpdf.text.pdf这 ...

  3. 利用itext操作pdf从数据库导出大量数据--添加水印(四)

    [原始需求] 通过SQL及JDBC模式导出各类业务数据,以PDF文件格式存放,要求该文件只能查看和打印(不能编辑和篡改),文件要有公司相关标志和水印功能. [需求分析] 1. 通过SQL及JDBC模式 ...

  4. 利用itext操作pdf从数据库导出大量数据--功能汇总(一)

    [原始需求] 通过SQL及JDBC模式导出各类业务数据,以PDF文件格式存放,要求该文件只能查看和打印(不能编辑和篡改),文件要有公司相关标志和水印功能. [需求分析] 1. 通过SQL及JDBC模式 ...

  5. stm32读操作失败_STM32学习笔记—通信容易出错的情况

    I²C:全称为Inter-Integrated Circuit(内部集成电路),是一种串行通讯总线,常用于嵌入式电子产品中. 这是第4篇分享,<STM32学习笔记>之I2C通信容易出错的情 ...

  6. itex将html转成pdf加水印,itext操作PDF文件添加水印

    功能描述:添加图片和文字水印 /** * * [功能描述:添加图片和文字水印] [功能详细描述:功能详细描述] * @param srcFile 待加水印文件 * @param destFile 加水 ...

  7. stm32单片机c语言入门 pdf,STM32学习笔记(初学者快速入门).pdf

    STM32 学习笔记 从51 开始,单片机玩了很长时间了,有51,PIC,AVR 等等,早就想跟潮 流玩玩ARM ,但一直没有开始,原因不知道玩了ARM 可以做什么(对我自 己而言).如果为学习而学习 ...

  8. 【原】无脑操作:ElasticSearch学习笔记(01)

    开篇来自于经典的"保安的哲学三问"(你是谁,在哪儿,要干嘛) 问题一.ElasticSearch是什么?有什么用处? 答:截至2018年12月28日,从ElasticSearch官 ...

  9. 使用Itext操作PDF,修改文本内容及指定位置插入图片

    参考博客:修改文本的 参考博客:插入图片的 这里基于修改文本的博客编写的,主要解决了几个问题: 1.文件乱码 2.设置区域背景色 3.设置文字字体颜色 4.插入图片空指针 5.指定位置插入偏移 等等问 ...

最新文章

  1. stm32 hal uart_STM32 非阻塞HAL_UART_Receive_IT解析与实际应用
  2. entity framework5 sqlserver2005 事务(TransactionScope)报未启用MSDTC错误解决办法
  3. mysql 缺省配置 崩溃_MySQL5.6初始配置调优_MySQL
  4. 刷爆了!程序员都在点赞的Python学习图谱安利给你!
  5. 计算机病毒与恶意软件
  6. 信息化建设项目前期方案编写1:设计要点
  7. 苹果手机温度测试软件,苹果手机测温神器上线啦!
  8. 计算机网络——ALOHA协议
  9. 想将PPT的文字转换到Word文档?看这一篇就够了!!!
  10. rounding mode
  11. 以汽车制造业为例,细说制造企业如何实施PLM系统项目?
  12. 解决Unity3D中多层级结构子物体旋转受父物体尺寸影响的问题
  13. RecyclerView多级目录实现
  14. Windows下压缩和解压命令
  15. ENGEL恩格尔注塑机手柄控制器操作屏KeTop C70E15维修概述
  16. arduinohanshu_Arduino 函数的位操作
  17. hive/spark 获取当季度最后一天和最后一天
  18. log4j配置详解以及模板
  19. 路由器linux系统负载,linux 系统负载 释义
  20. 【人文】找贵人扶持,事半功倍

热门文章

  1. 匿名内部类,最全讲解
  2. qt 编译的时候把源文件复制到编译目录_[QT]读写Excel
  3. 【Unity 粒子系统】Collision 模块
  4. 银河麒麟v10版本OpenDDS使用教程
  5. html邮箱图标代码,将图像嵌入html电子邮件
  6. 软件测试面试题-Linux
  7. Condition和 AQS 原理
  8. MyBatis框架的作用
  9. 全军出击机器人进房间_绝地求生:全军出击虐机器人,刺激战场BUG,玩家两个都已卸载...
  10. 微信小程序大转盘抽奖概率算法实现