itext7实现导出数据至pdf压缩包

1、配置文件中引入itext7依赖jar包
jar包从git上可以获取不同版本https://github.com/itext/itext7/releases

        <properties>
            <itext.version>7.1.11</itext.version>
        </properties>
        <!-- itext7 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>io</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>forms</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>pdfa</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>pdftest</artifactId>
            <version>${itext.version}</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>${itext.version}</version>
        </dependency>

2、代码部分
导出接口

    @ApiOperation(value = "导出竞卖活动列表")
    @RequestMapping(value = "/export/{encrypted}",method = {RequestMethod.GET})
    public void getPdf(@PathVariable String encrypted, HttpServletResponse resp, HttpServletRequest req)
    {
        String decrypted = new String(Base64.getUrlDecoder().decode(encrypted.getBytes()));
        AuctionListRequest listReq = JSON.parseObject(decrypted, AuctionListRequest.class);
        //查询竞卖信息
        List<AuctionVO> auctionVOList = getAuctions(listReq);
        if(CollectionUtils.isEmpty(auctionVOList)){
            throw new SbcRuntimeException();
        }

        try {
            ServletOutputStream os = resp.getOutputStream();
            String destDir = req.getServletContext().getRealPath("/")+ File.separator+"pdfFiles"+File.separator;
            File destDirFile = new File(destDir);
            if(!destDirFile.exists()){
                destDirFile.mkdirs();
            }
            //            PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H,false);//解决显示中文字体
            List<File> files = new ArrayList<>();
            auctionVOList.forEach(auctionVO->{
                //文件名:商家名称-活动名称-活动开始/结束时间
                String name = auctionVO.getSupplierName()+"-"+auctionVO.getAuctionName()+"-"+auctionVO.getStartTime().format(DateTimeFormatter.ofPattern(DateUtil.FMT_TIME_2))+"~"+auctionVO.getEndTime().format(DateTimeFormatter.ofPattern(DateUtil.FMT_TIME_2))+".pdf";
                File file = new File(destDir,name);
                PdfWriter writer = null;
                PdfFont font = null;
                try {
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    writer = new PdfWriter(file);
                    font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",true);
                } catch (Exception e) {
                    log.error("/auction/export/params error: ", e);
                    throw new SbcRuntimeException(SiteResultCode.ERROR_000001);
                }
                PdfDocument pdf = new PdfDocument(writer);
                Document document = new Document(pdf).setFont(font).setFontSize(14);
                //竞拍信息
                document.add(new Paragraph("活动详情-"+auctionVO.getAuctionType().getDesc()).setTextAlignment(TextAlignment.CENTER));
                Table auctionTable = PdfUtil.createTable(2);//创建表格
                Field[] auctionFields = PdfAuctionDto.class.getDeclaredFields();//获取dto 对象中所有的属性
                PdfUtil.generateNormalTable(auctionFields,generateAuctionMap(auctionVO),font,auctionTable);
                document.add(auctionTable);
                //拍品信息
                Table auctionGoodsTable = PdfUtil.createTable(12);//创建表格
                Field[] auctionGoodsFields = PdfAuctionGoodsDto.class.getDeclaredFields();//获取dto 对象中所有的属性
                List<Map<String,Object>> goodsMaps = new ArrayList<>();
                auctionVO.getAuctionGoodsInfoVOList().forEach(auctionGoodsInfoVO->{
                    goodsMaps.add(generateAuctionGoodsMap(auctionGoodsInfoVO));
                });
                PdfUtil.generateHeadTable(auctionGoodsFields,goodsMaps,font,auctionGoodsTable);
                document.add(auctionGoodsTable);
                //出价记录
                if(CollectionUtils.isNotEmpty(auctionVO.getAuctionBidVOList())){
                    document.add(new Paragraph(auctionVO.getAuctionType().equals(AuctionType.INCREASE_PRICE)?"出价记录":"降价记录").setTextAlignment(TextAlignment.CENTER).setMarginTop(20));
                    Table auctionBidTable = PdfUtil.createTable(7);//创建表格
                    Field[] auctionBidFields = PdfAuctionBidDto.class.getDeclaredFields();//获取dto 对象中所有的属性
                    List<Map<String,Object>> bidMaps = new ArrayList<>();
                    auctionVO.getAuctionBidVOList().forEach(auctionBidVO->{
                        bidMaps.add(generateAuctionBidMap(auctionBidVO));
                    });
                    PdfUtil.generateHeadTable(auctionBidFields,bidMaps,font,auctionBidTable);
                    document.add(auctionBidTable);
                }

                document.close();

                files.add(file);
            });

            //如果一个活动直接返回pdf,多个活动则打为压缩包
//            if(auctionVOList.size() == 1){
//                //商家名称-活动名称-活动开始/结束时间
//                AuctionVO auctionVO = auctionVOList.get(0);
//                filename = auctionVO.getSupplierName()+"-"+auctionVO.getAuctionName()+"-"+auctionVO.getStartTime().format(DateTimeFormatter.ofPattern(DateUtil.FMT_TIME_2))+"/"+auctionVO.getEndTime().format(DateTimeFormatter.ofPattern(DateUtil.FMT_TIME_2))+".pdf";
//                resp.setContentType("application/pdf");
//                resp.getOutputStream();
//            }else{
                //打为zip压缩包
                String filename = "竞卖活动.zip";
                ZipOutputStream zos = new ZipOutputStream(os);
                ZipEntry ze = null;
                for (int i = 0; i < files.size(); i++) {// 将所有需要下载的文件都写入临时zip文件
                    BufferedInputStream bis = new BufferedInputStream(
                            new FileInputStream(files.get(i)));
                    ze = new ZipEntry(files.get(i).getName());
                    zos.putNextEntry(ze);
                    int s = -1;
                    while ((s = bis.read()) != -1) {
                        zos.write(s);
                    }
                    bis.close();
                }
                zos.flush();
                zos.close();
                resp.setContentType("application/zip");// 定义输出类型
//            }

            resp.setHeader("Content-Disposition", "attachment;fileName="+ new String(filename.getBytes("utf-8"),"ISO8859-1"));
            resp.flushBuffer();
        } catch (Exception e) {
            log.error("/auction/export/params error: ", e);
            throw new SbcRuntimeException(SiteResultCode.ERROR_000001);
        } finally {
            exportCount.set(0);
        }
    }

PDF工具类

package com.wanmi.sbc.auction.pdf;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.DashedBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

public class PdfUtil {

    /**
     * 创建没有边框的Cell --设置字体大小为8,内边距设置成0,边框设置为无边框
     * @return
     */
    public static Cell getCellNoBorder(){
        return new Cell().setFontSize(10).setPaddings(0,0,0,0).setBorder(Border.NO_BORDER);//setBorder(Border.)
    }

    /**
     * 获取上边框为虚线的cell--因为默认情况下,边框默认是黑色实线边框,这里要把上边框设置成虚线并设置字体
     * @return
     */
    public static Cell getCellDashedBorder(){
        return new Cell().addStyle(new Style().setBorderTop(new DashedBorder(1))).setBorder(Border.NO_BORDER).setFontSize(10);
    }

    /**
     * 创建两列的表格并插入图片
     * @return
     */
    public static Table createTable(int numColumns){
        //创建两列的表格
        //表格在pdf整个页面的宽度百分比,这个值越小,整个个pdf表格越小,越靠近左边(这样说可能不对,大家可以试下)
        //设置外边距
        //设置图片在第一行表格中,cell(1,2) 代表这一行,有两列合并成一列,图像设置成自适应。这里有一个问题,就是当图像设置成自适应的时候通过new Table(new float[]{4,6})——创建两列的表格,列长度就是每个数组长度 创建的表格就会出现表格列长度改变的问题。
        return new Table(numColumns).
                setWidth(UnitValue.createPercentValue(100)).
                setMarginTop(10);
    }

    /**
     * 排序并生成指定样式的表格
     * @param a
     * @param map
     * @param font
     * @param table
     */
    public static void generateNormalTable(Field[] a, Map<String,Object> map, PdfFont font, Table table){
        for (Field field : a) { //遍历模板字段
            PdfValue annotation = field.getDeclaredAnnotation(PdfValue.class);//获取字段属性上的注释
            if (0==annotation.typeFile()){
                //如果是没有边框的Cell
                table.addCell(getCellNoBorder().add(new Paragraph(annotation.colName()).setFont(font)));
                //字体样式右对齐,默认是左对齐的
                table.addCell(getCellNoBorder().add(new Paragraph(map.get(field.getName())==null?"-":map.get(field.getName()).toString())).setFont(font));
            }
        }
    }

    /**
     * 有表头的Table
     * @param a
     * @param maps
     * @param font
     * @param table
     */
    public static void generateHeadTable(Field[] a, List<Map<String,Object>> maps, PdfFont font, Table table){
        //表头
        for (Field field : a) { //遍历模板字段
            PdfValue annotation = field.getDeclaredAnnotation(PdfValue.class);//获取字段属性上的注释
            table.addCell(new Paragraph(annotation.colName()).setFont(font).setFontSize(10));
        }
        //内容
        maps.forEach(map->{
            for (Field field : a) { //遍历模板字段
                //字体样式右对齐,默认是左对齐的
                table.addCell(new Paragraph(map.get(field.getName())==null?"-": map.get(field.getName()).toString())).setFont(font).setFontSize(10);
            }
        });
    }
}

PDF字段实体,这边只放一个作为示例

package com.wanmi.sbc.auction.pdf;

import lombok.Data;

@Data
public class PdfAuctionDto {
    /**
     * 所属商家
     */
    @PdfValue(colName = "所属商家:",typeFile = 0)
    private String supplierName;

    /**
     * 审核人员
     */
    @PdfValue(colName = "审核人员:",typeFile = 0)
    private String auditPerson;

    /**
     * 审核状态
     */
    @PdfValue(colName = "审核状态:",typeFile = 0)
    private String auditStatus;

    /**
     * 审核时间
     */
    @PdfValue(colName = "审核时间:",typeFile = 0)
    private String auditTime;

    /**
     * 活动名称
     */
    @PdfValue(colName = "活动名称:",typeFile = 0)
    private String auctionName;

    /**
     * 竞卖类型
     */
    @PdfValue(colName = "竞卖类型:",typeFile = 0)
    private String auctionType;

    /**
     * 起止时间
     */
    @PdfValue(colName = "起止时间:",typeFile = 0)
    private String auctionTime;

    /**
     * 延时周期
     */
    @PdfValue(colName = "延时周期:",typeFile = 0)
    private String delayPeriod;

}

字段注解

package com.wanmi.sbc.auction.pdf;

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface PdfValue {

    String colName() default "";
    int typeFile() default 0;//0-普通 不用边框 1-有边框

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容