ITEXT 页眉页脚页码三件套

x33g5p2x  于2021-12-28 转载在 其他  
字(6.9k)|赞(0)|评价(0)|浏览(505)

问题场景

利用itext写PDF的过程中遇到生成页眉页脚页码的问题,记录下。

整体思路

  • 编写相应事件
  • 在适当位置添加事件

效果

CODE

需要导入的包:itext-pdfa-5.5.6.jar、itext-xtra-5.5.6.jar、itext-5.5.6.jar、itext-asian.jar

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.net.MalformedURLException;
  5. import com.itextpdf.text.Document;
  6. import com.itextpdf.text.DocumentException;
  7. import com.itextpdf.text.ExceptionConverter;
  8. import com.itextpdf.text.Font;
  9. import com.itextpdf.text.Image;
  10. import com.itextpdf.text.PageSize;
  11. import com.itextpdf.text.Paragraph;
  12. import com.itextpdf.text.pdf.BaseFont;
  13. import com.itextpdf.text.pdf.PdfContentByte;
  14. import com.itextpdf.text.pdf.PdfPCell;
  15. import com.itextpdf.text.pdf.PdfPTable;
  16. import com.itextpdf.text.pdf.PdfPageEventHelper;
  17. import com.itextpdf.text.pdf.PdfTemplate;
  18. import com.itextpdf.text.pdf.PdfWriter;
  19. /** * @author youxingyang * @Date 2017-5-9 下午1:15:46 */
  20. public class pdfPage {
  21. //页码事件
  22. private static class PageXofYTest extends PdfPageEventHelper{
  23. /** The PdfTemplate that contains the total number of pages. */
  24. public PdfTemplate total;
  25. public BaseFont bfChinese;
  26. /** * 重写PdfPageEventHelper中的onOpenDocument方法 */
  27. @Override
  28. public void onOpenDocument(PdfWriter writer, Document document) {
  29. // 得到文档的内容并为该内容新建一个模板
  30. total = writer.getDirectContent().createTemplate(500, 500);
  31. try {
  32. String prefixFont = "";
  33. String os = System.getProperties().getProperty("os.name");
  34. if(os.startsWith("win") || os.startsWith("Win")){
  35. prefixFont = "C:\\Windows\\Fonts" + File.separator;
  36. }else {
  37. prefixFont = "/usr/share/fonts/chinese" + File.separator;
  38. }
  39. // 设置字体对象为Windows系统默认的字体
  40. bfChinese = BaseFont.createFont(prefixFont + "simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  41. } catch (Exception e) {
  42. throw new ExceptionConverter(e);
  43. }
  44. }
  45. /** * 重写PdfPageEventHelper中的onEndPage方法 */
  46. @Override
  47. public void onEndPage(PdfWriter writer, Document document) {
  48. // 新建获得用户页面文本和图片内容位置的对象
  49. PdfContentByte pdfContentByte = writer.getDirectContent();
  50. // 保存图形状态
  51. pdfContentByte.saveState();
  52. String text = writer.getPageNumber() + "/";
  53. // 获取点字符串的宽度
  54. float textSize = bfChinese.getWidthPoint(text, 9);
  55. pdfContentByte.beginText();
  56. // 设置随后的文本内容写作的字体和字号
  57. pdfContentByte.setFontAndSize(bfChinese, 9);
  58. // 定位'X/'
  59. float x = (document.right() + document.left()) / 2;
  60. float y = 56f;
  61. pdfContentByte.setTextMatrix(x, y);
  62. pdfContentByte.showText(text);
  63. pdfContentByte.endText();
  64. // 将模板加入到内容(content)中- // 定位'Y'
  65. pdfContentByte.addTemplate(total, x + textSize, y);
  66. pdfContentByte.restoreState();
  67. }
  68. /** * 重写PdfPageEventHelper中的onCloseDocument方法 */
  69. @Override
  70. public void onCloseDocument(PdfWriter writer, Document document) {
  71. total.beginText();
  72. try {
  73. String prefixFont = "";
  74. String os = System.getProperties().getProperty("os.name");
  75. if(os.startsWith("win") || os.startsWith("Win")){
  76. prefixFont = "C:\\Windows\\Fonts" + File.separator;
  77. }else {
  78. prefixFont = "/usr/share/fonts/chinese" + File.separator;
  79. }
  80. bfChinese = BaseFont.createFont(prefixFont + "simsun.ttc,0",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  81. total.setFontAndSize(bfChinese, 9);
  82. } catch (DocumentException e) {
  83. e.printStackTrace();
  84. } catch (IOException e) {
  85. e.printStackTrace();
  86. }
  87. total.setTextMatrix(0, 0);
  88. // 设置总页数的值到模板上,并应用到每个界面
  89. total.showText(String.valueOf(writer.getPageNumber() - 1));
  90. total.endText();
  91. }
  92. }
  93. //页眉事件
  94. private static class Header extends PdfPageEventHelper {
  95. public static PdfPTable header;
  96. public Header(PdfPTable header) {
  97. Header.header = header;
  98. }
  99. @Override
  100. public void onEndPage(PdfWriter writer, Document document) {
  101. //把页眉表格定位
  102. header.writeSelectedRows(0, -1, 36, 806, writer.getDirectContent());
  103. }
  104. /** * 设置页眉 * @param writer * @param req * @throws MalformedURLException * @throws IOException * @throws DocumentException */
  105. public void setTableHeader(PdfWriter writer) throws MalformedURLException, IOException, DocumentException {
  106. String imageAddress = "E://TESTPDF/";
  107. PdfPTable table = new PdfPTable(1);
  108. table.setTotalWidth(555);
  109. PdfPCell cell = new PdfPCell();
  110. cell.setBorder(0);
  111. Image image01;
  112. image01 = Image.getInstance(imageAddress + "testhead.png"); //图片自己传
  113. //image01.scaleAbsolute(355f, 10f);
  114. image01.setWidthPercentage(80);
  115. cell.setPaddingLeft(30f);
  116. cell.setPaddingTop(-20f);
  117. cell.addElement(image01);
  118. table.addCell(cell);
  119. Header event = new Header(table);
  120. writer.setPageEvent(event);
  121. }
  122. }
  123. //页脚事件
  124. private static class Footer extends PdfPageEventHelper {
  125. public static PdfPTable footer;
  126. @SuppressWarnings("static-access")
  127. public Footer(PdfPTable footer) {
  128. this.footer = footer;
  129. }
  130. @Override
  131. public void onEndPage(PdfWriter writer, Document document) {
  132. //把页脚表格定位
  133. footer.writeSelectedRows(0, -1, 38, 50, writer.getDirectContent());
  134. }
  135. /** * 页脚是图片 * @param writer * @throws MalformedURLException * @throws IOException * @throws DocumentException */
  136. public void setTableFooter(PdfWriter writer) throws MalformedURLException, IOException, DocumentException {
  137. String imageAddress = "E://TESTPDF/";
  138. PdfPTable table = new PdfPTable(1);
  139. table.setTotalWidth(523);
  140. PdfPCell cell = new PdfPCell();
  141. cell.setBorder(1);
  142. Image image01;
  143. image01 = Image.getInstance(imageAddress + "testfooter.png"); //图片自己传
  144. image01.scaleAbsoluteWidth(523);
  145. image01.scaleAbsoluteHeight(30f);
  146. image01.setWidthPercentage(100);
  147. cell.addElement(image01);
  148. table.addCell(cell);
  149. Footer event = new Footer(table);
  150. writer.setPageEvent(event);
  151. }
  152. /** * 页脚是文字 * @param writer * @param songti09 */
  153. public void setTableFooter(PdfWriter writer, Font songti09) {
  154. PdfPTable table = new PdfPTable(1);
  155. table.setTotalWidth(520f);
  156. PdfPCell cell = new PdfPCell();
  157. cell.setBorder(1);
  158. String string = "地址: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 网址: www.xxxxxxx.com 咨询热线: 400x-xxx-xxx";
  159. Paragraph p = new Paragraph(string, songti09);
  160. cell.setPaddingLeft(10f);
  161. cell.setPaddingTop(-2f);
  162. cell.addElement(p);
  163. table.addCell(cell);
  164. Footer event = new Footer(table);
  165. writer.setPageEvent(event);
  166. }
  167. }
  168. public static void main(String[] args) throws Exception {
  169. Document document = new Document(PageSize.A4, 48, 48, 60, 65);
  170. // add index page.
  171. String path = "test.pdf";
  172. String dir = "E://TEST";
  173. File file = new File(dir);
  174. if (!file.exists()) {
  175. file.mkdir();
  176. }
  177. path = dir + File.separator + path;
  178. FileOutputStream os = new FileOutputStream(path);
  179. PdfWriter writer = PdfWriter.getInstance(document, os);
  180. // 设置页面布局
  181. writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
  182. // 为这篇文档设置页面事件(X/Y)
  183. writer.setPageEvent(new PageXofYTest());
  184. String prefixFont = "";
  185. String oss = System.getProperties().getProperty("os.name");
  186. if(oss.startsWith("win") || oss.startsWith("Win")){
  187. prefixFont = "C:\\Windows\\Fonts" + File.separator;
  188. }else {
  189. prefixFont = "/usr/share/fonts/chinese" + File.separator;
  190. }
  191. BaseFont baseFont1 = BaseFont.createFont(prefixFont + "simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  192. Font songti09 = new Font(baseFont1, 9f); //宋体 小五
  193. document.open();
  194. document.newPage();
  195. PdfPTable pdfPTable = new PdfPTable(1);
  196. // 为报告添加页眉,事件的发生是在生成报告之后,写入到硬盘之前
  197. Header headerTable = new Header(pdfPTable);
  198. headerTable.setTableHeader(writer);
  199. Footer footerTable = new Footer(pdfPTable);
  200. footerTable.setTableFooter(writer, songti09);
  201. document.add(pdfPTable);
  202. for (int i = 0; i < 36; i++) {
  203. document.add(new Paragraph("the first page"));
  204. }
  205. document.newPage();
  206. document.add(new Paragraph("the second page"));
  207. document.close();
  208. os.close();
  209. }
  210. }

相关文章