iText7添加页眉、页脚

iText7添加页眉、页脚

  • iText7添加页眉、页脚
    • 版本号及maven依赖
    • PdfHeaderFooterEvent
    • PdfTest

iText7添加页眉、页脚

因为iText5对部分pdf操作的支持没有iText7的多,所以后续将项目原本用的itext5升级到了iText7,本文就整理一下iText7添加页眉和页脚的实现。
iText7修改实现IEventHandler,重写handlerEvent方法进行处理,然后addEventHandler到PdfDocment,并指定触发事件的类型。
还是以下边的页眉页脚为例:
页眉: 左边为logo,右边报告简称;
页脚:左边为导出人名,中间为页码,右边为导出日期;
将页眉和页脚都放在在表格里边,然后页眉仅显示底部边框,页脚仅显示顶部边框,做到分割线的作用。
注意点就是总页码,总页码是动态,只有到了写完整个文档,才能知道总页码,iText7修改为使用PdfFormXObject,并且需要在关闭文档前,手动调用。

版本号及maven依赖

iText7添加页眉、页脚_第1张图片

PdfHeaderFooterEvent

@Slf4j
public class PdfHeaderFooterEvent extends IEventHandler {

    private final static String FONT_PATH = "C:\Windows\Fonts\simsun.ttc,0";

    private final static BaseFont BASE_FONT = BaseFont.createFont(FONT_PATH, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

    private final static String logoPath = "D:\Users\admin\Downloads\logo.png";

    //总页码使用的模板对象
    public PdfFormXObject totalNumTemplate = null ;

    /**
     * 事件处理
     */
    @Override
    public void handlerEvent(Event event){
        final PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        final PdfDocument pdfDoc = docEvent.getDocument();
        final Document doc = new Document(pdfDoc);
        final PdfPage page = docEvent.getPage();
        final Rectangle pageSize = page.getPageSize();
        final int pageNumber = pdfDoc.getPageNumber(page);
        final float pdfHeight = pageSize.getHeight();
        
        try{
            this.addPageHeader(doc, pdfHeight);
        }catch(Exception e){
            log.error("添加页眉出错", e);
        }

        try{
            this.addPageFooter(doc, pdfDoc, page);
        }catch(Exception e){
            log.error("添加页脚出错", e);
        }
    }

    /**
     * 页眉
     */
    private void addPageHeader(Document docment, float pdfHeight){
        //创建字体
        Font textFont = new Font(BASE_FONT, 10f);
        float width = PageSize.A4.getWidth()-60;
        //表格 一行两列
        Table table = new Table(2);
        table.setWidth(width);
        
        //logo
        Image logo = new Image(ImageDataFactory.create(logoPath));
        table.addCell(new Cell().add(logo).setHeight(40).setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));

        //名称
        Paragraph nameP = new Paragraph("test").setFont(textFont).setFontSize(10f);
        table.addCell(new Cell().add(nameP).setHorizontalAlignment(HorizontalAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.MIDDLE).setTextAlignment(TextAlignment.RIGHT).setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));

        //设置表格的位置 页眉处
        table.setFixedPosition(document.getLeftMargin()-10, pdfHeight-document.getTopMargin()-40, table.getWidth());
        document.add(table);
    }

    /**
     * 页脚
     */
    private void addPageFooter(Document docment, PdfDocument pdf, PdfPage page){
        Rectangle pageSize = page.getPageSize();
        //创建字体
        Font textFont = new Font(BASE_FONT, 10f);
        float width = PageSize.A4.getWidth()-60;
        //表格 一行两列
        Table table = new Table(3);
        table.setWidth(width);

        //导入人
        Paragraph nameP = new Paragraph("admin").setFont(textFont).setFontSize(10f);
        table.addCell(new Cell().add(nameP).setBorderBottom(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));

        //页码 居右
        if(null == totalNumTemplate){
            totalNumTemplate = new PdfFormXObject(new Rectangle(0,0,20,20));
        }
        int pageNum = pdf.getPageNumber(page);
        PdfCanvas canvasP = new PdfCanvas(page);
        Canvas canvas = new Canvas(canvasP, pageSize);
        canvas.setFontSize(10f);
        Paragraph pageP = new Paragraph(pageNum).add(" / ").setFont(textFont).setFontSize(10f);
        canvas.showTextAligned(pageP, 295, 10, TextAlignment.RIGHT);
        canvas.close();
        canvasP.addXObjectAt(totalNumTemplate, 300f, 7f);
        canvasP.release();

        //日期
        Paragraph dateP = new Paragraph("2022/09/30").setFont(textFont).setFontSize(10f);
        table.addCell(new Cell().add(dateP).setBorderBottom(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));
        table.setFixedPosition(document.getLeftMargin()-10, pdfHeight-document.getBottomMargin()-40, table.getWidth());
        document.add(table);
    }

    /**
     * 文档关闭  手动调用
     */
    public void closeDocument(PdfDocument docment){
        //修改总页码  居左
        Canvas canvas = new Canvas(totalNumTemplate, docment);
        canvas.setFontSize(10f);
        canvas.showTextAligned(Integer.toString(docment.getNumberOfPages(),0,3f,TextAlignment.LEFT));
        canvas.close();
    }
}

PdfTest

public class PdfTest{

    public static void main(String[] args){
        String pdfPath = "test.pdf";
        
        PdfWriter writer = PdfWriter.getInstance(docment, new FileOutputStream(pdfPath));
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document docment = new Documnet(pdfDoc);
        PdfHeaderFooterEvent event = new PdfHeaderFooterEvent();
        pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, event);
        document.add(new Paragraph("test  contents"));
        event.closeDocument(pdfDoc);
        document.close();
    }
}

以上就是iText7添加页脚页眉的全部伪代码逻辑。

你可能感兴趣的:(iText,pdf,java)