Itext生成自定义PDF

Itext生成自定义PDF

去年写的,以下为测试类

package com.test;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.common.utils.DateUtil;
import com.common.utils.HeaderFooter;
import lombok.Data;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lzh
 * @date 2021/11/19 16:10
 */
public class Test{
    private static Font textFont;
    private static Font headFont;
    private static Font secondTitleFont;
    private static BaseColor darkGrey = new BaseColor(140,140,140);
    private static BaseColor lightGrey = new BaseColor(235,235,235);
    static {
        try {
            //设置字体样式
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //正常
            textFont = new Font(bfChinese, 10, Font.NORMAL);
            //表头
            headFont = new Font(bfChinese, 13, Font.NORMAL);
            //标题
            secondTitleFont = new Font(bfChinese, 16, Font.NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 学生类
     */
    @Data
    private static class Student{
        private String name;
        private Integer age;
        private String classes;

        public Student(String name, Integer age, String classes) {
            this.name = name;
            this.age = age;
            this.classes = classes;
        }
    }

	//隔行换色
    private static class AlternatingBackground implements PdfPTableEvent {
        //重写tableLayout方法
        @Override
        public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
            int columns;
            Rectangle rect;
            int footer = widths.length - table.getFooterRows();
            int header = table.getHeaderRows() - table.getFooterRows() + 1;
            for (int row = header; row < footer; row += 2) {
                columns = widths[row].length - 1;
                rect = new Rectangle(widths[row][0], heights[row], widths[row][columns], heights[row + 1]);
                rect.setBackgroundColor(lightGrey);
                canvases[PdfPTable.BASECANVAS].rectangle(rect);
            }
        }
    }

	/**
     * PDF工具类
     * @author: lzh
     * @date: 2020/1/14 2:09:48
     */
    private static class PDFUtil {
        /**
         * 获取指定内容与字体的单元格
         * @param text      单元格内容
         * @param font      字体
         * @param border    禁用边框(0-15)
         * @return PdfPCell
         * @throws
         */
        private static PdfPCell getPDFCell(String text, Font font, int border) {
            //创建单元格对象,将内容与字体放入段落中作为单元格内容
            PdfPCell cell = new PdfPCell(new Paragraph(text, font));
            //设置居中
            cell.setUseAscender(true);
            //设置单元格内容向左居中
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            //设置单元格字体垂直居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //设置最小单元格高度
            cell.setMinimumHeight(25);
            cell.disableBorderSide(border);
            return cell;
        }

        /**
         * 获取带有图片的单元格
         * @param image 图片
         * @return
         */
        private PdfPCell getPDFCell(Image image) {
            //创建单元格对象
            PdfPCell cell = new PdfPCell();
            //设置居中
            cell.setUseAscender(true);
            //设置单元格内容向左居中
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setImage(image);
            //设置最小单元格高度
            cell.setMinimumHeight(25);
            return cell;
        }

        /**
         * 获取合并行之后的单元格
         * @param text      内容
         * @param font      字体
         * @param rowspan   行数
         * @return PdfPCell
         * @throws
         */
        private PdfPCell mergeRow(String text,Font font,int rowspan) {
            //创建单元格对象,将内容与字体放入段落中作为单元格内容
            PdfPCell cell=new PdfPCell(new Paragraph(text,font));
            //设置单元格内容向左居中
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            //设置单元格字体垂直居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //将该单元格所在列包括该单元格在内的x行单元格合并为一个单元格
            cell.setRowspan(rowspan);
            return cell;
        }

        /**
         * 获取合并列之后的单元格
         * @param text      内容
         * @param font      字体
         * @param colspan   列数
         * @param border    禁用边框(0-15)
         * @return PdfPCell
         * @throws
         */
        private PdfPCell mergeCol(String text,Font font,int colspan,int border) {
            //创建单元格对象,将内容与字体放入段落中作为单元格内容
            PdfPCell cell=new PdfPCell(new Paragraph(text,font));
            //设置单元格内容向左居中
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            //设置单元格字体垂直居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //将该单元格所在列包括该单元格在内的x列单元格合并为一个单元格
            cell.setColspan(colspan);
            //设置单元格最小高度
            cell.setMinimumHeight(25);
            cell.disableBorderSide(border);
            return cell;
        }

        /**
         * 获取合并列之后的单元格-标题
         * @param text      内容
         * @param color     颜色
         * @param font      字体
         * @param colspan   列数
         * @return PdfPCell
         * @throws
         */
        private static PdfPCell mergeTitleCol(String text, Font font, BaseColor color, int colspan) {
            //创建单元格对象,将内容与字体放入段落中作为单元格内容
            PdfPCell cell=new PdfPCell(new Paragraph(text,font));
            //设置单元格背景颜色
            cell.setBackgroundColor(color);
            //设置单元格内容向左居中
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //设置单元格字体垂直居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //将该单元格所在列包括该单元格在内的x列单元格合并为一个单元格
            cell.setColspan(colspan);
            //设置单元格最小高度
            cell.setMinimumHeight(28);
            return cell;
        }
    }

    public static void main(String[] args) throws Exception {
        List<Student> list = new ArrayList<>();
        Student student1 = new Student("张三",10,"101班");
        Student student2 = new Student("李四",12,"124班");
        Student student3 = new Student("小明",9,"092班");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Document document = new Document(PageSize.LEGAL);
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //输出到本地
        FileOutputStream out = new FileOutputStream("C:\\Users\\18500\\Desktop\\test.pdf");
        try {
            //创建输出流
            PdfWriter writer = PdfWriter.getInstance(document, out);
            //设置页脚
            HeaderFooter headerFooter = new HeaderFooter();
            writer.setPageEvent(headerFooter);
            document.open();
            PdfPTable table = new PdfPTable(3);
            //设置页眉
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase("打印日期: " + DateUtil.formatTimeYMD_HMS(new Date()), textFont), document.right(), document.top() + 20, 0);
            //设置表格居中
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            //设置列宽(总和为540)
            table.setTotalWidth(new float[]{180, 180, 180});
            //锁定列宽
            table.setLockedWidth(true);
            table.addCell(PDFUtil.mergeTitleCol("学生列表", secondTitleFont, darkGrey, 3));
            table.addCell(PDFUtil.getPDFCell("姓名", headFont, 11));
            table.addCell(PDFUtil.getPDFCell("年龄", headFont, 15));
            table.addCell(PDFUtil.getPDFCell("班级", headFont, 7));
            for(Student student : list) {
                //将最后一行边框包住
                if(list.size() - 1 == list.indexOf(student)){
                    table.addCell(PDFUtil.getPDFCell(student.getName(), textFont, 9));
                    table.addCell(PDFUtil.getPDFCell(student.getAge().toString(), textFont, 13));
                    table.addCell(PDFUtil.getPDFCell(student.getClasses(), textFont, 5));
                }else {
                    table.addCell(PDFUtil.getPDFCell(student.getName(), textFont, 11));
                    table.addCell(PDFUtil.getPDFCell(student.getAge().toString(), textFont, 15));
                    table.addCell(PDFUtil.getPDFCell(student.getClasses(), textFont, 7));
                }
            }
            //加入隔行换色事件
            PdfPTableEvent event = new AlternatingBackground();
            table.setTableEvent(event);
            document.add(table);
        } finally {
            document.close();
        }
    }
}

效果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值