SpringBoot加itext实现PDF导出 - Go语言中文社区

SpringBoot加itext实现PDF导出


场景


iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。

官网:

https://itextpdf.com/en

Itext实现导出PDF常用方法说明

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/89476534

实现

打开pom.xml导入项目依赖

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.2.0</version>
</dependency>
<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
</dependency>

前端实现

打印按钮

 

<button id="printPdfBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> pdf打印</button>

js中按钮的点击事件

 $("#printPdfBtn").click(function () {
        var data = t.rows(['.selected']).data()[0];
        if(undefined===data){
            swal({
                type: 'warning',
                title: '提示:',
                text: '请首先选择一行数据!',
                confirmButtonColor: "#1ab394",
            })
        }else{
            exportPdf(data.id);
        }
    });

其中 var data = t.rows(['.selected']).data()[0];
是dataTables中获取选中行的id属性。

exportPdf(data.id)负责执行具体的导出PDF请求

先判断能不能执行导出,如果能导出则跳转Url并将参数id传递。

function  exportPdf(id){
        $.post("/wmsInOrder/isExport.do",{id:id}).done(function (res) {
            if(res.status){
               if(res.data ==true){                  
 window.location.href="/wmsInOrder/exportPdf.html?orderId="+id;
                }else{
                    Swal.fire(
                        '请选择已完成的单',
                        res.data,
                        'warning'
                    )
                }
            }else{
                Swal.fire(
                    '导出失败!',
                    res.data,
                    res.msg
                )
            }
        }).fail(function (err) {
            Swal.fire(
                '异常提示',
                '执行导出操作失败',
                'error'
            )
        });
    }

来到url="/wmsInOrder/exportPdf.html?orderId="+id所对应的后台。

 @Description("pdf导出")
    @RequestMapping(value = "/exportPdf.html")
    public void excelPdf(long orderId,HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.inOrderService.exportPdf(orderId, request, response);
    }

来到service层

 void exportPdf(Long orderId, HttpServletRequest request, HttpServletResponse response) throws Exception ;

来到serviceImpl层

具体方法作用参照代码注解。

public void exportPdf(Long orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置响应格式等
        response.setContentType("application/pdf");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        Map<String,Object> map = new HashMap<>();
        //设置纸张规格为A4纸
        Rectangle rect = new Rectangle(PageSize.A4);
        //创建文档实例
        Document doc=new Document(rect);
        //添加中文字体
        BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //设置字体样式
        Font textFont = new Font(bfChinese,11, Font.NORMAL); //正常
        //Font redTextFont = new Font(bfChinese,11,Font.NORMAL,Color.RED); //正常,红色
        Font boldFont = new Font(bfChinese,11,Font.BOLD); //加粗
        //Font redBoldFont = new Font(bfChinese,11,Font.BOLD,Color.RED); //加粗,红色
        Font firsetTitleFont = new Font(bfChinese,22,Font.BOLD); //一级标题
        Font secondTitleFont = new Font(bfChinese,15,Font.BOLD, CMYKColor.BLUE); //二级标题
        Font underlineFont = new Font(bfChinese,11,Font.UNDERLINE); //下划线斜体
        //设置字体
        com.itextpdf.text.Font FontChinese24 = new com.itextpdf.text.Font(bfChinese, 24, com.itextpdf.text.Font.BOLD);
        com.itextpdf.text.Font FontChinese18 = new com.itextpdf.text.Font(bfChinese, 18, com.itextpdf.text.Font.BOLD);
        com.itextpdf.text.Font FontChinese16 = new com.itextpdf.text.Font(bfChinese, 16, com.itextpdf.text.Font.BOLD);
        com.itextpdf.text.Font FontChinese12 = new com.itextpdf.text.Font(bfChinese, 12, com.itextpdf.text.Font.NORMAL);
        com.itextpdf.text.Font FontChinese11Bold = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.BOLD);
        com.itextpdf.text.Font FontChinese11 = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.ITALIC);
        com.itextpdf.text.Font FontChinese11Normal = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.NORMAL);

        //设置要导出的pdf的标题
        String title = "霸道流氓气质";
        response.setHeader("Content-disposition","attachment; filename=".concat(String.valueOf(URLEncoder.encode(title + ".pdf", "UTF-8"))));
        OutputStream out = response.getOutputStream();
        PdfWriter.getInstance(doc,out);
        doc.open();
        doc.newPage();
        //新建段落
        //使用二级标题 颜色为蓝色
        Paragraph   p1 = new Paragraph("二级标题", secondTitleFont);
        //设置行高
        p1.setLeading(0);
        //设置标题居中
        p1.setAlignment(Element.ALIGN_CENTER);
        //将段落添加到文档上
        doc.add(p1);
        //设置一个空的段落,行高为18  什么内容都不显示
        Paragraph blankRow1 = new Paragraph(18f, " ", FontChinese11);
        doc.add(blankRow1);
        //新建表格 列数为2
        PdfPTable table1 = new PdfPTable(2);
        //给表格设置宽度
        int width1[] = {80,60};
        table1.setWidths(width1);
        //新建单元格
        String name="霸道";
        String gender="男";
        //给单元格赋值 每个单元格为一个段落,每个段落的字体为加粗
        PdfPCell cell11 = new PdfPCell(new Paragraph("姓名:  "+name,boldFont));
        PdfPCell cell12 = new PdfPCell(new Paragraph("性别:  "+gender,boldFont));
        //设置单元格边框为0
        cell11.setBorder(0);
        cell12.setBorder(0);
        table1.addCell(cell11);
        table1.addCell(cell12);
        doc.add(table1);
        PdfPTable table3 = new PdfPTable(2);
        table3.setWidths(width1);
        PdfPCell cell15 = new PdfPCell(new Paragraph("博客主页: https://me.csdn.net/BADAO_LIUMANG_QIZHI  ",boldFont));
        PdfPCell cell16 = new PdfPCell(new Paragraph("当前时间:  "+DateConvert.formatDateToString(new Date(),DateStyle.YYYY_MM_DD),boldFont));
        cell15.setBorder(0);
        cell16.setBorder(0);
        table3.addCell(cell15);
        table3.addCell(cell16);
        doc.add(table3);
        doc.close();
    }

效果

点击按钮

打开PDF

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/89475877
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-26 22:07:03
  • 阅读 ( 946 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢