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 }
