itext5页眉页脚工具类,实现page x of y 完美兼容各种格式大小文档A4/B5/B3,兼容各种文档格式自动计算页脚XY轴坐标
鉴于没人做的这么细致,自己就写了一个itext5页眉页脚工具类,实现第几页/共几页,方便各位刚进入itext的童鞋调用。2013年9月16日 14:51:01
背景:网上流传的都是一些简单的demo,直接扔个A4文档就说实现了,其实很坑的,换个A4横版打印,那些代码就不行了,所以自己搞了这个出来。
如果页面看着排版不好,请移步我的百度空间 :http://hi.baidu.com/ae6623/item/08abce3ce29359119dc65ecf
工具类PdfReportM1HeaderFooter.java
[java] view plaincopy
- <span style="font-family:Microsoft YaHei; font-size:12px">/**
- * Project Name:report
- * File Name:PdfReportM1HeaderFooter.java
- * Package Name:com.riambsoft.report.pdf
- * Date:2013-9-16上午08:59:00
- * Copyright (c) 2013, riambsoft All Rights Reserved.
- *
- */
- package com.riambsoft.report.pdf;
- import java.io.IOException;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Element;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.PageSize;
- import com.itextpdf.text.Phrase;
- import com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.ColumnText;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfPageEventHelper;
- import com.itextpdf.text.pdf.PdfTemplate;
- import com.itextpdf.text.pdf.PdfWriter;
- /**
- * ClassName:PdfReportM1HeaderFooter <br/> Function: TODO ADD FUNCTION. <br/> Reason: TODO ADD REASON. <br/> Date: 2013-9-13 上午08:59:00 <br/>
- *
- * @author 落雨
- * @version 394263788(QQ)
- * @since JDK 1.5
- * @see http://hi.baidu.com/ae6623
- */
- public class PdfReportM1HeaderFooter extends PdfPageEventHelper {
- /**
- * 页眉
- */
- public String header = "";
- /**
- * 文档字体大小,页脚页眉最好和文本大小一致
- */
- public int presentFontSize = 12;
- /**
- * 文档页面大小,最好前面传入,否则默认为A4纸张
- */
- public Rectangle pageSize = PageSize.A4;
- // 模板
- public PdfTemplate total;
- // 基础字体对象
- public BaseFont bf = null;
- // 利用基础字体生成的字体对象,一般用于生成中文文字
- public Font fontDetail = null;
- /**
- *
- * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
- *
- */
- public PdfReportM1HeaderFooter() {
- }
- /**
- *
- * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
- *
- * @param yeMei
- * 页眉字符串
- * @param presentFontSize
- * 数据体字体大小
- * @param pageSize
- * 页面文档大小,A4,A5,A6横转翻转等Rectangle对象
- */
- public PdfReportM1HeaderFooter(String yeMei, int presentFontSize, Rectangle pageSize) {
- this.header = yeMei;
- this.presentFontSize = presentFontSize;
- this.pageSize = pageSize;
- }
- public void setHeader(String header) {
- this.header = header;
- }
- public void setPresentFontSize(int presentFontSize) {
- this.presentFontSize = presentFontSize;
- }
- /**
- *
- * TODO 文档打开时创建模板
- *
- * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
- */
- public void onOpenDocument(PdfWriter writer, Document document) {
- total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
- }
- /**
- *
- * TODO 关闭每页的时候,写入页眉,写入‘第几页共‘这几个字。
- *
- * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
- */
- public void onEndPage(PdfWriter writer, Document document) {
- try {
- if (bf == null) {
- bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
- }
- if (fontDetail == null) {
- fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
- }
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // 1.写入页眉
- ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(header, fontDetail), document.left(), document.top() + 20, 0);
- // 2.写入前半部分的 第 X页/共
- int pageS = writer.getPageNumber();
- String foot1 = "第 " + pageS + " 页 /共";
- Phrase footer = new Phrase(foot1, fontDetail);
- // 3.计算前半部分的foot1的长度,后面好定位最后一部分的‘Y页‘这俩字的x轴坐标,字体长度也要计算进去 = len
- float len = bf.getWidthPoint(foot1, presentFontSize);
- // 4.拿到当前的PdfContentByte
- PdfContentByte cb = writer.getDirectContent();
- // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了 ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
- ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0);
- // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F + len , y 轴和之前的保持一致,底边界-20
- cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20); // 调节模版显示的位置
- }
- /**
- *
- * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
- *
- * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
- */
- public void onCloseDocument(PdfWriter writer, Document document) {
- // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
- total.beginText();
- total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
- String foot2 = " " + (writer.getPageNumber() - 1) + " 页";
- total.showText(foot2);// 模版显示的内容
- total.endText();
- total.closePath();
- }
- }</span>
如何调用?
这样调用即可,下面的代码就是 第几页/共几页的实现方式!推荐大家使用,直接扔到自己的工程,在创建pdf的时候,直接把此event set进去即可。
[java] view plaincopy
- <span style="font-family:Microsoft YaHei; font-size:12px">/**
- * Project Name:report
- * File Name:PDFBuilder.java
- * Package Name:com.riambsoft.report.itext
- * Date:2013-9-13下午03:35:53
- * Copyright (c) 2013, riambsoft All Rights Reserved.
- *
- */
- package com.riambsoft.report.itext;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.PageSize;
- import com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.ColumnText;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfWriter;
- import com.riambsoft.report.pdf.PdfReportM1HeaderFooter;
- /**
- * ClassName:PDFBuilder <br/>
- * Function: TODO ADD FUNCTION. <br/>
- * Reason: TODO ADD REASON. <br/>
- * Date: 2013-9-13 下午03:35:53 <br/>
- * @author Administrator
- * @version
- * @since JDK 1.5
- * @see
- */
- public class PDFBuilder {
- private int pageHeight;
- private int pageWidth;
- private PDFBuilder(){
- }
- public static PDFBuilder getInstance(){
- return new PDFBuilder();
- }
- public void generatePDF()throws Exception {
- Document document = new Document(new Rectangle(pageWidth, pageHeight));
- PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(""));
- this.setFooter(writer);
- writer.setFullCompression();
- writer.setPdfVersion(PdfWriter.VERSION_1_4);
- document.open();
- // Set pdf version to 1.4
- PdfContentByte cb = writer.getDirectContent();
- ColumnText ct=new ColumnText(cb);
- for(int i=0;i<10;i++){
- document.newPage();
- //如果不设置 空白页无法单独显示
- writer.setPageEmpty(false);
- }
- document.close();
- }
- private void setFooter(PdfWriter writer) throws DocumentException, IOException {
- //HeaderFooter headerFooter = new HeaderFooter(this);
- //更改事件,瞬间变身 第几页/共几页 模式。
- PdfReportM1HeaderFooter headerFooter = new PdfReportM1HeaderFooter();//就是上面那个类
- writer.setBoxSize("art",PageSize.A4);
- writer.setPageEvent(headerFooter);
- }
- public int getPageHeight() {
- return pageHeight;
- }
- public void setPageHeight(int pageHeight) {
- this.pageHeight = pageHeight;
- }
- public int getPageWidth() {
- return pageWidth;
- }
- public void setPageWidth(int pageWidth) {
- this.pageWidth = pageWidth;
- }
- public static void main(String[] args) throws Exception {
- PDFBuilder builder=new PDFBuilder();
- builder.setPageHeight(400);
- builder.setPageWidth(600);
- builder.generatePDF();
- }
- }</span>
核心算法:就是计算文档的长宽,算出中点,记得中文字体是需要占用宽度的,所以也要计算进去,其次没什么重点,研究一下中点的计算吧,初中知识。
paga x 这种好做,page x of y 按照官方 itext in action 2这本书上面说的那种办法,无法准确计算各种文档的x轴和y轴坐标。
我按照书上所写的实现方式如下,不推荐使用,因为只适合于A4纸张。
PdfReportM1HeaderFooter2.java
[java] view plaincopy
- <span style="font-family:Microsoft YaHei; font-size:12px">/**
- * Project Name:report
- * File Name:PdfReportM1HeaderFooter.java
- * Package Name:com.riambsoft.report.pdf
- * Date:2013-9-13上午08:59:00
- * Copyright (c) 2013, riambsoft All Rights Reserved.
- *
- */
- package com.riambsoft.report.pdf;
- import java.io.IOException;
- import com.itextpdf.text.Document;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Element;
- import com.itextpdf.text.ExceptionConverter;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.Image;
- import com.itextpdf.text.Phrase;
- import com.itextpdf.text.Rectangle;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.ColumnText;
- import com.itextpdf.text.pdf.PdfPCell;
- import com.itextpdf.text.pdf.PdfPTable;
- import com.itextpdf.text.pdf.PdfPageEventHelper;
- import com.itextpdf.text.pdf.PdfTemplate;
- import com.itextpdf.text.pdf.PdfWriter;
- /**
- * ClassName:PdfReportM1HeaderFooter2 <br/> Function: TODO ADD FUNCTION. <br/> Reason: TODO ADD REASON. <br/> Date: 2013-9-13 上午08:59:00 <br/>
- *
- * @author Administrator
- * @version
- * @since JDK 1.5
- * @see
- */
- public class PdfReportM1HeaderFooter2 extends PdfPageEventHelper {
- String header;
- int presentFontSize = 12;
- PdfTemplate total;
- BaseFont bf = null;
- Font fontDetail = null;
- public void setHeader(String header) {
- this.header = header;
- }
- public void onOpenDocument(PdfWriter writer, Document document) {
- total = writer.getDirectContent().createTemplate(30, 16);
- }
- public void onEndPage(PdfWriter writer, Document document) {
- Rectangle pageSize = writer.getBoxSize("art");
- try {
- if (bf == null) {
- bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
- }
- if (fontDetail == null) {
- fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
- }
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- int pageN = writer.getPageNumber();
- String text = "第 " + pageN + "页/共 ";
- // 页眉
- ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase("我是页眉,土豪我们做朋友吧",fontDetail), document.left(), document.top() + 20, 0);
- PdfPTable table = new PdfPTable(2);
- try {
- table.setWidths(new int[] { 1, 1 });
- table.setWidthPercentage(100F);// 占据百分百宽度
- table.setTotalWidth(pageSize.getRight() - pageSize.getLeft() - 100);
- PdfPCell cell1 = new PdfPCell(new Phrase(text, fontDetail));
- PdfPCell cell2 = new PdfPCell(Image.getInstance(total));
- cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
- cell1.setBorder(Rectangle.NO_BORDER);
- cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
- cell2.setBorder(Rectangle.NO_BORDER);
- table.addCell(cell1);
- table.addCell(cell2);
- table.writeSelectedRows(0, -1, document.left(), document.bottom(), writer.getDirectContent());
- } catch (DocumentException de) {
- throw new ExceptionConverter(de);
- }
- }
- public void onCloseDocument(PdfWriter writer, Document document) {
- try {
- if (bf == null) {
- bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
- }
- if (fontDetail == null) {
- fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
- }
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.format("%d页", writer.getPageNumber() - 1), fontDetail), 2, 2, 0);
- }
- }</span>
这种只能自己去计算Y轴坐标,很容易不在一行。所以不如我的第一种方便。具体就看你使用了。
时间: 2024-10-07 22:28:52