java itext pdf 添加页码

一、页码添加,重写事件,直接上代码:

public class PdfPageXofYEventHelper extends PdfPageEventHelper {
    public PdfTemplate total;

    public BaseFont baseFont;

    /**
     * 重写PdfPageEventHelper中的onOpenDocument方法
     */
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        // 得到文档的内容并为该内容新建一个模板
        total = writer.getDirectContent().createTemplate(500, 500);
        try {
            ClassPathResource cpr = new ClassPathResource("arial.ttf");
            baseFont = BaseFont.createFont(cpr.getPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }

    /**
     * 重写PdfPageEventHelper中的onEndPage方法
     */
    @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);

        // 定位'X/'
//        float x = (document.right() + document.left()) / 2;
        float x = document.right();
        float y = 20f;
        pdfContentByte.setTextMatrix(x, y);
        pdfContentByte.showText(text);
        pdfContentByte.endText();

        // 将模板加入到内容(content)中- // 定位'Y'
        pdfContentByte.addTemplate(total, x + textSize, y);

        pdfContentByte.restoreState();
    }

    /**
     * 重写PdfPageEventHelper中的onCloseDocument方法
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        total.beginText();
        try {
            ClassPathResource cpr = new ClassPathResource("arial.ttf");
            baseFont = BaseFont.createFont(cpr.getPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            total.setFontAndSize(baseFont, 9);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        total.setTextMatrix(0, 0);
        // 设置总页数的值到模板上,并应用到每个界面
        total.showText(String.valueOf(writer.getPageNumber() - 1));
        total.endText();
    }
}

重写完事件之后,在写pdf时添加上即可:

。。。
// 1.新建document对象
document = new Document(PageSize.A4);
// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
writer = PdfWriter.getInstance(document, os);

//--------------------------页码添加---------------------------
// 设置页面布局
writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
// 为这篇文档设置页面事件(X/Y)
writer.setPageEvent(new PdfPageXofYEventHelper());
//--------------------------页码添加---------------------------

// 3.打开文档
document.open();

效果图:
在这里插入图片描述

二、页脚添加

public class Footer extends PdfPageEventHelper {

    public static PdfPTable footer;

    @SuppressWarnings("static-access")
    public Footer(PdfPTable footer) {
        this.footer = footer;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        //把页脚表格定位
        footer.writeSelectedRows(0, -1, 38, 50, writer.getDirectContent());
    }

    /**
     * 页脚是文字
     * @param writer
     * @param songti09
     */
    public void setTableFooter(PdfWriter writer, Font songti09) {
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(520f);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(1);
        String string = "地址:  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX         网址:  www.xxxxxxx.com       咨询热线:  400x-xxx-xxx";
        Paragraph p = new Paragraph(string, songti09);
        cell.setPaddingLeft(10f);
        cell.setPaddingTop(-2f);
        cell.addElement(p);
        table.addCell(cell);
        Footer event = new Footer(table);
        writer.setPageEvent(event);
    }
}

写pdf时添加上即可:

// 3.打开文档
document.open();

PdfPTable pdfPTable1 = new PdfPTable(1);
// 自己重写的Footer 类
Footer footerTable = new Footer(pdfPTable1);
footerTable.setTableFooter(writer, PdfCommon.createFont(9f));
document.add(pdfPTable1);

效果图:
在这里插入图片描述

也可参考 :https://www.bbsmax.com/A/rV5702oLdP/

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中使用iText库生成PDF并在页眉中插入图片的方法如下: 首先,你可以创建一个页眉页脚类,根据实际情况使用,如果不需要页眉页脚可以忽略这一步。通过参考中的链接可以了解更多关于页眉页脚带图片的详细信息。 接下来,你需要使用iText库生成PDF。你可以通过参考中的链接找到一个示例代码,并在生成PDF的过程中插入图片。具体来说,在创建表格的过程中,你可以在表格的某一行中插入图片,例如在createHardwarePDF方法的第九行。 最后,你可以参考中的链接来了解更多关于JavaiText生成PDF并插入图片的信息和效果演示。 这样,你就可以在Java中使用iText库生成PDF并在页眉中插入图片了。希望对你有所帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [itextpdf 使用之 html 转 pdf 页眉页脚带图片](https://download.csdn.net/download/z1353095373/85382971)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [JavaItext生成Pdf,并给PdfCell添加图片](https://blog.csdn.net/qq_17847881/article/details/130180328)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Itextpdf添加页眉页脚页码,页眉中需要添加logo图片](https://blog.csdn.net/qb170217/article/details/118718685)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值