• 【java】itext5 添加页眉页脚


      1 import com.itextpdf.text.*;
      2 import com.itextpdf.text.pdf.*;
      3 import java.io.IOException;
      4 
      5 public class PdfReportM1HeaderFooter extends PdfPageEventHelper {
      6     /**
      7      * 页眉
      8      */
      9     public String header = "";
     10 
     11     /**
     12      * 文档字体大小,页脚页眉最好和文本大小一致
     13      */
     14     public int presentFontSize = 12;
     15 
     16     /**
     17      * 文档页面大小,最好前面传入,否则默认为A4纸张
     18      */
     19     public Rectangle pageSize = PageSize.A4;
     20 
     21     // 模板
     22     public PdfTemplate total;
     23 
     24     // 基础字体对象
     25     public BaseFont bf = null;
     26 
     27     // 利用基础字体生成的字体对象,一般用于生成中文文字
     28     public Font fontDetail = null;
     29 
     30     /**
     31      *
     32      * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
     33      *
     34      */
     35     public PdfReportM1HeaderFooter() {
     36 
     37     }
     38 
     39     /**
     40      *
     41      * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
     42      *
     43      * @param yeMei
     44      *            页眉字符串
     45      * @param presentFontSize
     46      *            数据体字体大小
     47      * @param pageSize
     48      *            页面文档大小,A4,A5,A6横转翻转等Rectangle对象
     49      */
     50     public PdfReportM1HeaderFooter(String yeMei, int presentFontSize, Rectangle pageSize) {
     51         this.header = yeMei;
     52         this.presentFontSize = presentFontSize;
     53         this.pageSize = pageSize;
     54     }
     55 
     56     public void setHeader(String header) {
     57         this.header = header;
     58     }
     59 
     60     public void setPresentFontSize(int presentFontSize) {
     61         this.presentFontSize = presentFontSize;
     62     }
     63 
     64     /**
     65      *
     66      * TODO 文档打开时创建模板
     67      *
     68      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     69      */
     70     public void onOpenDocument(PdfWriter writer, Document document) {
     71         total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
     72     }
     73 
     74     /**
     75      *
     76      * TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
     77      *
     78      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     79      */
     80     public void onEndPage(PdfWriter writer, Document document) {
     81 
     82         try {
     83             if (bf == null) {
     84                 bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
     85             }
     86             if (fontDetail == null) {
     87                 fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
     88             }
     89         } catch (DocumentException e) {
     90             e.printStackTrace();
     91         } catch (IOException e) {
     92             e.printStackTrace();
     93         }
     94 
     95         // 1.写入页眉
     96         ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(header, fontDetail), document.left(), document.top() + 20, 0);
     97 
     98         // 2.写入前半部分的 第 X页/共
     99         int pageS = writer.getPageNumber();
    100         String foot1 = "第 " + pageS + " 页 /共";
    101         Phrase footer = new Phrase(foot1, fontDetail);
    102 
    103         // 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
    104         float len = bf.getWidthPoint(foot1, presentFontSize);
    105 
    106         // 4.拿到当前的PdfContentByte
    107         PdfContentByte cb = writer.getDirectContent();
    108 
    109         // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了 ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
    110         ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0);
    111 
    112         // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F + len , y 轴和之前的保持一致,底边界-20
    113         cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20); // 调节模版显示的位置
    114 
    115     }
    116 
    117     /**
    118      *
    119      * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
    120      *
    121      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
    122      */
    123     public void onCloseDocument(PdfWriter writer, Document document) {
    124         // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
    125         total.beginText();
    126         total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
    127         String foot2 = " " + (writer.getPageNumber()) + " 页";
    128         total.showText(foot2);// 模版显示的内容
    129         total.endText();
    130         total.closePath();
    131     }
    132 }

    使用

     1 Document document = new Document(PageSize.A4.rotate());
     2 try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
     3             PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
     4 
     5             BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     6             Font titleFont = new Font(baseFont, 14, Font.NORMAL);
     7             Font textFont = new Font(baseFont, 10, Font.NORMAL);
     8             PdfReportM1HeaderFooter headerFooter = new PdfReportM1HeaderFooter();//就是上面那个类
     9             pdfWriter.setBoxSize("art",PageSize.A4);
    10             pdfWriter.setPageEvent(headerFooter);
    11             pdfWriter.setFullCompression();
    12             pdfWriter.setPdfVersion(PdfWriter.VERSION_1_4);
    13             document.open();
    14        Image image = Image.getInstance("D:\学习图\1.png");
    15             float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
    16             float documentHeight = documentWidth / 580 * 320;//重新设置宽高
    17             image.scaleAbsolute(documentWidth, documentHeight);//重新设置宽高
    18             PdfContentByte pdfContentByte = pdfWriter.getDirectContent();
    19             pdfContentByte.addImage(image, 50, 0, 0, 50, 50, 50);
    20 
    21             document.close();
    22             return os.toByteArray();
    作者:
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    网站结构之扁平结构与树形结构的区分
    如何提高网站的访问速度
    CSS透明度大汇总
    Microsoft.AlphaImageLoader滤镜讲解
    浏览器的渲染原理简介
    ACM思维题训练 Section A
    CF--思维练习--CodeForces
    CF--思维练习--CodeForces
    CF--思维练习--CodeForces
    CF思维联系--CodeForces
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/14777448.html
Copyright © 2020-2023  润新知