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();
    }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java FTL生成PDF是一种将FreeMarker模板Java代码结合使用的技术,用于生成PDF文件。FreeMarker是一个模板引擎,它提供了模板的定义和数据的注入机制,可以将模板与数据结合起来生成输出内容。 在Java使用FTL生成PDF的过程通常包括以下几个步骤: 1. 导入所需的Java和FTL库:首先,需要在Java项目引入相应的FTL库,以及用于生成PDF的相关Java库,例如iText。这些库可以通过Maven等构建工具进行导入。 2. 创建FreeMarker模板:使用FreeMarker模板定义需要生成PDF的样式和格式。模板可以包含静态内容,也可以通过模板语言标记占位符,用于插入动态数据。 3. 编写Java代码:在Java,通过调用FreeMarker库的相关类和方法,可以将数据与模板进行合并,生成包含动态数据的文本内容。 4. 生成PDF文件:在得到合并后的文本内容后,使用iText等相关Java库将文本内容转化为PDF格式。这些库提供生成PDF的方法和API,可以指定生成的PDF文件的路径和样式。 使用Java FTL生成PDF的好处是,可以通过模板和数据分离的方式,实现PDF的动态生成,从而提高开发效率和灵活性。通过模板的复用,可以实现对于不同数据的PDF生成,从而满足不同的需求。同时,使用Java的优势也能够提供更多的功能和扩展性,比如添加图片、表格等多样化的内容。 当然,需要注意的是,Java FTL生成PDF仍然需要对Java和FreeMarker的使用有一定的了解和掌握。在使用过程,也需要关注文件路径、字体设置、编码等细节,以确保生成的PDF文件符合预期的要求。 ### 回答2: Java FTL(FreeMarker Template Language)可以用来生成PDF文件。FTL是一种模板语言,常用于生成动态的网页内容。但是,我们也可以通过将FTL模板与相应的数据进行结合,然后使用Java代码来渲染模板并生成PDF文件。 首先,我们需要设置一个FTL模板,其包含我们想要在PDF显示的内容。这个模板可以包含HTML标记和FTL标签,用于在生成PDF插入动态数据。 然后,我们需要在Java代码使用FreeMarker库来实现模板的渲染和生成PDF文件的功能。这可以通过以下步骤完成: 1. 创建一个Configuration对象,并设置模板文件的路径。这将告诉FreeMarker在哪里查找FTL模板文件。 2. 使用Configuration对象创建一个Template对象,将需要使用的模板文件作为参数传递给它。 3. 创建一个Writer对象,用于将生成的PDF内容写入。 4. 创建一个Map对象,并将需要在FTL模板使用的数据放入其。这些数据将替换模板的FTL标签。 5. 使用Template对象的process方法,将Map对象和Writer对象作为参数传递给它。这将生成PDF文件的内容并将其写入Writer对象。 6. 最后,将Writer对象的内容写入到PDF文件,完成PDF文件的生成。 总结起来,通过使用Java和FTL模板,我们可以生成动态的PDF文件。首先设置模板文件,然后使用Java代码来渲染模板并将数据填充到模板,最后将生成的内容写入到PDF文件即可。 ### 回答3: Java与FreeMarker模板引擎(FTL)可以结合生成PDF文档。具体过程如下: 首先,我们需要使用Java的相关库来操作PDF文档。常用的库有iText、Apache PDFBox等。这些库提供了一些API来创建、编辑和保存PDF文件。 其次,我们需要准备好FTL模板文件。FTL是一种模板引擎语言,可以将数据动态地填充到模板,生成相应的输出文本。 然后,我们需要在Java代码使用FTL模板引擎。Java有一些FTL模板引擎的实现,比如FreeMarker和Velocity。我们可以选择其之一,然后使用相应的API来加载模板文件。 接下来,我们需要准备数据。通过Java代码,我们可以从数据库、文件或其他资源获取数据。然后,将数据与FTL模板进行结合,填充到模板。 最后,我们使用PDF库的API将生成的文本保存为PDF文件。根据选择的PDF库,可能会有一些具体的步骤和API调用。 总结来说,使用Java和FTL模板引擎生成PDF的过程包括准备PDF库、准备FTL模板文件、使用Java代码加载模板、准备数据并填充到模板,最后使用PDF库将生成的文本保存为PDF文件。这样,我们就可以通过Java和FTL生成PDF文档了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值