zoukankan      html  css  js  c++  java
  • java使用模板生成PDF

    一,用Adobe Acrobat pro软件制作模板

    (1)先用word做出模板界面

    (2)文件另存为pdf格式文件

    (3)通过Adobe Acrobat pro软件打开刚刚用word转换成的pdf文件

    (4)点击右边的"准备表单"按钮,没有请在更多里面找

    选择"xxx.pdf"选择开始(选择工具栏里面添加文本域,可以选择在任意位置添加你想要的文本域。在文本域属性框可以设置文本的属性,例如文本的名称、字体大小、位置等)

     

     

     

    (5)做完上面的工作后,直接"另存为"将pdf存储就可以

    到此模板就制作完成啦!接下来就开始写代码啦
    ————————————————

    public static void exportPdf(String templatePath,  Map<String, Object> data) {

    PdfReader reader = null;
    AcroFields s = null;
    PdfStamper ps = null;
    ByteArrayOutputStream bos = null;

    try {
    //设置字体
    String font = "src\main\resources\pdf\Microsoft-YaHei.ttf";
    reader = new PdfReader(templatePath);
    bos = new ByteArrayOutputStream();
    ps = new PdfStamper(reader, bos);
    s = ps.getAcroFields();
    //使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体,在模板文件中设置字体为中文字体 Adobe 宋体 std L
    BaseFont bfChinese = BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    //设置编码格式
    s.addSubstitutionFont(bfChinese);
    // 遍历data 给pdf表单表格赋值
    for (String key : data.keySet()) {
    if (data.get(key) != null) {
    String s1 = data.get(key).toString();
    s.setField(key, s1);
    }
    }
    // 如果为false那么生成的PDF文件还能编辑,一定要设为true
    ps.setFormFlattening(true);
    ps.close();

    HttpServletResponse response = ServletUtil.getResponse();
    response.setCharacterEncoding("UTF-8");
    response.setHeader("content-Type", "application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("car_bill.pdf", "UTF-8"));

    //用流写出
    try{
    /* 用流将数据写给前端 */
    OutputStream os = response.getOutputStream();
    os.write(bos.toByteArray());
    os.flush();
    os.close();
    }catch (IOException ioe){
    ioe.printStackTrace();
    }

    // 用文件流写出

    // String savePath = "文件保存路径";
    // FileOutputStream fos = new FileOutputStream(savePath);
    //
    // fos.write(bos.toByteArray());
    // fos.flush();
    // fos.close();


    } catch (IOException | DocumentException e) {
    log.error("读取文件异常");
    throw new HwBusinessException(BasicCode.ERROR, "生成PDF失败!");
    } finally {
    try {
    bos.close();
    reader.close();
    } catch (IOException e) {
    log.error("关闭流异常");
    e.printStackTrace();
    }
    }
    }


    参考链接:https://blog.csdn.net/qq_33624558/java/article/details/82891411

  • 相关阅读:
    Linux Kernel USB 子系统(1)
    折腾 Gnome3
    2011年06月08日
    xelatex 果然好用
    倍受打击
    长到40岁学到的41件事
    autocompletemode + flyspellmode
    The Linux Staging Tree, what it is and is not.
    如何选择开源许可证?
    Use emacs &amp; Graphviz to plot data structure
  • 原文地址:https://www.cnblogs.com/azoveh/p/13186982.html
Copyright © 2011-2022 走看看