Java操作PDF,在PDF模板中插入表格

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
 /**
     * 成绩导出pdf
     * @return
     */
    @Log(title = "成绩导出pdf", businessType = BusinessType.OTHER)
    @GetMapping( "/scoreExportPdf")
    public void scoreExportPdf(String xh, HttpServletResponse response) {
        //用户信息
        XyUser xyUser = xyUserService.selectXyUserByXH(xh);
        if (xyUser == null) {
//            return AjaxResult.success("未查到该学号用户");
            return;
        }

        String LOCAL_LIST_PATH = "classpath:ehcache/score.pdf";
        InputStream inputStream = null;
        PdfReader reader = null;
        try {
            inputStream = ResourceUtils.getInputStreamForPath(LOCAL_LIST_PATH);
            reader = new PdfReader(inputStream);
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        String profile = RuoYiConfig.getProfile()+"/scoreExportPdf/";
        File desc = new File(profile);
        //判断是否有该文件夹,没有的话创建
        if (!desc.exists()) {
            desc.mkdirs();
        }
        profile += UUID.randomUUID().toString()+".pdf";

        PdfStamper stamper = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(profile);
            stamper = new PdfStamper(reader, fileOutputStream);
        } catch (DocumentException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        PdfContentByte overContent = stamper.getOverContent(1);
        //添加文字
        BaseFont font = null;
        try {
            font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        overContent.beginText();
        overContent.setFontAndSize(font, 10);
        overContent.setTextMatrix(200, 200);
        overContent.showTextAligned(Element.ALIGN_CENTER,"成绩单",300,730,0);
        overContent.showTextAligned(Element.ALIGN_CENTER,"学号:"+xyUser.getXh()+"      姓名:"+xyUser.getMz()+"      年级:"+xyUser.getNj()+"      专业:"+xyUser.getZy()+"      层次:"+xyUser.getCc(),300,710,0);
//        overContent.showTextAligned(Element.ALIGN_CENTER,"需要添加的文字1  222",100,715,0);
//        overContent.showTextAligned(Element.ALIGN_CENTER,"需要添加的文字  2",100,700,0);
        overContent.endText();

        //横向分割
        PdfPTable table = new PdfPTable(8);
        table.setHeaderRows(1);
        //边框
        table.getDefaultCell().setBorderWidth(1);

        //标题
        Font font1 = new Font(font, 10, Font.NORMAL);
        Font font2 = new Font(font, 8, Font.NORMAL,new BaseColor(54, 95, 145));
        Font font3 = new Font(font, 8, Font.NORMAL);
        PdfPCell begCell = new PdfPCell(new Paragraph("课程名称",font1));
        begCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCell.setBackgroundColor(new BaseColor(122, 193, 236));
        begCell.setBorder(0);
        table.addCell(begCell);

        PdfPCell begCell1 = new PdfPCell(new Paragraph("课程性质",font1));
        begCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCell1.setBackgroundColor(new BaseColor(122, 193, 236));
        begCell1.setBorder(0);
        table.addCell(begCell1);

        PdfPCell begCell2 = new PdfPCell(new Paragraph("学分",font1));
        begCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCell2.setBackgroundColor(new BaseColor(122, 193, 236));
        begCell2.setBorder(0);
        table.addCell(begCell2);

        PdfPCell begCell3 = new PdfPCell(new Paragraph("成绩",font1));
        begCell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCell3.setBackgroundColor(new BaseColor(122, 193, 236));
        begCell3.setBorder(0);
        begCell3.setBorderWidthRight(0.3f);
        begCell3.setBorderColorRight(new BaseColor(170, 170, 170));
        table.addCell(begCell3);

        PdfPCell begCellExt = new PdfPCell(new Paragraph("课程名称",font1));
        begCellExt.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCellExt.setBackgroundColor(new BaseColor(122, 193, 236));
        begCellExt.setBorder(0);
        table.addCell(begCellExt);

        PdfPCell begCellExt1 = new PdfPCell(new Paragraph("课程性质",font1));
        begCellExt1.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCellExt1.setBackgroundColor(new BaseColor(122, 193, 236));
        begCellExt1.setBorder(0);
        table.addCell(begCellExt1);

        PdfPCell begCellExt2 = new PdfPCell(new Paragraph("学分",font1));
        begCellExt2.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCellExt2.setBackgroundColor(new BaseColor(122, 193, 236));
        begCellExt2.setBorder(0);
        table.addCell(begCellExt2);

        PdfPCell begCellExt3 = new PdfPCell(new Paragraph("成绩",font1));
        begCellExt3.setHorizontalAlignment(Element.ALIGN_CENTER);
        begCellExt3.setBackgroundColor(new BaseColor(122, 193, 236));
        begCellExt3.setBorder(0);
        table.addCell(begCellExt3);


        //根据学号查询成绩
        List<XyStudentAchievement> xyStudentAchievementList = xyStudentAchievementMapper.selectXyStudentAchievementXhList(xh);
        List<String> stringList = xyStudentAchievementList.stream().map(XyStudentAchievement::getXn).distinct().collect(Collectors.toList());

        for (String xn : stringList) {
            //当前学期课程数
            List<XyStudentAchievement> collect = xyStudentAchievementList.stream().filter(xyStudentAchievement -> xyStudentAchievement.getXn().equals(xn)).collect(Collectors.toList());
            Map<String, Object> objectMap = schoolScore(collect);
            //设置学期
            PdfPCell beg = new PdfPCell(new Paragraph(xn + " (第"+collect.get(0).getXq()+")学期  平均分:"+objectMap.get("avg")+",学分:"+objectMap.get("xfCount")+",GPA:"+objectMap.get("gpa")+"/5 ",font2));
            beg.setColspan(6);
            beg.setBorder(0);
            beg.setBorderWidthBottom(0.3f);
            beg.setBorderColorBottom(new BaseColor(170, 170, 170));
            //边框颜色
//            beg.setBorderColor(new BaseColor(54, 95, 145));
            table.addCell(beg);
            PdfPCell beg1 = new PdfPCell(new Paragraph("小计:课程数"+collect.size()+",",font2));
            beg1.setColspan(2);
            beg1.setBorder(0);
            beg1.setBorderWidthBottom(0.3f);
            beg1.setBorderColorBottom(new BaseColor(170, 170, 170));
            beg1.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(beg1);
            int result = 0;
            for (XyStudentAchievement xyStudentAchievement : collect) {
                result++;
                //添加课程
                //课程名称
                PdfPCell kecCell = new PdfPCell(new Paragraph(xyStudentAchievement.getKcmc(),font3));
                kecCell.setColspan(1);
                kecCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                kecCell.setBorder(0);
                kecCell.setBorderWidthBottom(0.3f);
                kecCell.setBorderColorBottom(new BaseColor(170, 170, 170));
                table.addCell(kecCell);
                //课程性质
                PdfPCell kecCell1 = new PdfPCell(new Paragraph(xyStudentAchievement.getKcxz(),font3));
                kecCell1.setColspan(1);
                kecCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                kecCell1.setBorder(0);
                kecCell1.setBorderWidthBottom(0.3f);
                kecCell1.setBorderColorBottom(new BaseColor(170, 170, 170));
                table.addCell(kecCell1);
                //学分
                PdfPCell kecCell2 = new PdfPCell(new Paragraph(xyStudentAchievement.getXf(),font3));
                kecCell2.setColspan(1);
                kecCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                kecCell2.setBorder(0);
                kecCell2.setBorderWidthBottom(0.3f);
                kecCell2.setBorderColorBottom(new BaseColor(170, 170, 170));
                table.addCell(kecCell2);
                //成绩
                PdfPCell kecCell3 = new PdfPCell(new Paragraph(xyStudentAchievement.getKccj(),font3));
                kecCell3.setColspan(1);
                kecCell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                kecCell3.setBorder(0);
                kecCell3.setBorderWidthBottom(0.3f);
                kecCell3.setBorderColorBottom(new BaseColor(170, 170, 170));
                if (result%2 == 1) {
                    kecCell3.setBorderWidthRight(0.3f);
                    kecCell3.setBorderColorRight(new BaseColor(170, 170, 170));
                }
                table.addCell(kecCell3);
            }
            if (collect.size()%2 == 1) {
                PdfPCell kecCell3 = new PdfPCell(new Paragraph("",font3));
                kecCell3.setColspan(4);
                kecCell3.setBorder(0);
                kecCell3.setBorderWidthBottom(0.3f);
                kecCell3.setBorderColorBottom(new BaseColor(170, 170, 170));
                table.addCell(kecCell3);
            }
        }


        //底部总计
        if (xyStudentAchievementList.size() > 0) {
            Map<String, Object> objectMap = schoolScore(xyStudentAchievementList);
            //设置学期
            PdfPCell beg = new PdfPCell(new Paragraph("总计:课程数:"+xyStudentAchievementList.size()+", 平均分:"+objectMap.get("avg")+",学分:"+objectMap.get("xfCount")+",GPA:"+objectMap.get("gpa")+"/5 ",font3));
            beg.setColspan(8);
            beg.setHorizontalAlignment(Element.ALIGN_RIGHT);
            beg.setBorder(0);
            table.addCell(beg);
        }

        table.setTotalWidth(500);
        table.writeSelectedRows(0, 8, 0, -1, 40, 700, overContent);

        // 设置输出的格式
//        response.setContentType("application/pdf");
//        response.addHeader("content-type","application/x-msdownload");
//        response.addHeader("Content-Disposition","attachment; filename=" + UUID.randomUUID().toString() + ".pdf");
//        OutputStream OS = null;
//        try {
//            OS = response.getOutputStream();
            baos.writeTo(OS);
//            OS.write(baos.toByteArray());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }



            //        table.writeSelectedRows(5, -1, 0, -1, 210, 700, overContent);

//        addWatermark(stamper, "www.360sdn.com" );

//        AcroFields s = stamper.getAcroFields();
//        //插入文字
//        insertText(stamper, s);
//
//        try {
//            stamper.close();
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        reader.close();



//        PdfContentByte over = stamper.getOverContent(1);


//        BaseFont bf_times = null;
//        try {
            bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
//            bf_times = BaseFont.createFont( "STSongStd-Light" ,
//                    "UniGB-UCS2-H",
//                    BaseFont.NOT_EMBEDDED);
            bf_times = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        over.beginText();
//用来设置文字的位置和字体---开始
//        over.setColorFill(BaseColor.RED);
//        over.setFontAndSize(bf_times,16);
//        over.setTextRise(45);//斜度
//横向居中
//under.setTextMatrix((pageWidth-fontSize*stampStr.length())/2+50,(pageHeight-fontSize*stampStr.length())/2+100);
//        PdfGState gs = new PdfGState();
//        gs.setFillOpacity(0.3f);// 设置透明度为0.8
//        over.setGState(gs);
//用来设置文字的位置和字体---结束
//        over.setTextMatrix(100,400);
//        over.newlineShowText("姓名\t成绩\t学号\t性别\n111");
//        over.endText();

        try {
            stamper.close();
        } catch (DocumentException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }


        response.setContentType("application/pdf");
//        response.addHeader("content-type","application/x-msdownload");
//        response.addHeader("Content-Disposition","attachment; filename=" + UUID.randomUUID().toString() + ".pdf");
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(profile));
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[512];
            while ((in.read(b))!=-1) {
                out.write(b);
            }
            out.flush();
            in.close();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }


//        Rectangle pageSize = reader.getPageSize(1);
//        Document document = new Document(pageSize);
//        try {
//            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }
//
//        document.open();
//        try {
//            document.add(new Paragraph("Hello World"));
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }
//        document.close();

//        PdfPTable table = new PdfPTable(3);
//        PdfPCell cell;
//        cell = new PdfPCell(new Phrase("Cell with colspan 3"));
//        cell.setColspan(3);
//        table.addCell(cell);
//        cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
//        cell.setRowspan(2);
//        table.addCell(cell);
//        table.addCell("row 1; cell 1");
//        table.addCell("row 1; cell 2");
//        table.addCell("row 2; cell 1");
//        table.addCell("row 2; cell 2");
//        try {
//            document.add(table);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }

//        return AjaxResult.success();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值