itextpdf html转pdf 添加页码和水印

itextpdf html转pdf 添加页码和水印,需要在Document打开前给PdfWriter添加一个pageEvent

调用代码

 1 import java.io.ByteArrayInputStream;
 2 import java.io.FileOutputStream;
 3 import java.io.StringWriter;
 4 import java.nio.charset.Charset;
 5 
 6 import com.itextpdf.text.Document;
 7 import com.itextpdf.text.pdf.PdfWriter;
 8 import com.itextpdf.tool.xml.XMLWorkerHelper;
 9 import com.jfinal.log.Logger;
10 import com.jfinal.render.FreeMarkerRender;
11 
12 import freemarker.template.Template;
13 
14 public class PdfKit {
15     private static final Logger log = Logger.getLogger(PdfKit.class);
16     /**
17      * 导出pdf
18      * 
19      * @param templateView-freemarker模板相对路径
20      * @param os-输出流
21      * @param model-模板所需要的数据
22      * @throws Exception
23      */
24     public static void export(String templateView,Object model,String temp) throws Exception {
25         log.info("生成的合同文件地址:"+temp);
26         FileOutputStream tempOs = new FileOutputStream(temp);  
27         Template template = FreeMarkerRender.getConfiguration().getTemplate(templateView);
28         StringWriter result = new StringWriter();
29         template.process(model, result);
30         String htmlData = result.toString();//模版变量
31         Document document = new Document();
32         PdfWriter writer = PdfWriter.getInstance(document, tempOs);
33         
34         //添加水印和页码
35         PDFBuilder builder = new PDFBuilder();
36         writer.setPageEvent(builder);
37         
38         document.open();
39         XMLWorkerHelper.getInstance().parseXHtml(writer, document,
40             new ByteArrayInputStream(htmlData.getBytes()), Charset.forName("UTF-8"));
41         document.close();
42     }
43 
44 }

PDFBuilder代码

此部分代码来自于http://my.oschina.net/u/203582/blog/121838?fromerr=S6TtPCeH

  1 package com.sign.system.kit;
  2 
  3 import java.io.IOException;
  4 
  5 import com.itextpdf.text.Document;
  6 import com.itextpdf.text.DocumentException;
  7 import com.itextpdf.text.Element;
  8 import com.itextpdf.text.Font;
  9 import com.itextpdf.text.Image;
 10 import com.itextpdf.text.PageSize;
 11 import com.itextpdf.text.Phrase;
 12 import com.itextpdf.text.Rectangle;
 13 import com.itextpdf.text.pdf.BaseFont;
 14 import com.itextpdf.text.pdf.ColumnText;
 15 import com.itextpdf.text.pdf.PdfContentByte;
 16 import com.itextpdf.text.pdf.PdfPageEventHelper;
 17 import com.itextpdf.text.pdf.PdfTemplate;
 18 import com.itextpdf.text.pdf.PdfWriter;
 19 import com.sign.system.PathCons;
 20 import com.sign.util.PathUtil;
 21 
 22 /**
 23  * 设置页面附加属性
 24  *
 25  */
 26 public class PDFBuilder extends PdfPageEventHelper {
 27 
 28     /**
 29      * 页眉
 30      */
 31     public String header = "";
 32 
 33     /**
 34      * 文档字体大小,页脚页眉最好和文本大小一致
 35      */
 36     public int presentFontSize = 12;
 37 
 38     /**
 39      * 文档页面大小,最好前面传入,否则默认为A4纸张
 40      */
 41     public Rectangle pageSize = PageSize.A4;
 42 
 43     // 模板
 44     public PdfTemplate total;
 45 
 46     // 基础字体对象
 47     public BaseFont bf = null;
 48 
 49     // 利用基础字体生成的字体对象,一般用于生成中文文字
 50     public Font fontDetail = null;
 51 
 52     /**
 53      * 
 54      * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
 55      * 
 56      */
 57     public PDFBuilder() {
 58 
 59     }
 60 
 61     /**
 62      * 
 63      * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
 64      * 
 65      * @param yeMei
 66      *            页眉字符串
 67      * @param presentFontSize
 68      *            数据体字体大小
 69      * @param pageSize
 70      *            页面文档大小,A4,A5,A6横转翻转等Rectangle对象
 71      */
 72     public PDFBuilder(String yeMei, int presentFontSize, Rectangle pageSize) {
 73         this.header = yeMei;
 74         this.presentFontSize = presentFontSize;
 75         this.pageSize = pageSize;
 76     }
 77 
 78     public void setHeader(String header) {
 79         this.header = header;
 80     }
 81 
 82     public void setPresentFontSize(int presentFontSize) {
 83         this.presentFontSize = presentFontSize;
 84     }
 85 
 86     /**
 87      * 
 88      * TODO 文档打开时创建模板
 89      * 
 90      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
 91      *      com.itextpdf.text.Document)
 92      */
 93     public void onOpenDocument(PdfWriter writer, Document document) {
 94         total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
 95     }
 96 
 97     /**
 98      * 
 99      * TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
100      * 
101      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
102      *      com.itextpdf.text.Document)
103      */
104     public void onEndPage(PdfWriter writer, Document document) {
105         this.addPage(writer, document);
106         this.addWatermark(writer);
107     }
108     
109     //加分页
110     public void addPage(PdfWriter writer, Document document){
111         try {
112             if (bf == null) {
113                 bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
114             }
115             if (fontDetail == null) {
116                 fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
117             }
118         } catch (DocumentException e) {
119             e.printStackTrace();
120         } catch (IOException e) {
121             e.printStackTrace();
122         }
123 
124         // 1.写入页眉
125         ColumnText.showTextAligned(writer.getDirectContent(),
126                 Element.ALIGN_LEFT, new Phrase(header, fontDetail),
127                 document.left(), document.top() + 20, 0);
128         // 2.写入前半部分的 第 X页/共
129         int pageS = writer.getPageNumber();
130         String foot1 = "第 " + pageS + " 页 /共";
131         Phrase footer = new Phrase(foot1, fontDetail);
132 
133         // 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
134         float len = bf.getWidthPoint(foot1, presentFontSize);
135 
136         // 4.拿到当前的PdfContentByte
137         PdfContentByte cb = writer.getDirectContent();
138 
139         // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
140         // 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
141         // ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
142         ColumnText
143                 .showTextAligned(
144                         cb,
145                         Element.ALIGN_CENTER,
146                         footer,
147                         (document.rightMargin() + document.right()
148                                 + document.leftMargin() - document.left() - len) / 2.0F + 20F,
149                         document.bottom() - 20, 0);
150 
151         // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
152         // len , y 轴和之前的保持一致,底边界-20
153         cb.addTemplate(total, (document.rightMargin() + document.right()
154                 + document.leftMargin() - document.left()) / 2.0F + 20F,
155                 document.bottom() - 20); // 调节模版显示的位置
156 
157     }
158     
159     //加水印
160     public void addWatermark(PdfWriter writer){
161         // 水印图片
162         Image image;
163         try {
164             image = Image.getInstance(PathUtil.getRootClassPath(PathCons.FILE_PDF_IMG));
165             PdfContentByte content = writer.getDirectContentUnder();
166             content.beginText();
167             // 开始写入水印
168             for(int k=0;k<5;k++){
169                 for (int j = 0; j <4; j++) {
170                     image.setAbsolutePosition(150*j,170*k);
171                     content.addImage(image);
172                 }
173             }
174             content.endText();
175         } catch (IOException | DocumentException e) {
176             // TODO Auto-generated catch block
177             e.printStackTrace();
178         }
179     }
180 
181     /**
182      * 
183      * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
184      * 
185      * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
186      *      com.itextpdf.text.Document)
187      */
188     public void onCloseDocument(PdfWriter writer, Document document) {
189         // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
190         total.beginText();
191         total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
192         String foot2 = " " + (writer.getPageNumber()-1) + " 页";
193         total.showText(foot2);// 模版显示的内容
194         total.endText();
195         total.closePath();
196     }
197 }
原文地址:https://www.cnblogs.com/joann/p/5511905.html