一、Itext简介

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

iText的安装非常方便,在http://www.lowagie.com/iText/download.html网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。

二、生成PDF步骤

1、创建文档对象实例

Document document = new Document();

2、建立书写器(Writer)与文档对象(document)关联,通过书写器将文档写入磁盘

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));

DEST:生成PDF文件

3、打开文档

document.open();

4、向文档中添加内容

document.add(new Paragraph("PDF demo"));

5、关闭文档

document.close();

三、具体分析

1、对象实例

public document();

public document(Rectangle pageSize);

public document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);

pageSize是指文档页面大小,public document();页面大小为A4,效果等同于Document(PageSize.A4);

marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距。

通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144, 720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。

2、书写器对象

一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体文档存盘成需要的格式。

PDFWriter可以将文档存成PDF文件;HtmlWriter可以将文档存成html文件

3、文档属性

在文档打开之前,可以设定文档的标题、主题、作者、关键字、装订方式、创建者、生产者、创建日期等属性,调用的方法分别是:

public boolean addTitle(String title) 

public boolean addSubject(String subject) 

public boolean addKeywords(String keywords) 

public boolean addAuthor(String author) 

public boolean addCreator(String creator) 

public boolean addProducer() 

public boolean addCreationDate() 

public boolean addHeader(String name, String content)

其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息。

当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:

public boolean setPageSize(Rectangle pageSize) 

public boolean add(Watermark watermark) 

public void removeWatermark() 

public void setHeader(HeaderFooter header) 

public void resetHeader() 

public void setFooter(HeaderFooter footer) 

public void resetFooter() 

public void resetPageCount() 

public void setPageCount(int pageN)

如果要设定第一面的页面属性,这些方法必须在文档打开前调用。

对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的 setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性。

另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性。

4、添加文档内容

所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。

IText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:

Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE)); 

短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块(Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中,如:phrase6.add(chunk);

段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。通过函数setAlignment可以设定段落的对齐方式,setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。

Itext中处理表格在有PDFTable,Table。对于简单在表格处理可以用Table,但如果要处理复杂的表格就需要PDFTable进行处理。

创建表格时,必须要指定列,行则不是必须的。

建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。

IText中处理图像的类为Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。

Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");

四、例子
 1、IText添加水印,并且增加权限
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;public class JinzhiCopy {public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {// TODO Auto-generated method stubString srcFile="E:\\pdfile\\NeedToDo\\Jiemi\\Test.pdf";//要添加水印的文件  String text="";int textWidth=200;int textHeight=440;PdfReader reader = new PdfReader(srcFile);// 待加水印的文件PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File("E:\\pdfile\\NeedToDo\\Jiemi\\addWaterTest.pdf")));// 加完水印的文件byte[] ownerPassword = "http://blog.sina.com.cn/s/blog_3f6b8ac00100gjae.html".getBytes();stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, true);stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, true);stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, true);stamper.setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar);stamper.setViewerPreferences(PdfWriter.HideWindowUI);int total = reader.getNumberOfPages() + 1;PdfContentByte content;BaseFont font = BaseFont.createFont("E:\\pdfile\\NeedToDo\\Jiemi\\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);for (int i = 1; i < total; i++)// 循环对每页插入水印{content = stamper.getUnderContent(i);// 水印的起始content.beginText();// 开始content.setColorFill(BaseColor.GREEN);// 设置颜色 默认为蓝色content.setFontAndSize(font, 38);// 设置字体及字号content.setTextMatrix(textWidth, textHeight);// 设置起始位置content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);// 开始写入水印content.endText();}stamper.close();System.out.println("OK.");}

}
2、IText创建PDF
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;public class PDFJiemi {private static String USER_PASS = "Hello123";private static String OWNER_PASS = "Owner123";@SuppressWarnings("deprecation")public static void main(String[] args) {byte[] ownerPassword = "http://blog.sina.com.cn/s/blog_3f6b8ac00100gjae.html".getBytes();try {
OutputStream file = new FileOutputStream(new File("E:\\pdfile\\NeedToDo\\Jiemi\\Test2.pdf"));Document document = new Document();PdfWriter writer = PdfWriter.getInstance(document, file);
            writer.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, 16);writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);document.open();document.add(new Paragraph("Hello World, iText"));document.add(new Paragraph(new Date().toString()));document.close();file.close();} catch (Exception e) {e.printStackTrace();}System.out.println("OK.");}
}
3、IText破解加密PDF文档
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;public class DeEncrypt {public static void main(String[] args) throws Exception {String srcFile = "E:\\pdfile\\NeedToDo\\Jiemi\\addWaterTest.pdf";String dstFile = "E:\\pdfile\\NeedToDo\\Jiemi\\DeEncryption.pdf";deletePDFEncrypt(srcFile, dstFile);System.out.println("OK.");}private static void deletePDFEncrypt(String sourceFullName, String newFullName) throws Exception{if (sourceFullName == null || sourceFullName.isEmpty() || sourceFullName.length() == 0){throw new Exception("源文件路径为空或null.");}try{// 创建一个PdfReader对象PdfReader reader = new PdfReader(sourceFullName);PdfReader.unethicalreading = true;// 获得第一页的大小Rectangle pagesize = reader.getPageSize(1);float width = pagesize.getWidth();float height = pagesize.getHeight();// 创建一个文档变量OutputStream file = new FileOutputStream(new File(newFullName));Document document = new Document(pagesize, 50, 50, 50, 50);// 创建该文档PdfWriter writer = PdfWriter.getInstance(document, file);// 打开文档document.open();// 添加内容PdfContentByte cb = writer.getDirectContent();PdfImportedPage page;int currentPageNumber = 0;int pageOfCurrentReaderPDF  = 0;// Create a new page in the target for each source page.while (pageOfCurrentReaderPDF < reader.getNumberOfPages()){pageOfCurrentReaderPDF++;currentPageNumber++;page = writer.getImportedPage(reader, pageOfCurrentReaderPDF);document.setPageSize(new Rectangle(page.getWidth(), page.getHeight()));document.newPage();cb.addTemplate(page, 0, 0);}// 关闭文档document.close();}catch (Exception ex){ex.printStackTrace();}}}
4、PDFBox判断PDF文档是否加密
import java.io.File;
import java.io.IOException;import org.apache.pdfbox.pdmodel.PDDocument;
//import org.apache.pdfbox.pdmodel.encryption.PDEncryption;public class PDFIsEncrypted {public static void main(String[] args) throws IOException {PDDocument pdf = PDDocument.load(new File("E:\\pdfile\\NeedToDo\\Jiemi\\addWaterTest.pdf")); 
      System.out.println("isEncrypted : " + pdf.isEncrypted());
 }}

IText实现对PDF文档属性的基本设置相关推荐

  1. Java使用PDFBox开发包实现对PDF文档内容编辑与保存

    pdfbox开发包下载地址:http://pdfbox.apache.org/ 程序实现了PDF文档的创建,读入,与修改PDF内容并保存. 可能有个前提,PDF文档不是加密的,如果加密怎么办,我没研究 ...

  2. java中operationBox_Java使用PDFBox开发包实现对PDF文档内容编辑与保存

    pdfbox开发包下载地址:http://pdfbox.apache.org/ 程序实现了PDF文档的创建,读入,与修改PDF内容并保存. 可能有个前提,PDF文档不是加密的,如果加密怎么办,我没研究 ...

  3. java pdfbox_Java使用PDFBox开发包实现对PDF文档内容编辑与保存

    pdfbox开发包下载地址:http://pdfbox.apache.org/ 程序实现了PDF文档的创建,读入,与修改PDF内容并保存. 可能有个前提,PDF文档不是加密的,如果加密怎么办,我没研究 ...

  4. 使用IText组件在PDF文档上绘制椭圆形印章的算法分析及代码分享

    1. 引言 PDF是一种和操作系统及平台无关的.可移植的电子文件格式,其以PostScript语言图像模型为基础,无论在哪种打印机上,都可保证精确的颜色和准确的打印效果.PDF将真实地再现原稿的每一个 ...

  5. Java使用iText实现对PDF文件的操作

    iText是著名的开放项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转化为PDF文件. http://itextpdf.c ...

  6. python对word文档内容进行批量替换_python 使用win32com实现对word文档批量替换页眉页脚...

    最近由于工作需要,需要将70个word文件的页眉页脚全部进行修改,在想到这个无聊/重复/没有任何技术含量的工作时,我的内心是相当奔溃的.就在我接近奔溃的时候我突然想到完全可以用python脚本来实现这 ...

  7. 利用iStylePDF的API实现在PDF文档中动态插入一幅图片

    PDF的交互特性里面有一种叫Annotation的注释和标记对象,我们可以在一个注释对象中放入自己想要的数据.在这篇文章中所讲到的插入一幅图片,是我们在PDF应用中经常需要这样做的,比如个人签名的图片 ...

  8. java实现在pdf文档上填充内容

    需求: 在合同附件模板上填充内容,生成一个新的合同附件,并可以查看合同附件 思路: 首先在模板文档上设置文本域,根据文本域填充内容,使用itextpdf在pdf上填充内容 1.在pom.xml中加入以 ...

  9. 利用iText.jar操作pdf文档

    1.需要的jar包 2.如何解决中文不能输出的方法(异常分析) iText 5.0.1生成pdf,加入iTextAsian.jar 出现异常 Font 'STSong-Light' with 'Uni ...

最新文章

  1. SAP S4HANA里委外加工采购功能的变化
  2. sublime_REPL使用及安装教程(解决Sublime无交互问题)
  3. Leetcode 102. 二叉树的层次遍历
  4. Qt工作笔记-QGraphics框架场景中图元的移除与析构
  5. 安卓三维展示源码_谷歌也翻车了?全球数亿安卓设备难逃一“劫”,用户隐私数据库被利用长达10年!...
  6. VSCode下Pytorch无法自动补全的问题
  7. 大数据面试都问些什么?
  8. 【bzoj1976】[BeiJing2010组队]能量魔方 Cube 网络流最小割
  9. hmcl启动器java下载_HMCL启动器
  10. [Win32] 打字游戏MFC版
  11. 宏碁台式计算机u盘启动,Acer宏碁台式电脑怎么通过bios设置u盘启动
  12. C语言基础-计算一个整数各个位数之和
  13. 零基础边缘端智慧交通训练营 | Lesson 4
  14. Html定义网页背景色
  15. GWL30地下水情监测仪应用全自动水情信息实时监测
  16. [概率练习]n个小球放入m个盒子
  17. 《流浪地球》让刘慈欣赚了多少钱?技术男搞写作原来这么简单
  18. [Cougaar]Cougaar快速开始指导(Cougaar Quick Start Guide)
  19. flask实现文件简易服务器,可根据链接上传下载
  20. 微信小程序引入echarts图表(保姆式)

热门文章

  1. 生物医学数据统计分析-相关性分析
  2. 获取当前系统时间(三种方法)
  3. 常用vi编辑器命令行
  4. [内核安全4]内核态Rootkit之IDT Hook
  5. nor flash原理详细讲解
  6. SetDlgItemText
  7. Android程序员必备的六大顶级开发工具,快加入你的清单,看完没有不懂的
  8. 数据分析课设(SPSS,EVIEWS,R)【理论】
  9. vim比较目录diff
  10. 大专毕业,0基础转行C++程序员一个月后,我后悔了