1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package com.ruoyi.common.utils.pdf;
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.ExceptionConverter; import com.itextpdf.text.pdf.*;
import java.io.IOException;
public class PdfPageXofYEventHelper extends PdfPageEventHelper { public PdfTemplate total;
public BaseFont baseFont;
@Override public void onOpenDocument(PdfWriter writer, Document document) { total = writer.getDirectContent().createTemplate(500, 500); try { baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { throw new ExceptionConverter(e); } }
@Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte pdfContentByte = writer.getDirectContent(); pdfContentByte.saveState(); String text = "第 " + writer.getPageNumber() + " 页, 共 "; float textSize = baseFont.getWidthPoint(text, 9); pdfContentByte.beginText(); pdfContentByte.setFontAndSize(baseFont, 9);
float x = (float) ((document.right() + document.left()) / 2.2);
float y = 20f; pdfContentByte.setTextMatrix(x, y); pdfContentByte.showText(text + " 页"); pdfContentByte.endText();
pdfContentByte.addTemplate(total, x + textSize, y);
pdfContentByte.restoreState(); }
@Override public void onCloseDocument(PdfWriter writer, Document document) { total.beginText(); try { baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); total.setFontAndSize(baseFont, 9); } catch (DocumentException | IOException e) { e.printStackTrace(); } total.setTextMatrix(0, 0); total.showText(String.valueOf(writer.getPageNumber())); total.endText(); } }
|