Java导出完整版模板(pdf)

1.在pom引入jra包

<!--itext的jar包   生成pdf   兼容linux  windows-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.4.1</version>
</dependency>

2.导出模板(util文件)

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class SSWToPdf extends PdfPageEventHelper {

    public void createOutsourcingAuditBillsPDF(String billMonth, List<LinkedHashMap<String, Object>> taskStatusList, String pdfPath, String fileName) throws Exception {
        // 1.新建document对象
        Document document = new Document(PageSize.A4, 0, 0, 60, 50);
        File pdfFile = new File(pdfPath);
        if (!pdfFile.exists()) {
            pdfFile.mkdirs();
        }

        // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
        // 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath + fileName));
        //设置字体
        BaseFont bfChinese1 = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese10Color = new Font(bfChinese1, 10, Font.NORMAL, new BaseColor(231, 24, 55));
        Font FontChinese10Normal = new Font(bfChinese1, 10, Font.NORMAL);
        //writer.setPageEvent(new PdfPageHelper("外包供应商月度账单","外包审计账单",billMonth));
        // 3.打开文档
        document.open();

        PdfPTable table = new PdfPTable(7);
        table.setWidths(new int[]{12, 14, 15, 15, 15, 15, 14});
        table.setTotalWidth(560);//设置绝对宽度
        table.setLockedWidth(true);//使绝对宽度模式生效

        PdfPCell cell11 = new PdfPCell(new Paragraph("列名1", FontChinese10Normal));
        PdfPCell cell12 = new PdfPCell(new Paragraph("列名2", FontChinese10Normal));
        PdfPCell cell13 = new PdfPCell(new Paragraph("列名3", FontChinese10Normal));
        PdfPCell cell14 = new PdfPCell(new Paragraph("列名4", FontChinese10Normal));
        PdfPCell cell15 = new PdfPCell(new Paragraph("列名5", FontChinese10Normal));
        PdfPCell cell16 = new PdfPCell(new Paragraph("列名6", FontChinese10Normal));
        PdfPCell cell17 = new PdfPCell(new Paragraph("列名7", FontChinese10Normal));
        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell11.setBackgroundColor(new BaseColor(102, 102, 102));
        cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell12.setBackgroundColor(new BaseColor(102, 102, 102));
        cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell13.setBackgroundColor(new BaseColor(102, 102, 102));
        cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell14.setBackgroundColor(new BaseColor(102, 102, 102));
        cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell15.setBackgroundColor(new BaseColor(102, 102, 102));
        cell16.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell16.setBackgroundColor(new BaseColor(102, 102, 102));
        cell17.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell17.setBackgroundColor(new BaseColor(102, 102, 102));
        table.addCell(cell11);
        table.addCell(cell12);
        table.addCell(cell13);
        table.addCell(cell14);
        table.addCell(cell15);
        table.addCell(cell16);
        table.addCell(cell17);

        for (int i = 0; i < taskStatusList.size(); i++) {
            PdfPCell pdfPCell1 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column1")), FontChinese10Normal));
            PdfPCell pdfPCell2 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column2")), FontChinese10Normal));
            PdfPCell pdfPCell3 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column3")), FontChinese10Normal));
            PdfPCell pdfPCell4 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column4")), FontChinese10Normal));
            PdfPCell pdfPCell5 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column5")), FontChinese10Normal));
            PdfPCell pdfPCell6 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column6")), FontChinese10Normal));
            PdfPCell pdfPCell7 = new PdfPCell(new Paragraph(String.valueOf(taskStatusList.get(i).get("column7")), FontChinese10Normal));
            pdfPCell1.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell2.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell3.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell4.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell5.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell6.setBackgroundColor(new BaseColor(230, 230, 230));
            pdfPCell7.setBackgroundColor(new BaseColor(230, 230, 230));
            table.addCell(pdfPCell1);
            table.addCell(pdfPCell2);
            table.addCell(pdfPCell3);
            table.addCell(pdfPCell4);
            table.addCell(pdfPCell5);
            table.addCell(pdfPCell6);
            table.addCell(pdfPCell7);
        }

        PdfPCell cell21 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell22 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell23 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell24 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell25 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell26 = new PdfPCell(new Paragraph(" "));
        PdfPCell cell27 = new PdfPCell(new Paragraph(" "));
        new SSWToPdf2().showBorder(cell21, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell22, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell23, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell24, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell25, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell26, 0, 0, 0, 0);
        new SSWToPdf2().showBorder(cell27, 0, 0, 0, 0);
        table.addCell(cell21);
        table.addCell(cell22);
        table.addCell(cell23);
        table.addCell(cell24);
        table.addCell(cell25);
        table.addCell(cell26);
        table.addCell(cell27);

        document.add(table);
        // 5.关闭文档
        document.close();
    }

    //单元格边框显示隐藏
    public PdfPCell showBorder(PdfPCell pdfPCell, int a, int b, int c, int d) {
        if (a == 0) {
            pdfPCell.setBorderWidthTop(0);
        }
        if (b == 0) {
            pdfPCell.setBorderWidthBottom(0);
        }
        if (c == 0) {
            pdfPCell.setBorderWidthLeft(0);
        }
        if (d == 0) {
            pdfPCell.setBorderWidthRight(0);
        }
        return pdfPCell;
    }
}

3.service

// 导出PDF
public Object PDFOutsourcingAuditBills(String billMonth,String companyId) throws Exception {
    Map resultMap = new HashedMap();
    String billId = mapper.getBillId(billMonth,companyId);
    List<LinkedHashMap<String, Object>> taskStatusList = new ArrayList<>();
    if(null != billId){
        taskStatusList = beOutbillDescMapper.getOutsourcingAuditBills(billId);// 得到要展示的值
    }
    String fileName =  "表名"  + new Date().getTime() + ".pdf";
    new SSWToPdf().createOutsourcingAuditBillsPDF(billMonth, taskStatusList, pdfPath, fileName);//调导出的方法
    resultMap.put("code", "1");
    resultMap.put("fileName", fileName);
    resultMap.put("filePath", pdfPath);
    resultMap.put("msg", "查询成功");
    return resultMap;
}
// 校验文件路径是否存在
public Object checkPath(String fileName,String path) throws  Exception{
    File file = new File(path+fileName);
    if(!file.exists()){
        return "false";
    }else{
        return "true";
    }
}
//下载文件
public void download(HttpServletRequest request, HttpServletResponse response) {
        String agent = request.getHeader("User-Agent");
        boolean isMSIE = ((agent != null && agent.indexOf("MSIE") != -1) || (null != agent && -1 != agent.indexOf("like Gecko")));
        String filePath = request.getParameter("filePath");
        String fileName = request.getParameter("fileName");
        String responseFileName = "";
        try {
            if (isMSIE) {
                responseFileName = URLEncoder.encode(fileName, "UTF-8");
                fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                responseFileName = new String(fileName.getBytes(), "ISO-8859-1");
            }
        } catch (Exception e) {
            log.error("" + e);
        }
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setContentType("text/html");
        response.setHeader("Content-Disposition", "attachment;filename=" + responseFileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filePath + fileName)));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("" + e);
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                response.flushBuffer();
                // 删除指定文件
                File file = new File(filePath + fileName);
                if (file.exists() && file.isFile()) {
                    //file.delete();//避免删除模板
                }
            } catch (IOException e) {
                log.error("" + e);
            }
        }
    }

4.controller

// 导出PDF
@GetMapping("/export/exportFile/PDFOutsourcingAuditBills")
public Object PDFOutsourcingAuditBills(String billMonth,String companyId)throws Exception{
    return service.PDFOutsourcingAuditBills(billMonth,companyId);
}
// 校验文件路径是否存在
@GetMapping("/checkPath")
public Object checkPath(String fileName,String path){
    try{
        return ResultUtil.resultMsg("200","OK",service.checkPath(fileName,path));
    }catch (Exception e){
        log.error("selectTaskOne:{}",e);
        return ResultUtil.resultMsg(ErrorCode.HAS_EXCEPRION.getValue(),
                ErrorCode.HAS_EXCEPRION.getDesc());
    }
}
//下载模板数据
@GetMapping("/download")
public void download(HttpServletRequest request,HttpServletResponse res) {
    excleService.download(request,res);
}

5.前端调用导出

$.ajax({
    url: getApi() + 'report/export/exportFile/PDFOutsourcingAuditBills',
    type: "get",
    contentType: 'application/json;charset=utf-8',
    dataType: "json",
    data:{
        billMonth: billMonth,
        companyId: companyId
    },
    success: function(response) {
        if (result.code == "1") {
            var fileName = result.fileName;
            var filePath = result.filePath;
            checkPath(fileName, filePath);
        } else {
            layer.msg(result.msg);
        }
    },
    error: function(res) {
    }
});
// 打开文件
checkPath: function (fileName, path) {
    $.ajax({
        url: getApi() + 'Tool/checkPath',
        type: "get",
        contentType: 'application/json;charset=utf-8',
        dataType: "json",
        data: {
            fileName: fileName,
            path: path
        },
        success: function (response) {
            if (data.code == "200") {
                if (data.data == "false") {
                    layer.msg("文件不存在");
                } else {
                    methods.download(fileName, path);
                }
            }
        },
        error: function (res) {
        }
    });
},
// 下载文件
download: function (fileName, path) {
    var url = getApi() + 'excel/download';
    var form = $("<form>");
    $('body').append(form);
    form.attr('style', 'display:none');
    form.attr('target', '');
    form.attr('method', 'get');
    form.attr('action', url);//下载文件的请求路径
    var input1 = $('<input>');
    input1.attr('type', 'hidden');
    input1.attr('name', 'filePath');
    input1.attr('value', path);
    form.append(input1);
    var input2 = $('<input>');
    input2.attr('type', 'hidden');
    input2.attr('name', 'fileName');
    input2.attr('value', fileName);
    form.append(input2);
    form.submit();
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值