Java中Itext生成Pdf,并给PdfCell添加图片

Java中Itext生成Pdf,并给PdfCell添加图片

1. 页眉页脚类 _ 根据实际情况使用,如不需要可忽略此步

package com.mediinfo.test;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Date;

@Slf4j
public class PdfHeaderFooter extends PdfPageEventHelper {

    private final static String FONT_PATH = "c:\\windows\\fonts\\SIMSUN.TTC,1";
    private final static String logoPath = "D:\\1.jpg";

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

    /**
     * 重写页面结束时间  分别添加页眉、页脚
     */
    public void onEndPage(PdfWriter writer, Document docment){
        try{
            this.addPageHeader(writer, docment);
        }catch(Exception e){
            log.error("添加页眉出错", e);
        }

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

    /**
     * 页眉
     */
    private void addPageHeader(PdfWriter writer, Document docment) throws IOException, DocumentException {
        BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);

        //创建字体
        Font textFont = new Font(BASE_FONT, 10f);

        //两列  一列logo  一列项目简称   有Logo时添加图片,没有时添加个空值,避免报错
        PdfPTable table = new PdfPTable(2);
        //设置表格宽度 A4纸宽度减去两个边距  比如我一边30  所以减去60
        table.setTotalWidth(PageSize.A4.getWidth()-60);

        //logo
        //创建图片对象
        try {
            Image logo = Image.getInstance(logoPath);
            //创建一个Phrase对象 再添加一个Chunk对象进去  Chunk里边是图片
            Phrase logoP = new Phrase("", textFont);
            //自己调整偏移值 主要是y轴值
            logoP.add(new Chunk(logo, 0, -5));
            PdfPCell logoCell = new PdfPCell(logoP);
            //只保留底部边框和设置高度
            logoCell.disableBorderSide(13);
            logoCell.setFixedHeight(20);
            table.addCell(logoCell);
        }catch (IOException e){
            Phrase nameP = new Phrase("", textFont);
            PdfPCell nameCell = new PdfPCell(nameP);
            nameCell.disableBorderSide(13);
            nameCell.setFixedHeight(20);
            table.addCell(nameCell);
        }

        Phrase nameP = new Phrase("页眉右上角显示的内容", textFont);
        PdfPCell nameCell = new PdfPCell(nameP);
        //只保留底部边框和设置高度 设置水平居右和垂直居中
        nameCell.disableBorderSide(13);
        nameCell.setFixedHeight(20);
        nameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        nameCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(nameCell);

        //再把表格写到页眉处  使用绝对定位
        table.writeSelectedRows(0, -1, 30, PageSize.A4.getHeight()-5, writer.getDirectContent());
    }

    /**
     * 页脚
     */
    private void addPageFooter(PdfWriter writer, Document docment) throws DocumentException, IOException {

        BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        //创建字体
        Font textFont = new Font(BASE_FONT, 10f);

        //三列  一列导出人  一列页码   一列时间
        PdfPTable table = new PdfPTable(3);
        //设置表格宽度 A4纸宽度减去两个边距  比如我一边30  所以减去60
        table.setTotalWidth(PageSize.A4.getWidth()-60);
        //仅保留顶部边框
        table.getDefaultCell().disableBorderSide(14);
        table.getDefaultCell().setFixedHeight(40);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        //导出人
        table.addCell(new Phrase("admin", textFont));

        //页码
        //初始化总页码模板
        if(null == totalNumTemplate){
            totalNumTemplate = writer.getDirectContent().createTemplate(30, 16);
        }
        //再嵌套一个表格 一左一右  左边当前页码 右边总页码 
        PdfPTable pageNumTable = new PdfPTable(2);
        pageNumTable.setTotalWidth(new float[]{80f, 80f});
        pageNumTable.setLockedWidth(true);
        pageNumTable.setPaddingTop(-5f);
        //第一列居右
        pageNumTable.getDefaultCell().disableBorderSide(15);
        pageNumTable.getDefaultCell().setFixedHeight(16);
        pageNumTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        pageNumTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
        pageNumTable.addCell(new Phrase(writer.getPageNumber()+" / ", textFont));
        //第二列居左
        Image totalNumImg = Image.getInstance(totalNumTemplate);
        totalNumImg.setPaddingTop(-5f);
        pageNumTable.getDefaultCell().setPaddingTop(-18f);
        pageNumTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        pageNumTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        pageNumTable.addCell(totalNumImg);
        //把页码表格添加到页脚表格
        table.addCell(pageNumTable);

        //日期
        table.addCell(new Phrase(String.valueOf(new Date()), textFont));

        //再把表格写到页脚处  使用绝对定位
        table.writeSelectedRows(0, -1, 30, 40, writer.getDirectContent());
    }

    /**
     * 文档关闭事件
     */
    @SneakyThrows
    @Override
    public void onCloseDocument(PdfWriter writer, Document docment){
        BaseFont BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        //创建字体
        Font textFont = new Font(BASE_FONT, 10f);
        //将最后的页码写入到总页码模板
        String totalNum = writer.getPageNumber() + "页";
        totalNumTemplate.beginText();
        totalNumTemplate.setFontAndSize(BASE_FONT, 5f);
        totalNumTemplate.showText(totalNum);
        totalNumTemplate.setHeight(16f);
        totalNumTemplate.endText();
        totalNumTemplate.closePath();
    }
}

2. Pdf生成 [ PdfCell添加图片参考createHardwarePDF方法的第九行nineRowTalbe ]

package com.mediinfo.test;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;

public class PdfUtils {

    //使用例子
    public static void main(String[] args) throws Exception {
        createHardwarePDF("d:/test.pdf");
    }

    /**
     * 新建以下两个方法,创建表格内的字体和样式的方法
     *
     * @param str  内容
     * @param font 字体对象
     * @param high 表格高度
     * @return
     * @Param alignCenter 是否水平居中
     * @Param alignMidde  是否垂直居中
     */
    private static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde) {
        PdfPCell pdfPCell = new PdfPCell(new Phrase(str, font));
        pdfPCell.setMinimumHeight(high);
        pdfPCell.setUseAscender(true); // 设置可以居中
        if (alignCenter) {
            pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
        }
        if (alignMidde) {
            pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
        }
        return pdfPCell;
    }

    /**
     * @param str  字符串
     * @param font 字体
     * @param high 表格高度
     * @return
     * @Param alignCenter 是否水平居中
     * @Param alignMidde  是否垂直居中
     * @Param haveColor 是否有背景色(灰色)
     */
    private static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde, boolean haveColor) {
        PdfPCell pdfPCell = new PdfPCell(new Phrase(str, font));
        pdfPCell.setMinimumHeight(high);
        pdfPCell.setUseAscender(true); // 设置可以居中
        if (alignCenter) {
            pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
        }
        if (alignMidde) {
            pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
        }
        if (haveColor) {
            //颜色代码 RGB
            pdfPCell.setBackgroundColor(new BaseColor(217, 217, 217));
        }
        return pdfPCell;
    }

    /*
    将图片插入到PdfCell
     */
//    private static PdfPCell mircoSoftFont(byte[] iamgeBytes, int high) throws Exception {
    private static PdfPCell ImageSet(int high) throws Exception {
        byte[] fileByte = toByteArray("D:\\2.jpg");
        Jpeg jpeg = new Jpeg(fileByte);
        jpeg.scaleAbsolute(70, 50);

        PdfPCell pdfPCell = new PdfPCell(jpeg);
        pdfPCell.setMinimumHeight(high);
        pdfPCell.setUseAscender(true); // 设置可以居中
        pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
        pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
        return pdfPCell;
    }


    /*
    生成Pdf文档
     */
    public static void createHardwarePDF(String outputPath) throws Exception {
        //新建文档对象,页大小为A4纸,然后设置4个边距
        Document document = new Document(PageSize.A4, 20, 20, 30, 30);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));

        //创建字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //字体对象
        Font size14font = new Font(baseFont, 14, Font.NORMAL);  //大小为14的正常字体
        Font size10font = new Font(baseFont, 10, Font.BOLD); //大小为10的粗体
        document.open();

        // 添加页眉和页码  Add By Zhaof 2022-11-16 实测可用
        // 要修改页眉页脚显示的内容,直接修改PdfHeaderFooterEvent对象的页眉页脚内容即可;
        PdfHeaderFooter event = new PdfHeaderFooter();
        writer.setPageEvent(event);

        //添加标题
        PdfPTable tableName = new PdfPTable(1);
        tableName.setWidthPercentage(90);  //设置标题长度占纸张比例

        PdfPCell titleCell = mircoSoftFont("个人信息", size14font, 80, true, true);
        titleCell.disableBorderSide(15);
        tableName.addCell(titleCell);
        document.add(tableName);
        //添加第二行的数据
        PdfPTable secondRowTable = new PdfPTable(3); //三列的意思
        secondRowTable.setWidthPercentage(90);
        //这里的数组长度是上面创建的列数,数组的总和为1,就是按比例划分的意思
        secondRowTable.setTotalWidth(new float[]{0.18f, 0.32f, 0.5f});
        secondRowTable.addCell(mircoSoftFont(" 姓名: ", size10font, 50, false, true));
        secondRowTable.addCell(mircoSoftFont("李晓明", size10font, 50, false, true));
        secondRowTable.addCell(mircoSoftFont(" 出生日期: 1994年3月14日", size10font, 50, false, true));
        document.add(secondRowTable);
        //第三行数据
        PdfPTable thirdRowTable = new PdfPTable(3);
        thirdRowTable.setWidthPercentage(90);
        thirdRowTable.setTotalWidth(new float[]{0.18f, 0.32f, 0.5f});
        thirdRowTable.addCell(mircoSoftFont(" 名族:", size10font, 50, false, true));
        thirdRowTable.addCell(mircoSoftFont("汉族", size10font, 50, false, true));
        thirdRowTable.addCell(mircoSoftFont(" 联系电话: 13888880000", size10font, 50, false, true));
        document.add(thirdRowTable);
        //第四行数据
        PdfPTable fourthRowTable = new PdfPTable(2);
        fourthRowTable.setWidthPercentage(90);
        fourthRowTable.setTotalWidth(new float[]{0.66f, 0.34f});
        fourthRowTable.addCell(mircoSoftFont(" 个人描述 :", size10font, 175, false, false));
        fourthRowTable.addCell(mircoSoftFont("个人特长 :", size10font, 175, false, false));
        document.add(fourthRowTable);
        //第五行
        PdfPTable fifthDetailName = new PdfPTable(1);
        fifthDetailName.setWidthPercentage(90);
        fifthDetailName.addCell(mircoSoftFont("获奖记录 :", size14font, 50, true, true));
        document.add(fifthDetailName);
        //第六行
        PdfPTable sisthRowTalbe = new PdfPTable(1);
        sisthRowTalbe.setWidthPercentage(90);
        sisthRowTalbe.addCell(mircoSoftFont(" 联系地址: " + "广东省广州市天河区XXXXXXXXXXXXXXXXXX", size10font, 50, false, true));
        document.add(sisthRowTalbe);
        PdfPTable seventhRowTalbe = new PdfPTable(1);
        seventhRowTalbe.setWidthPercentage(90);
        seventhRowTalbe.addCell(mircoSoftFont(" 毕业院校 ", size14font, 60, true, true));
        document.add(seventhRowTalbe);
        //第八行
        PdfPTable eiththRowTalbe = new PdfPTable(3);
        eiththRowTalbe.setWidthPercentage(90);
        eiththRowTalbe.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
        eiththRowTalbe.addCell(mircoSoftFont(" 毕业学校", size10font, 50, true, true, true));
        eiththRowTalbe.addCell(mircoSoftFont(" 就读日期", size10font, 50, true, true, true));
        eiththRowTalbe.addCell(mircoSoftFont(" 联系人", size10font, 50, true, true, true));
        document.add(eiththRowTalbe);
        //接下来加List
        String school = "XXX学校";
        String time = "201909  -  2022-06";
        String name = "陈某";
        for (int i = 0; i < 2; i++) {
            PdfPTable tempTable = new PdfPTable(3);
            tempTable.setWidthPercentage(90);
            tempTable.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
            tempTable.addCell(mircoSoftFont(school, size10font, 50, true, true));
            tempTable.addCell(mircoSoftFont(time, size10font, 50, true, true));
            tempTable.addCell(mircoSoftFont(name, size10font, 50, true, true));
            document.add(tempTable);
        }

        // 第九行,添加图片
        PdfPTable nineRowTalbe = new PdfPTable(3);
        nineRowTalbe.setWidthPercentage(90);
        nineRowTalbe.setTotalWidth(new float[]{0.3f, 0.5f, 0.2f});
        nineRowTalbe.addCell(mircoSoftFont(" test1", size10font, 50, true, true));
        nineRowTalbe.addCell(mircoSoftFont(" test222", size10font, 50, true, true));
        nineRowTalbe.addCell(ImageSet(50));   // 给PdfCell添加图片
        document.add(nineRowTalbe);

        document.close();
        writer.close();
    }



    public static byte[] toByteArray(String filename) throws IOException {

        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }




}

3. 实现效果如下图

在这里插入图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值