一、Itext简介
1、API地址:javadoc/index.html
如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/index.html
2、功能:a Free Java-PDF
3、中文支持:iTextAsian.jar,现在高版本Itext不支持语言包。
4、使用的版本:iTextpdf-5.0.0.jar, iTextAsian-2.0.jar
二、Itext API
(一)PDF文档生成的5步
-
-
-
- public void createPdf() throws Exception {
-
- Document document = new Document(PageSize.A4, 500, 150, 50, 50);
-
-
- PdfWriter.getInstance(document, out);
-
-
- document.open();
-
-
- document.add(new Paragraph("Hello! PDF!!!"));
-
-
- document.close();
- }
- </span>
(二)文档对象:Document、Rectangle、PageSize
1、 Document — PDF对象
1)构造方法:
①、Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop,
float marginBottom):分别指pdf页面大小和内容距离文档边的距离。
②、默认 Document()为:A4,36,36,36,36
①、基本属性:版本(PdfVersionImp)、标题(Title)、作者(Author)、主题(Subject)、关键字(Keywords)、创建者(Creator)等等
②、其他属性:页面空白(Margins和marginLeft各个方位)
①、 add()-添加内容,newPage()-下一页, addDocListener-监听器
② 、getPageNumber()-第几页 ,getPageSize-页面大小 ,
top|left|right|bottom-页面预定义位置,置页眉页脚或者页码时有用,内部调用Rectangle的属性
setJavaScript_onLoad(添加js)等等
-
- document = new Document(PageSize.A4.rotate());
- document = new Document(tRectangle.rotate());
-
- try {
-
- PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream("pdf/pdfText.pdf"));
-
-
- document.addAuthor("作者");
- document.addTitle("标题");
- document.addSubject("主题");
- document.addKeywords("关键字");
-
-
- document.setMargins(10, 20, 30, 40);
-
- document.open();
-
-
- document.add(new Paragraph("Hello world"));
-
-
-
- document.newPage();
-
- writer.setPageEmpty(true);
-
- document.newPage();
- document.add(new Paragraph("New page"));
-
- logger.debug("PDF创建结束....");
2、 Rectangle— 页面对象
1)构造方法:
Rectangle(final float llx, final float lly, final float urx, final float ury)
Rectangle(PageSize.A4) -PageSize 封装常用的 Rectangle
①、NO_BORDER-无边框(单元格),left|top|right|bottom
②、setBackgroundColor()-背景色,
setBorder()-边框,
setBorderColor()-边框颜色
-
- Document document = null;
- document = new Document();
- document = new Document(PageSize.A4);
- document = new Document(PageSize.A4, 50, 50, 50, 50);
-
-
-
- Rectangle tRectangle = null;
- tRectangle = PageSize.A4;
- tRectangle = new Rectangle(800, 600);
- tRectangle = new Rectangle(0, 0, 800, 600);
-
-
- tRectangle.setBackgroundColor(BaseColor.BLACK);
- tRectangle.setBorder(1220);
- tRectangle.setBorderColor(BaseColor.BLUE);
- tRectangle.setBorderWidth(244.2f);
-
- document = new Document(tRectangle);</span>
3、综合案例代码:
- <span style="font-family:SimSun;">
-
-
-
-
- public void myPDF() throws DocumentException {
-
-
- Rectangle tRectangle = new Rectangle(PageSize.A4);
-
-
- tRectangle.setBackgroundColor(BaseColor.ORANGE);
- tRectangle.setBorder(1220);
- tRectangle.setBorderColor(BaseColor.BLUE);
- tRectangle.setBorderWidth(244.2f);
-
- Document doc = new Document(tRectangle);
- doc = new Document(tRectangle.rotate());
-
- PdfWriter writer = PdfWriter.getInstance(doc, out);
-
-
- 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"));
-
-
- doc.newPage();
- writer.setPageEmpty(true);
-
- doc.newPage();
- doc.add(new Paragraph("New page"));
-
- doc.close();
- }
- </span>
(三)内容对象:
1、中文支持:
1)BaseFont-确认支持中文
2)Font-字体的设置,如颜色,字体,大小等
3)固定用法如下:
- <span style="font-family:SimSun;">
-
-
-
-
- public Font getChineseFont() {
- BaseFont bfChinese;
- Font fontChinese = null;
- try {
- bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
-
- fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLUE);
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return fontChinese;
-
- }
- }
- </span>
2、Element接口
1)内容对象基本都实现这个接口。如Chunk、 Phrase、 Paragraph
2)一些有用的方位参数:
ALIGN_LEFT, ALIGN_CENTER、 ALIGN_RIGHT, ALIGN_JUSTIFIED 。
如设置居中对齐:setAlignment(Element.ALIGN_CENTER)
3、 Chunk
1)块对象: a String, a Font, and some attributes
2)方法:Chunk.NEWLINE-换行,
setUnderline(0.2f, -2f)- 下划线
setTextRise(6)-上浮
- <span style="font-family:SimSun;">
- document.add(new Chunk("中文输出: ", getChineseFont()));
-
- Chunk tChunk2 = new Chunk("输出的内容", getChineseFont());
- tChunk2.setBackground(BaseColor.CYAN, 1f, 0.5f, 1f, 1.5f);
- tChunk2.setTextRise(6);
- tChunk2.setUnderline(0.2f, -2f);
- document.add(tChunk2);
-
- document.add(Chunk.NEWLINE);
-
4、 Phrase
1)Phrase短语对象: a List of Chunks with leading
2)方法:add(Element)-添加方法,add(Chunk.NEWLINE)-内部换行
- <span style="font-family:SimSun;">
- document.add(new Phrase("Phrase page :"));
-
- Phrase tPhrase = new Phrase();
- Chunk name = new Chunk("China");
- name.setUnderline(0.2f, -2f);
- tPhrase.add(name);
- tPhrase.add(Chunk.NEWLINE);
- tPhrase.add(new Chunk("换行了 :", getChineseFont()));
- tPhrase.add(new Chunk("chinese"));
- tPhrase.setLeading(14f);
- document.add(tPhrase);
-
-
-
- document.add(Chunk.NEWLINE);
-
- Phrase director2 = new Phrase();
- Chunk name2 = new Chunk("换行了---Japan", getChineseFont());
- name2.setUnderline(0.2f, -2f);
- director2.add(name2);
- director2.add(new Chunk(","));
- director2.add(new Chunk(" "));
- director2.add(new Chunk("japanese上浮下", getChineseFont()).setTextRise(3f));
- director2.setLeading(24);
- document.add(director2);</span>
5、 Paragraph—(新段落另起一行)
1)段落对象: a Phrase with extra properties and a newline
2)方法:
add(Element)-添加; setLeading(20f)-行间距,一个Paragraph只有一个行间距;
setIndentationLeft()-左缩进, setIndentationRight-右缩进, setFirstLineIndent-首行缩进;
setSpacingBefore-设置上空白, setSpacingAfter(10f)-设置段落下空;
setAlignment(Element.ALIGN_CENTER)-居中对齐;
- <span style="font-family:SimSun;">
- 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"));
- info.setSpacingAfter(10f);
- document.add(info);
-
-
- Paragraph tParagraph = new Paragraph("段落是文章中最基本的单位。内容上它具有一个相对完整的意思;在文章中,段具有换行的标。段是由句子或句群组成的,在文章中用于体现作者的思路发展或全篇文章的层次。有的段落只有一个句子,称为独句段,独句段一般是文章的开头段、结尾段、"
- + "过渡段强调段等特殊的段落。多数段落包括不止一个句子或句群,叫多句段。中文段落开头前一般空两个格。", getChineseFont());
- tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);
-
- tParagraph.setIndentationLeft(12);
- tParagraph.setIndentationRight(12);
- tParagraph.setFirstLineIndent(24);
-
- tParagraph.setLeading(20f);
- tParagraph.setSpacingBefore(5f);
- tParagraph.setSpacingAfter(10f);
- document.add(tParagraph);
-
-
- tParagraph = new Paragraph("新的段落", getChineseFont());
- tParagraph.setAlignment(Element.ALIGN_CENTER);
- document.add(tParagraph);
- </span>
综合代码如下:
- <span style="font-family:SimSun;">
-
-
-
-
-
- public void addContent() throws Exception {
- Document document = new Document(PageSize.A4);
- PdfWriter.getInstance(document, out);
- document.open();
-
-
- document.add(new Chunk("中文输出: ", getChineseFont()));
-
- Chunk tChunk2 = new Chunk("输出的内容", getChineseFont());
- tChunk2.setBackground(BaseColor.CYAN, 1f, 0.5f, 1f, 1.5f);
- tChunk2.setTextRise(6);
- tChunk2.setUnderline(0.2f, -2f);
- document.add(tChunk2);
-
- document.add(Chunk.NEWLINE);
-
-
-
- document.add(new Phrase("Phrase page :"));
-
- Phrase tPhrase = new Phrase();
- Chunk name = new Chunk("China");
- name.setUnderline(0.2f, -2f);
- tPhrase.add(name);
- tPhrase.add(Chunk.NEWLINE);
- tPhrase.add(new Chunk("换行了 :", getChineseFont()));
- tPhrase.add(new Chunk("chinese"));
- tPhrase.setLeading(14f);
- document.add(tPhrase);
-
-
-
- document.add(Chunk.NEWLINE);
-
- Phrase director2 = new Phrase();
- Chunk name2 = new Chunk("换行了---Japan", getChineseFont());
- name2.setUnderline(0.2f, -2f);
- director2.add(name2);
- director2.add(new Chunk(","));
- director2.add(new Chunk(" "));
- director2.add(new Chunk("japanese上浮下", getChineseFont()).setTextRise(3f));
- director2.setLeading(24);
- document.add(director2);
-
-
- 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"));
- info.setSpacingAfter(10f);
- document.add(info);
-
-
- Paragraph tParagraph = new Paragraph("段落是文章中最基本的单位。内容上它具有一个相对完整的意思;在文章中,段具有换行的标。段是由句子或句群组成的,在文章中用于体现作者的思路发展或全篇文章的层次。有的段落只有一个句子,称为独句段,独句段一般是文章的开头段、结尾段、"
- + "过渡段强调段等特殊的段落。多数段落包括不止一个句子或句群,叫多句段。中文段落开头前一般空两个格。", getChineseFont());
- tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);
-
- tParagraph.setIndentationLeft(12);
- tParagraph.setIndentationRight(12);
- tParagraph.setFirstLineIndent(24);
-
- tParagraph.setLeading(20f);
- tParagraph.setSpacingBefore(5f);
- tParagraph.setSpacingAfter(10f);
- document.add(tParagraph);
-
-
- tParagraph = new Paragraph("新的段落", getChineseFont());
- tParagraph.setAlignment(Element.ALIGN_CENTER);
- document.add(tParagraph);
-
- document.close();
- }
- </span>
6、Image继承自Rectangle
1)、初始化:Image img = Image.getInstance("source/imag/bage.png")
2)、方法:
setAlignment(Image.LEFT)-对齐方式,setBorder(Image.BOX)-边框,
setBorderWidth(10)-边框宽度,setBorderColor(BaseColor.WHITE)-边框颜色,
scaleToFit(1000, 72)-大小,setRotationDegrees(-30)-旋转,
setAbsolutePosition()-绝对位置
- <span style="font-family:SimSun;">
- Image img = Image.getInstance("source/imag/bage.png");
- img.setAlignment(Image.LEFT);
- img.setBorder(Image.BOX);
- img.setBorderWidth(10);
- img.setBorderColor(BaseColor.WHITE);
- img.scaleToFit(1000, 72);
- img.setRotationDegrees(-30);
- document.add(img);</span>
7、Anchor(锚点、超链接) 、Chapter、Section(目录章节)等:
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void insertObject() throws Exception {
-
- Document document = new Document(PageSize.A4);
- PdfWriter.getInstance(document, out);
- document.open();
-
-
- Paragraph country = new Paragraph();
- Anchor dest = new Anchor("我是锚点,也是超链接", getChineseFont());
- dest.setName("CN");
- dest.setReference("http://www.china.com");// 连接
- country.add(dest);
- country.add(String.format(": %d sites", 10000));
- document.add(country);
-
- Anchor toUS = new Anchor("连接到设置的CN锚点。", getChineseFont());
- toUS.setReference("#CN");
- document.add(toUS);
-
-
- Image img = Image.getInstance("source/imag/bage.png");
- img.setAlignment(Image.LEFT);
- img.setBorder(Image.BOX);
- img.setBorderWidth(10);
- img.setBorderColor(BaseColor.WHITE);
- img.scaleToFit(1000, 72);
- img.setRotationDegrees(-30);
- document.add(img);
-
-
- Paragraph title = new Paragraph("一级标题", getChineseFont());
- Chapter chapter = new Chapter(title, 1);
-
- Paragraph title2 = new Paragraph("二级标题1", getChineseFont());
- Section section = chapter.addSection(title2);
- section.setBookmarkTitle("bmk");
- section.setIndentation(30);
- section.setIndentationLeft(5);
- section.setBookmarkOpen(false);
- section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
-
- Section section2 = chapter.addSection(new Paragraph("二级标题2", getChineseFont()));
- section2.setIndentation(30);
- section2.setIndentationLeft(5);
- section2.setBookmarkOpen(false);
- section2.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
-
- Section subsection = section.addSection(new Paragraph("三级标题1", getChineseFont()));
- subsection.setIndentationLeft(10);
-
- subsection.setNumberStyle(Section.NUMBERSTYLE_DOTTED);
-
- Section subsection2 = section2.addSection(new Paragraph("三级标题2", getChineseFont()));
- subsection2.setIndentationLeft(10);
- subsection2.setNumberStyle(Section.NUMBERSTYLE_DOTTED);
- document.add(chapter);
-
- document.close();
-
- }
- </span>
(四)、表格对象:Table、PdfPTable
1、构造方法:
PdfPTable datatable = new PdfPTable(6);//列数
PdfPTable datatable = new PdfPTable(new float[]{1,2,3})-每个单元格宽度
PdfPTable[PdfPTable[PdfPCell[Paragraph]]]
3、方法:
1) setWidths(数组)-单元格宽度, setTotalWidth(300f)-表格的总宽度,
setWidthPercentage(100)-表格的宽度百分比,setLockedWidth(true)-宽度锁定
2) getDefaultCell()-得到默认单元格,addCell()-添加单元格
setPadding(2)-单元格的间隔 ,setBackgroundColor(BaseColor.GREEN)-背景色
3) setSpacingAfter(40f)-设置表格下面空白行, setSpacingBefore(20f)-设置表格上面空白行
new Paragraph(“\n\n”)-可以实现换行,留白
4)setBorderWidth(2)-边框宽度
5)setHorizontalAlignment(Element.ALIGN_CENTER)-对齐方式
6)写入绝对位置:
PdfContentByte tContent = writer.getDirectContent()-得到层
table.writeSelectedRows(0,-1, 0, -1, 100, 200, tContent)-写入绝对位置
- <span style="font-family:SimSun;">
-
-
-
-
-
- public void insertTable() throws Exception {
-
- Document document = new Document(PageSize.A4, 50, 50, 50, 50);
-
- PdfWriter.getInstance(document, out);
- document.open();
-
-
- BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
- Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
-
- int colNumber = 6;
-
-
-
- PdfPTable datatable = new PdfPTable(colNumber);
-
- int[] cellsWidth = { 1, 1, 1, 1, 1, 1 };
- datatable.setWidths(cellsWidth);
-
- datatable.setWidthPercentage(100);
-
- datatable.getDefaultCell().setPadding(2);
- datatable.getDefaultCell().setBorderWidth(2);
-
- datatable.getDefaultCell().setBackgroundColor(BaseColor.GREEN);
- datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
-
-
-
- for (int i = 0; i < colNumber; i++) {
- datatable.addCell(new Paragraph(tableHeader[i], fontChinese));
- }
-
- for (int i = 0; i < colNumber; i++) {
- datatable.addCell(new Paragraph(tableCont[i], fontChinese));
- }
-
-
- for (int i = 0; i < colNumber; i++) {
- PdfPCell cell = new PdfPCell(new Paragraph(""));
- cell.setFixedHeight(10);
- datatable.addCell(cell);
- }
- datatable.setSpacingAfter(40f);
- document.add(datatable);
-
-
- PdfPTable table = new PdfPTable(3);
- PdfPCell cell;
- cell = new PdfPCell(new Phrase("跨3列", getChineseFont()));
- cell.setColspan(3);
- table.addCell(cell);
-
- cell = new PdfPCell(new Phrase("跨2行", getChineseFont()));
- cell.setRowspan(2);
- table.addCell(cell);
- table.addCell("row 1; cell 1");
- table.addCell("row 1; cell 2");
- table.addCell("row 2; cell 1");
- table.addCell("row 2; cell 2");
-
- document.add(table);
-
-
- PdfPTable tableFather = new PdfPTable(4);
- tableFather.setSpacingBefore(20f);
-
- PdfPTable nested1 = new PdfPTable(2);
- nested1.addCell("1.1");
- nested1.addCell("1.2");
-
- PdfPTable nested2 = new PdfPTable(1);
- nested2.addCell("2.1");
- nested2.addCell("2.2");
-
-
- for (int k = 0; k < 12; ++k) {
- if (k == 1) {
- tableFather.addCell(nested1);
- } else if (k == 6) {
- tableFather.addCell(nested2);
- } else {
- tableFather.addCell("cell " + k);
- }
- }
- document.add(tableFather);
-
- document.close();
- }
- </span>
(五)、单元格对象: PdfPCell
1、构造函数
PdfPCell cell= new PdfPCell(new Paragraph(“表格”, 中文支持)
2、方法
1)setBackgroundColor(BaseColor.CYAN)-背景色
2)setMinimumHeight(30f)-最小高度
setFixedHeight(40f)-固定高度。表格的高度通过单元格高度完成
3)setBorder(Rectangle.NO_BORDER)-无边框,setBorderWidth(0)-无边框。不设,默认是有边框的
setBorderColor(new BaseColor(255, 0, 0))-边框颜色
4)setHorizontalAlignment(Element.ALIGN_CENTER)-水平居中
setVerticalAlignment(Element.ALIGN_MIDDLE)-垂直居中。设置单元格内容的显示
5)setRowspan(2)-跨2行,setColspan(2)-跨2列
- <span style="font-family:SimSun;">
-
-
-
-
-
- public void myTable() throws Exception {
-
- Document document = new Document(PageSize.A4, 50, 50, 50, 50);
- PdfWriter writer = PdfWriter.getInstance(document, out);
- document.open();
-
- PdfPTable table = new PdfPTable(6);
-
- for (int i = 0; i < 6; i++) {
- table.addCell(new Paragraph(tableHeader[i], getChineseFont()));
- }
-
- for (int i = 0; i < 6; i++) {
- table.addCell(new Paragraph(tableCont[i], getChineseFont()));
- }
- table.setSpacingBefore(10f);
-
-
- table.setHorizontalAlignment(Element.ALIGN_LEFT);
- table.setTotalWidth(369.7f);
- table.setWidths(new float[] { 0.1565f, 0.15f, 0.15f, 0.145f, 0.15f, 0.145f });
- table.setWidthPercentage(100);
-
- document.add(table);
- document.add(new Paragraph("\n\n"));
-
-
- table.setHorizontalAlignment(Element.ALIGN_CENTER);
- document.add(table);
- document.add(new Paragraph("\n\n"));
-
-
- table.setWidthPercentage(50);
- table.setHorizontalAlignment(Element.ALIGN_RIGHT);
- document.add(table);
- document.add(new Paragraph("\n\n"));
-
-
- table.setTotalWidth(300);
- table.setLockedWidth(true);
- document.add(table);
-
-
- PdfPCell cell = new PdfPCell(new Paragraph("合并3个单元格", getChineseFont()));
- cell.setColspan(3);
- cell.setBackgroundColor(BaseColor.CYAN);
- cell.setMinimumHeight(30f);
- cell.setFixedHeight(40f);
- table.addCell(cell);
-
-
- Paragraph tParagraph = new Paragraph("居中", getChineseFont());
- tParagraph.setAlignment(Element.ALIGN_CENTER);
- cell = new PdfPCell(tParagraph);
- cell.setBorderColor(new BaseColor(255, 0, 0));
- cell.setFixedHeight(45f);
- cell.setHorizontalAlignment(Element.ALIGN_CENTER);
- cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell);
-
-
- cell = new PdfPCell(new Paragraph("无边框", getChineseFont()));
- cell.setBorder(Rectangle.NO_BORDER);
- cell.setBorderWidth(0);
- table.addCell(cell);
-
-
- cell = new PdfPCell(new Paragraph("单元格边框颜色", getChineseFont()));
- cell.setBorderColor(BaseColor.YELLOW);
- table.addCell(cell);
-
- document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'", getChineseFont()));
- table.setSpacingBefore(15f);
- document.add(table);
- table.setSpacingAfter(15f);
- document.add(table);
-
-
-
-
-
- document.add(new Paragraph(
- "写入文档的绝对位置:(writeSelectedRows(rowStart, rowEnd, xPos, yPos, canvas))参数rowStart是你想开始的行的数目,参数rowEnd是你想显示的最后的行(如果你想显示所有的行,用-1),xPos和yPos是表格的坐标,canvas是一个PdfContentByte对象。",
- getChineseFont()));
- PdfContentByte tContent = writer.getDirectContent();
- table.writeSelectedRows(0, -1, 0, -1, 100, 200, tContent);
-
- document.add(new Paragraph("第1行到最后,从0开始计数", getChineseFont()));
- table.writeSelectedRows(1, -1, 100, 100, tContent);
- document.close();
-
- }
- </span>
(六)、PDF结构-4层结构
1、四层结构
2、层对象: PdfContentByte
3、一、四层可操作;二、三层Itext内部处理
4、 操作:
第 1 层操作:PdfWriter. getDirectContent(),
第 2 层操作:getDirectContentUnder()。
第 1 层操作: PdfStamper. getUnderContent(1),-可以加页数
第 2 层操作: PdfStamper .getOverContent(1)。
5、作用:添加水印、背景、添加内容到绝对位置、合并PDF
(六)、添加水印
1、方法:
PdfContentByte under = writer.getDirectContentUnder();//默认当前页
PdfContentByte under = stamp.getUnderContent(1);// 拿到层,可以有页数
2、文本水印
1)beginText():开始,endText()结束。
2)showTextAligned()写入文档,这个方法有很多重载,可以添加方位,旋转等。
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void addShuyinByWriter() throws Exception {
-
- Document document = new Document(PageSize.A4);
- PdfWriter writer = PdfWriter.getInstance(document, out);
- document.open();
-
-
-
-
-
-
- PdfContentByte under = writer.getDirectContentUnder();
-
-
- under.beginText();
- BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
- under.setFontAndSize(bf, 18);
-
- under.showTextAligned(Element.ALIGN_LEFT, "ShuiYin................", 230, 430, 45);
- under.endText();
-
- document.close();
- }
- </span>
3、图片水印与背景
1)添加水印:
2)水印与背景的区别:背景只需要把绝对置为从 文档左下角开始。 即设置setAbsolutePosition(0, 0)
3)位置的定位:理解页面对象——Rectangle
Rectangle tRectangle = new Rectangle(0, 0, 800, 600);
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void addShuiYinByTempete() throws Exception {
-
-
- PdfReader reader = new PdfReader(templetePdf);
-
- PdfStamper stamp = new PdfStamper(reader, out);
-
-
- Image img = Image.getInstance("source/imag/bage.png");
- img.setAbsolutePosition(100, 100);
- PdfContentByte under = stamp.getUnderContent(1);
- under.addImage(img);
-
-
- PdfContentByte over = stamp.getOverContent(1);
- 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, "ShuiYin", 230, 430, 45);
- over.endText();
-
-
- Image img2 = Image.getInstance("resource/test.jpg");
- img2.setAbsolutePosition(0, 0);
- PdfContentByte under2 = stamp.getUnderContent(3);
- under2.addImage(img2);
-
-
- stamp.close();
- reader.close();
- }
- </span>
(七)、添加头尾注和页码等
1、需要使用监听器,类似于Sax解析Xml:
1)PdfWriter. setPageEvent(PdfPageEvent event) - PdfPageEven接口
2)PdfPageEventHelper类实现了PdfPageEven接口。我们自定义只要实现PdfPageEventHelper即可,随意重
写需要的方法即可。
2、重写的方法:
onOpenDocument(PdfWriter writer, Document document)
onEndPage(PdfWriter writer, Document document)等等
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void insertHeadAndFoot() throws Exception {
- Document doc = new Document();
- PdfWriter writer = PdfWriter.getInstance(doc, out);
-
-
- writer.setPageEvent(new PdfPageHelper());
-
- doc.open();
- doc.add(new Paragraph("1 page"));
- doc.newPage();
- doc.add(new Paragraph("2 page"));
-
- doc.close();
- }
- </span>
- <span style="font-family:SimSun;">
-
-
-
-
-
-
-
-
-
-
- class PdfPageHelper extends PdfPageEventHelper {
-
- @Override
- public void onEndPage(PdfWriter writer, Document document) {
-
- PdfContentByte cb = writer.getDirectContent();
- cb.saveState();
-
- cb.beginText();
- cb.setFontAndSize(getBaseFont(), 10);
-
- float x = document.top(-20);
-
- cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "H-Left", document.left(), x, 0);
-
- cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "第" + writer.getPageNumber() + "页", (document.right() + document.left()) / 2, x, 0);
-
- cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "H-Right", document.right(), x, 0);
-
- float y = document.bottom(-20);
-
- cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "F-Left", document.left(), y, 0);
-
- cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "第" + writer.getPageNumber() + "页", (document.right() + document.left()) / 2, y, 0);
-
- cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);
- cb.endText();
- cb.restoreState();
-
- }
- </span>
(八)、读取PDF即模板的使用
1、使用Adobe Acrobat 制作PDF模板(可以用word先编辑,另存为PDF格式)
1)文本域:工具-内容编辑-编辑文本域图像(自动会选中)
2)表单域:工具-表单-编辑-编辑-添加新域(或者编辑域)
3)编辑表单域可以设置一个name,如 ConNo;也可以设置显示的字体、大小、对齐方式等等。
2、涉及的核心类:PdfReader,PdfStamper
3、实现:
1)读取PDF文档( PdfReader )->交给解析器( PdfStamper )
- <span style="font-family:SimSun;">
-
- String tPdfTemplateFile = "source/pdf/templete/EdorTemplete.pdf";
- String tPdfResultFile = "temp/pdf/Edor_" + new Random().nextInt() + ".pdf";
-
-
- FileOutputStream fos = new FileOutputStream(tPdfResultFile);
- PdfReader reader = new PdfReader(tPdfTemplateFile);
- PdfStamper mPdfStamper = new PdfStamper(reader, fos);
2)获取保单域( AcroFields )->获取所有的表单域数据(Map)
- <span style="font-family:SimSun;">
- AcroFields form = mPdfStamper.getAcroFields();
-
- Map<String, Item> acroFieldMap = form.getFields();
- </span>
3)处理:循环Map,拿到key(即表单域的name),给表单域赋值即可。
AcroFields .setField(fieldName, fieldValue);
4)关闭PdfReader, PdfStamper。
- <span style="font-family:SimSun;">
- int len = 4;
- for (Map.Entry<String, Item> entry : acroFieldMap.entrySet()) {
-
- String fieldName = entry.getKey();
- String fieldValue = "fill_" + len;
- System.out.println(fieldName + ":" + fieldValue);
- form.setField(fieldName, fieldValue);
- len++;
- }
-
-
- mPdfStamper.setFormFlattening(true);
- reader.close();
- mPdfStamper.close();</span>
5、完整代码如下:模板为上面截图模板:
- <span style="font-family:SimSun;">package pdf.templete;
-
- import java.io.FileOutputStream;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
-
- import com.itextpdf.text.pdf.AcroFields;
- import com.itextpdf.text.pdf.AcroFields.Item;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.PdfStamper;
-
-
-
-
-
-
-
-
-
-
-
-
- public class PdfTempleteWithIText {
-
-
-
-
-
- public static void main(String[] args) {
- PdfTempleteWithIText pdfTemplete = new PdfTempleteWithIText();
-
- try {
-
-
- pdfTemplete.fillFormDatas();
-
-
- pdfTemplete.fillTableDatas();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
-
- public void fillFormDatas() throws Exception {
-
-
- Map<String, String> mMapDatas = new HashMap<String, String>();
- mMapDatas.put("CustomerName", "SAM-SHO");
- mMapDatas.put("ContNo", "123456789098765");
- mMapDatas.put("ContCount", "1");
- mMapDatas.put("EdorType", "CT-退保");
- mMapDatas.put("GetMoney", "999.99");
- mMapDatas.put("AcceptName", "人寿保险");
- mMapDatas.put("AcceptDate", "2014-11-1");
-
-
- Random a = new Random();
- a.nextInt();
- String tPdfTemplateFile = "source/pdf/templete/EdorTemplete.pdf";
- String tPdfResultFile = "temp/pdf/Edor_" + a.nextInt() + ".pdf";
-
-
- FileOutputStream fos = new FileOutputStream(tPdfResultFile);
- PdfReader reader = new PdfReader(tPdfTemplateFile);
- PdfStamper mPdfStamper = new PdfStamper(reader, fos);
-
-
- AcroFields form = mPdfStamper.getAcroFields();
-
- Map<String, Item> acroFieldMap = form.getFields();
-
- for (Map.Entry<String, Item> entry : acroFieldMap.entrySet()) {
-
- String fieldName = entry.getKey();
- String fieldValue = mMapDatas.get(fieldName);
- if (!"".equals(fieldValue)) {
-
- form.setField(fieldName, fieldValue);
- System.out.println(fieldName + "," + fieldValue);
- }
- }
-
-
- mPdfStamper.setFormFlattening(true);
- reader.close();
- mPdfStamper.close();
- }
-
-
-
-
-
-
-
- public void fillTableDatas() throws Exception {
-
-
-
- String tPdfTemplateFile = "source/pdf/templete/EdorTemplete.pdf";
- String tPdfResultFile = "temp/pdf/Edor_" + new Random().nextInt() + ".pdf";
-
-
- FileOutputStream fos = new FileOutputStream(tPdfResultFile);
- PdfReader reader = new PdfReader(tPdfTemplateFile);
- PdfStamper mPdfStamper = new PdfStamper(reader, fos);
-
-
- AcroFields form = mPdfStamper.getAcroFields();
-
- Map<String, Item> acroFieldMap = form.getFields();
-
- int len = 4;
- for (Map.Entry<String, Item> entry : acroFieldMap.entrySet()) {
-
- String fieldName = entry.getKey();
- String fieldValue = "fill_" + len;
- System.out.println(fieldName + ":" + fieldValue);
- form.setField(fieldName, fieldValue);
- len++;
- }
-
-
- mPdfStamper.setFormFlattening(true);
- reader.close();
- mPdfStamper.close();
-
- }
-
- }</span>
(九)、合并PDF-——核心是合并旧的,生成新的PDF
1、涉及的核心类:PdfReader,PdfCopy(PdfWriter的子类)
2、实现:2次循环
1)第一层循环:PDF合并的文件个数,有几个PDF需要合并。
①、每一个pdf文件都使用PdfReader获取:PdfReader reader = new PdfReader(files[i]);
② 、reader.getNumberOfPages()获取一个PDF有多少页
2)第二层循环:一个PDF文件的页数,一个PDF有几页
PdfImportedPage page = copy.getImportedPage(reader, 第几页);
3、代码如下:
1)使用PdfCopy:
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public boolean mergePdfFiles(String[] files, String newfile) {
- boolean retValue = false;
- Document document = null;
- try {
- document = new Document();
- PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
- document.open();
-
- for (int i = 0; i < files.length; i++) {
- PdfReader reader = new PdfReader(files[i]);
- int n = reader.getNumberOfPages();
- for (int j = 1; j <= n; j++) {
- document.newPage();
- PdfImportedPage page = copy.getImportedPage(reader, j);
- copy.addPage(page);
- }
- }
- retValue = true;
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- document.close();
- }
- return retValue;
- }
- </span>
2)使用PdfWriter实现PDF合并
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void mergePdf() throws Exception {
-
- String[] files = { "source/pdf/1.pdf", "source/pdf/2.pdf" };
- String savepath = "source/pdf/mergePdf.pdf";
-
- Document document = new Document();
-
- PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(savepath));
-
-
- document.open();
- PdfContentByte cb = writer.getDirectContent();
-
- for (int i = 0; i < files.length; i++) {
- PdfReader reader = new PdfReader(files[i]);
- int n = reader.getNumberOfPages();
- for (int j = 1; j <= n; j++) {
- document.newPage();
-
-
- PdfImportedPage page = writer.getImportedPage(reader, j);
- cb.addTemplate(page, 0, 0);
- }
- }
- document.close();
-
-
-
-
- }
- </span>
(十)、删除pdf页
1、思路:读取pdf文档,然后页码,然后输出到新的PDF
2、实现:
- <span style="font-family:SimSun;">
-
-
-
-
-
-
- public void deletePage() throws Exception {
-
-
-
-
-
-
-
-
-
-
-
-
-
- PdfReader reader = new PdfReader("deletePage.pdf");
- reader.selectPages("1,3");
- PdfStamper stamp = new PdfStamper(reader, out);
- stamp.close();
- reader.close();
-
- }
- </span>