pdf模板生成与响应下载 + SpringBoot + itextpdf

1.制作PDF模板


   1)新建Word文档

 安装Adobe Acrobat DC
链接: https://pan.baidu.com/s/1sNGZhAFVPv-ufp6gGWg6Sw 提取码: 4dxh

2)新建的Word 通过软件转成PDF格式。

3)制备菜单

2.pom 添加依赖

<!-- pdf -->

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

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

3创建PDF工具类 PdfUtils

public class PdfUtils {

    public static PdfUtils getUtil(){
        return new PdfUtils();
    }

    /**
     * @param data         数据源
     * @param templatePath 模板路径
     */
    public void createPdf(Map<String, String> data, String templatePath,String  inputFileName,String outputFileName,HttpServletResponse response) throws IOException {

        //2.根据模板填充数据源
        ByteArrayOutputStream pdf = createPdfStream(templatePath, inputFileName, data);

        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition",
                "attachment;filename="+new String( outputFileName.getBytes("utf-8"),
                        "ISO8859-1" )+".pdf");
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        OutputStream out = response.getOutputStream();
        out.write(pdf.toByteArray());
        out.flush();
        out.close();
        pdf.close();
    }

    /**
     * 根据pdf模板输出流
     * @param templateFilePath
     * @param templateFileName
     * @param resultMap
     * @return
     */
    public static ByteArrayOutputStream createPdfStream(String templateFilePath, String templateFileName,
                                                        Map<String, String> resultMap) {

        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {



            PdfReader reader = new PdfReader(templateFilePath + File.separator + templateFileName);
            PdfStamper stamp = new PdfStamper(reader, ba);

            //使用字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            /* 获取模版中的字段 */
            AcroFields form = stamp.getAcroFields();

            //填充表单
            if (resultMap != null) {
                for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                    form.setFieldProperty(entry.getKey(), "textfont", bf, null);
                    form.setField(entry.getKey(), entry.getValue());
                }
            }

            stamp.setFormFlattening(true);//不能编辑
            stamp.close();

            reader.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (DocumentException documentException) {
            documentException.printStackTrace();
        }
        return ba;
    }

4.数据填充

/**
 * 合同下载
 * @param collectId
 * @param response
 */
public void generateContract(String collectId, HttpServletResponse response) throws SoaException, IOException {

    Map<String,String> map = Maps.newHashMap();
    // todo  查询数据 key就是PDF模板菜单的字段名,value为填充的值

    PdfUtils.getUtil().createPdf(map,"pdf","合同.pdf","合同",response);

}

5.controller 调用,就能直接填充下载到页面了。

 

@RequestMapping(value = "/download",method = RequestMethod.GET)
@ApiOperation(value = "[ZS]合同下载 -- 合同下载", notes = "作者JOKER")
@JwtIgnore
public BaseResult<?> download(String id,HttpServletResponse response) throws SoaException, IOException {

    try {
        pdfServiceDto.generateContract(id,response);

        return BaseResult.success("成功!");
    }
    catch (SoaException e) {
        if (e.getCode() > 10000){
            return new BaseResult(e.getCode(),e.getMessage());
        }
        return BaseResult.failure("合同下载失败!");
    }

}

文章部分来自于网络,自己稍加整改,不喜勿喷,三口。

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值