pdf插入数据并下载

来源:互联网 发布:淘宝韩式褶皱斑马帘 编辑:程序博客网 时间:2024/06/01 20:56

首先需要一个pdf模板,Adobe Acrobat 9 Pro里的表单插入文本域即可。

然后是导出pdf工具类

import com.itextpdf.text.DocumentException;import com.itextpdf.text.pdf.AcroFields;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.PdfStamper;/** *  * 导出pdf工具类<br> * 导出pdf工具类 *  */public class ExportPdfUtil {    /*     * 日志     */    static Logger logger = LoggerFactory.getLogger(ExportPdfUtil.class);    /**     *      * 导出pdf工具类 <br>     * 导出pdf工具类     *      * @param outpath     * @param fontPath     * @param templateName     * @param paraMap     * @return     * @see [相关类/方法](可选)     */    public static String exportpdf(String outpath, String templateName, String fontPath, Map<String, String> paraMap,String pdfPath) {               // 得到当前时间        Date now = new Date();        SimpleDateFormat dataformat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");        String t = dataformat.format(now);        // 得到一个随机数        String ran = Math.random() + "";        // 以当前时间加上一个随机数获取下载的文件以保证不重名        String filename = t + "-" + ran;        // 定义pdf完整路径//        String url = Pdf2SwfUtil.class.getResource("Pdf2SwfUtil.class").getFile().toString();//        logger.debug("[exportpdf] class URL = "+url);//        String address = url.substring(CommonConstants.NumeralConstant.ZERO,//                url.lastIndexOf("Pdf2SwfUtil"))+"pdf/"+templateName;//        logger.debug("[exportpdf] address URL = "+address);        String address = pdfPath  + templateName;                        String savepath = outpath + File.separator + filename + ".pdf";        logger.debug("[exportpdf] savepath URL = "+savepath);        PdfReader reader = null;        ByteArrayOutputStream bos = null;        PdfStamper ps = null;        FileOutputStream fos = null;        try {            // 创建字体            BaseFont chineseSong = BaseFont.createFont(fontPath + "/simsun.ttc,1", BaseFont.IDENTITY_H,                    BaseFont.EMBEDDED);                        // 读取pdf            reader = new PdfReader(address);            bos = new ByteArrayOutputStream();            ps = new PdfStamper(reader, bos);            AcroFields s = ps.getAcroFields();            // 添加所创建的字体            s.addSubstitutionFont(chineseSong);            //找到pdf中输入域并替换为内容            int i = 1;            for (Iterator<String> it = s.getFields().keySet().iterator(); it.hasNext(); i++) {                String name = (String) it.next();                s.setField("" + name.trim(), paraMap.get(name.trim()));            }            //这两步必须有,否则pdf生成失败            ps.setFormFlattening(true);            ps.close();            //输出pdf            fos = new FileOutputStream(savepath);            fos.write(bos.toByteArray());        } catch (FileNotFoundException e) {            logger.error("FileNotFoundException");        } catch (Exception e) {            logger.error("Exception");        } finally {            if (null != reader) {                reader.close();            }            try {                if (null != bos) {                    bos.close();                }            } catch (IOException e) {                logger.debug("failed to close ByteArrayOutputStream ");                logger.debug("关闭ByteArrayOutputStream失败", e);            }            try {                if (null != ps) {                    ps.close();                }            } catch (DocumentException e) {                logger.debug("failed to close PdfStamper ");                logger.debug("关闭PdfStamper失败", e);            } catch (IOException e) {                logger.debug("failed to close PdfStamper ");                logger.debug("关闭PdfStamper失败", e);            }            try {                if (null != fos) {                    fos.close();                }            } catch (IOException e) {                logger.debug("failed to close FileOutputStream ");                logger.debug("关闭FileOutputStream失败", e);            }        }        return filename;    }            }

下载操作公共类

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** *  * 下载操作公共类 *  *  */public class DownLoadUtil {    /**     * 日志打印     */    private static Logger logger = LoggerFactory.getLogger(DownLoadUtil.class);    /**     *      * 下载: <br>     *      * @param savePath     * @param filename     * @param response     * @see     * @since 3.3     */    public static void download(String savePath, String filename, boolean deleteFlag, HttpServletResponse response) {        File f = new File(savePath);        if (f.exists()) {            // 设置response的相应消息头            response.setContentType("application/pdf");            response.setIntHeader("Expires", 0);            response.setHeader("Pragma", "public");            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");            response.addHeader("Cache-Control", "public");            FileInputStream in = null;            try {                String newFilename = new String(filename.getBytes("gbk"), "iso8859-1");                response.setHeader("Content-Disposition", "attachment;filename=" + newFilename);                // 创建一 个输入流对象和指定的文件相关联                in = new FileInputStream(f);                OutputStream out = response.getOutputStream();                byte[] buff = new byte[PdfAndFlashConstants.Common.THOUSAND];                int len = CommonContants.NumeralConstant.ZERO;                while ((len = in.read(buff)) > PdfAndFlashConstants.Common.ZERO) {                    out.write(buff, PdfAndFlashConstants.Common.ZERO, len);                }                out.flush();                out.close();            } catch (UnsupportedEncodingException e) {                logger.error("IO错误");            } catch (IOException e) {                logger.error("IO错误");            } finally {                try {                    if (in != null) {                        in.close();                    }                } catch (IOException e) {                    logger.error("关闭IO错误");                } finally {                    if (deleteFlag) {                        if (f.delete()) {                            logger.debug("删除成功");                        } else {                            logger.error("删除失败");                        }                    }                }            }        } else {            logger.error("文件不存在");        }    }}


controller层

  @RequestMapping("/getPdf")  public void getPdf(@RequestParam(value = "fncAplyId",required=false) String fncAplyId,HttpServletResponse response) {  SingleFinanceEntity bean = singleFinanceService.getBeanByFncAppyId(fncAplyId);      String pdfname = this.genaratePdf(bean);      String filename ="练习--"+bean.getFncAplyId()+".pdf";      WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();      ServletContext servletContext = webApplicationContext.getServletContext();      String pdfandflash = servletContext.getRealPath("js"+File.separator+"PDF") +File.separator;      DownLoadUtil.download(pdfandflash + File.separator + pdfname + ".pdf",              filename, true, response);  }    private Map<String, String> getMap(SingleFinanceEntity financeEntity){Map<String, String> map = new HashMap<String, String>();OpCompanyContractEntity contract = contractService.queryContractBy(financeEntity.getMainContractCode());map.put("id", financeEntity.getLoanNo());map.put("custName", financeEntity.getCustName());String validStartDate = contract.getValidStartDate();map.put("signYear", validStartDate.substring(0, 4));map.put("signMonth", validStartDate.substring(5, 7));map.put("signDay", validStartDate.substring(8, 10));map.put("parentCode", contract.getContractCode());DecimalFormat df = new DecimalFormat("###.##");map.put("lmoney", df.format(financeEntity.getAppLoanAmt()));map.put("umoney", MoneyUtil.numToChinese(financeEntity.getAppLoanAmt().toString()));SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String nowDate = formatter.format(financeEntity.getConfirmDate() == null ?new Date() : financeEntity.getConfirmDate());map.put("nowYear", nowDate.substring(0, 4));map.put("nowMonth", nowDate.substring(5, 7));map.put("nowDay", nowDate.substring(8, 10));map.put("forDay", financeEntity.getForbidPeriod());map.put("infoDay", financeEntity.getFncPd());map.put("fncRate", df.format(financeEntity.getFncAnnRt()));map.put("Rate", "0");map.put("flRate", "50");return map;}    public String genaratePdf(SingleFinanceEntity bean) {      Map<String, String> map = getMap(bean);      String templateName = "DBRZXY.pdf";      WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();      ServletContext servletContext = webApplicationContext.getServletContext();      // 得到文件绝对路径      String pdfandflash = servletContext.getRealPath("js"+File.separator+"PDF") +File.separator;      return ExportPdfUtil.exportpdf(pdfandflash, templateName, pdfandflash,              map,pdfandflash);  }

getmap也可以设置成String object。后期可优化