IText实现对PDF文档属性的基本设置
一、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");
图像的位置
图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。IText中通过函数public void
setAlignment(int
alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。这两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字围绕图像显示。
图像的尺寸和旋转
如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;
函数public voidscalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;
而函数scalePercent(int percentX, int percentY)则图像高宽的显示比例。
如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,参数r为弧度,如果旋转角度为30度,则参数r= Math.PI/6。
四、中文处理
默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
或者
BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);、
注意:此处大小写敏感!例如宋体的英文名称是SimSun(注意不是simsun!,首字母都是大写的)
错误写法:font-family:宋体 或者 font-family:simsun
正确写法:font-family:SimSun 或者 font-family:SimHei
确保上述所有字体均通过addFont加入,字体名称错误或者字体不存在会抛出异常,很方便,但是没导入的字体不会有任何提示。
五、例子
1、IText添加水印,并且增加权限
@Test
public void addWaterMark() throws Exception{
String srcFile="D:\\work\\pdf\\win10.pdf";//要添加水印的文件
String text="系统集成公司";//要添加水印的内容
int textWidth=200;
int textHeight=440;
PdfReader reader = new PdfReader(srcFile);// 待加水印的文件
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File("D:\\work\\pdf\\addWaterMark.pdf")));// 加完水印的文件
// byte[] userPassword = "123".getBytes();
byte[] ownerPassword = "12345".getBytes();
// int permissions = PdfWriter.ALLOW_COPY|PdfWriter.ALLOW_MODIFY_CONTENTS|PdfWriter.ALLOW_PRINTING;
// stamper.setEncryption(null, ownerPassword, permissions,false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, false);
stamper. setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar);
// stamper.setViewerPreferences(PdfWriter.HideWindowUI);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
BaseFont font = BaseFont.createFont("font/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();
}
2、IText添加书签
Document document = new Document(PageSize.A4);
BaseFont bfCN =
BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 章的字体
Font chFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE);
// 节的字体
Font secFont = new Font(bfCN, 12, Font.NORMAL, new BaseColor(0, 204,
255));
// 正文的字体
Font textFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK);
PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
int chNum = 1;
Chapter chapter = new Chapter(new Paragraph("Michael介绍", chFont),
chNum++);
Section section = chapter.addSection(new Paragraph("基本信息", secFont));
section.setIndentation(10);
section.setIndentationLeft(10);
section.setBookmarkOpen(true);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section.add(new Paragraph("苦逼的码农一枚。。。", textFont));
Section section2 = chapter.addSection(new Paragraph("SNS", secFont));
section2.setIndentation(10);
section2.setIndentationLeft(10);
section2.setBookmarkOpen(false);
section2.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section2.add(new Paragraph("SNS地址分类:", textFont));
section = section2.addSection(new Paragraph(new Chunk("我的博客", secFont)
.setUnderline(0.2f, -2f).setAnchor("http://www.cnblogs.com/xiaoSY-learning")));
section.setBookmarkOpen(false);
section.setIndentation(10);
section.setIndentationLeft(10);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section.add(new Paragraph(new Chunk("我的blog地址:http://www.cnblogs.com/xiaoSY-learning/",
textFont).setUnderline(0.2f, -2f).setAnchor(
"http://www.cnblogs.com/xiaoSY-learning/")));
section.add(new Paragraph("分享自己的技术心得。", textFont));
section = section2.addSection(new Paragraph(new Chunk("我的weibo",
secFont).setUnderline(0.2f, -2f).setAnchor(
"http://weibo.com/u/2772113512")));
section.setIndentation(10);
section.setIndentationLeft(10);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section.add(new Paragraph(new Chunk("我的weibo:http://weibo.com/u/2772113512",
textFont).setUnderline(0.2f, -2f).setAnchor(
"http://weibo.com/u/2772113512")));
section.add(new Paragraph("发表下心情,分享下技术,转转乱七八糟的新闻。", textFont));
section = section2.addSection(new Paragraph(new Chunk("twitter",
secFont)));
section.setIndentation(10);
section.setIndentationLeft(10);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section.add(new Paragraph(new Chunk("twitter:@suncto", textFont)
.setUnderline(0.2f, -2f).setAnchor("twitter:twitter:twitter:")));
section.add(new Paragraph("一个常常被墙的地方", textFont));
LineSeparator line = new LineSeparator(1, 100, new BaseColor(204, 204,
204), Element.ALIGN_CENTER, -2);
Paragraph p_line = new Paragraph("分割线");
p_line.add(line);
chapter.add(p_line);
document.add(chapter);
chapter = new Chapter(new Paragraph("Miu的介绍", chFont), chNum++);
section = chapter.addSection(new Paragraph("基本信息", secFont));
section.setIndentation(10);
section.setIndentationLeft(10);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
section.add(new Paragraph("90后一枚,喜欢美食和旅游。。。", textFont));
document.add(chapter);
document.close();
3、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"; public static void main(String[] args) { 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(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); 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.");
}
}
4、附上PDFBox判断PDF文档是否加密
import java.io.File;
import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; 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());
} }
5、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();
}
} }
转载:https://www.cnblogs.com/matrix-zhu/p/6305944.html
IText实现对PDF文档属性的基本设置的更多相关文章
- XMLHelper类 源码(XML文档帮助类,静态方法,实现对XML文档的创建,及节点和属性的增、删、改、查)
以下是代码: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...
- python 使用win32com实现对word文档批量替换页眉页脚
最近由于工作需要,需要将70个word文件的页眉页脚全部进行修改,在想到这个无聊/重复/没有任何技术含量的工作时,我的内心是相当奔溃的.就在我接近奔溃的时候我突然想到完全可以用python脚本来实现这 ...
- jaxp实现对xml文档的增,删,改,查操作(附源码)浅析
jaxp,属于javase中的一部分.是对xml进行解析的一个工具类: 既然说到这里,还是讲全一点,讲讲上面说到的xml的解析技术. xml的一个标记型文档. 在html的层级结构中,它会在内存中分配 ...
- 【JAVA与DOM4J实现对XML文档的CRUD操作】
一.简介 1.网上下载DOM4J 1.6.1压缩包,解压开之后,发现几个目录和一个jar文件,jar文件是必须的文件其它目录: docs目录:帮助文档的目录,单击index.html: Quick s ...
- C# 实现对PPT文档加密、解密以及重置密码的操作
工作中我们会使用到各种各样的文档,其中,PPT起着不可或缺的作用.一份PPT文档里可能包含重要商业计划.企业运营资料或者公司管理资料等.因此,在竞争环境里,企业重要资料的保密工作就显得尤为重要,而对于 ...
- openpyxl库实现对excel文档进行编辑(追加写入)
首先,这个库只支持xlsx格式的excel文件 预期,对”excel_test.xlsx“的A1单元格写入”hello word“ 1.安装”openpyxl“库,pip install openpy ...
- 基于DevExpress实现对PDF、Word、Excel文档的预览及操作处理
http://www.cnblogs.com/wuhuacong/p/4175266.html 在一般的管理系统模块里面,越来越多的设计到一些常用文档的上传保存操作,其中如PDF.Word.Excel ...
- 【PDF】java使用Itext生成pdf文档--详解
[API接口] 一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/ ...
- iText框架(生成pdf文档)
1.创建一个itext的简单示例 a.导包(pom.xml文件) <dependencies> <dependency> <groupId>com.lowagie& ...
随机推荐
- spring boot 之 错误:SpelEvaluationException: EL1008E: Property or field 'timestamp' cannot be found on object of type 'java.util.HashMap'
这个错误我也见过很多次了,今天终于理解了其出现的原因. 错误是这样的: 2017-11-23 18:05:39.504 ERROR 4092 --- [nio-8080-exec-3] o.a.c.c ...
- try、catch、finally都有return语句时执行哪个
任何执行try 或者catch中的return语句之前,都会先执行finally语句,如果finally存在的话.如果finally中有return语句,那么程序就return了,所以finally中 ...
- Mybatis中DAO层接口没有写实现类,Mapper中的方法和DAO接口方法是怎么绑定到一起的,其内部是怎么实现的
其实也就是通过接口名与mapper的id绑定在一起(即相同),通过SQL去写实现类,返回数据.
- 数据库设计,表与表的关系,一对多。One-To-Many(2)
一对多:主键数据表中只能包含一个记录,而在其关系记录表中这条记录可以与一个或多个记录相关,也可以没有记录与之相关. 关联映射:一对多/多对一存在最普遍的映射关系,简单来讲就如球员与球队的关系:一对多: ...
- centos安装tree命令
centos安装tree命令 sudo yum -y install tree windows安装tree命令 我的另一篇
- springBoot拦截器的使用
拦截器是动态拦截Action调用的对象.它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行.同时也是提供了一种可以提取action中可 ...
- Mask RCNN 源码阅读(update)
之前看了Google官网的object_dectect 的源码,感觉Google大神写的还不错.最近想玩下Mask RCNN,就看了下源码,这里刚好当做总结和梳理.链接如下: Google官网的obj ...
- Object.assign()解释整理
链接:https://blog.csdn.net/wang252949/article/details/79106160 语法 Object.assign(target, ...sources) 参数 ...
- C++中绝对值的运算
首先,输入-42333380005结果取出来的绝对值却是616292955. 开始我以为是long型的取值范围有问题,就把long型全部改为long long型的了,结果还是一样,就觉得绝对值这个函数 ...
- Quartz基础知识了解(一)
一.QuartZ是什么? 二.获取 三.核心接口 Scheduler - 与调度程序交互的主要API. Job - 由希望由调度程序执行的组件实现的接口. JobDetail - 用于定义作业的实例. ...