zoukankan      html  css  js  c++  java
  • springMVC(3)---利用pdf模板下载

    springMVC(3)---利用pdf模板下载

           

              在实际开发中,很多时候需要通过把数据库中的数据添加到pdf模板中,然后供客户下载,那我们该如何中呢?

               本文主要内容是:用java在pdf模板中加入数据,图片

                直接举例:

             

     第一步,对pdf模板添加文本域                   

             使用Adobe Acrobat  Pro软件,选择表单,就可以添加文本域很简单。这里也可以设置字体大小,是否换行等

           

    第二步、pom文件导入相关jar包                           

     <!--  注意:我一开始把这个放到pom.xml文件中,发现报错了,原因是我的本地mevan库中没有5.5.10版的,只有5.1.1和5.1.3于是我在网上下了个,再放到本地库,更新下项目就可以了 -->
     <!-- itext 图片转pdf -->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.10</version>
            </dependency>

     第三步,把pdf和照片素材放到项目中                      

          这里我在resources下面新建了pdf文件夹,放到这里面          

     

    第四步、PdfController.java                              

    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.itextpdf.text.Image;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.AcroFields;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.PdfContentByte;
    import com.itextpdf.text.pdf.PdfReader;
    import com.itextpdf.text.pdf.PdfStamper;
    
    @Controller
    @RequestMapping("/jsp/exportpdf")
    public class PdfController {
    
        @RequestMapping
        public String pdfexport(HttpServletResponse response) {
            // 指定解析器
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                    "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
    
            String filename = "resume.pdf";
    
            response.setContentType("application/pdf");
            try {
    //设置文件头:最后一个参数是设置下载文件名(这里我们叫:个人简历.pdf) response.setHeader(
    "Content-Disposition", "attachment;fileName=" + URLEncoder.encode("个人简历.pdf", "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } OutputStream os = null; PdfStamper ps = null; PdfReader reader = null; try { os = response.getOutputStream(); // 生成的新文件路径 ,这里指页面 /** * class.getResource("/") --> 返回class文件所在的顶级目录,一般为包名的顶级目录 * 在这个目录中src/main/java和src/main/resources和src/test/java都是属于顶级目录 * 这里pdf/就属于顶级目录下的子目录了 * */ // 2 读入pdf表单 reader = new PdfReader(PdfController.class.getResource("/pdf/") + "resume.pdf"); // 3 根据表单生成一个新的pdf ps = new PdfStamper(reader, os); // 4 获取pdf表单中所有字段 AcroFields form = ps.getAcroFields(); // 5给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示 BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); form.addSubstitutionFont(bf); // 6查询数据 Map<String, Object> data = new HashMap<String, Object>(); data.put("xh", "1021229"); data.put("xm", "徐小筱"); // 7遍历data 给pdf表单表格赋值 for (String key : data.keySet()) { form.setFieldProperty(key, "textfont", bf, null);// 设置字体 form.setField(key, data.get(key).toString()); } // 如果为false那么生成的PDF文件还能编辑,一定要设为true ps.setFormFlattening(true); //添加图片: 通过域名获取所在页和坐标,左下角为起点 int pageNo = form.getFieldPositions("zp").get(0).page; Rectangle signRect = form.getFieldPositions("zp").get(0).position; float x = signRect.getLeft(); float y = signRect.getBottom(); // 读图片 String imgpath = PdfController.class.getResource("/pdf/") + "zhaopian.jpg"; Image image = Image.getInstance(imgpath); // 获取操作的页面 PdfContentByte under = ps.getOverContent(pageNo); // 根据域的大小缩放图片 image.scaleToFit(signRect.getWidth(), signRect.getHeight()); // 添加图片 image.setAbsolutePosition(x, y); under.addImage(image); System.out.println("===============PDF导出成功============="); } catch (Exception e) { System.out.println("===============PDF导出失败============="); e.printStackTrace(); } finally { try { ps.close(); reader.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } }

     第五步、jsp文件映射到Controller层           

             只要点击下载,文件就自动下载了

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html>
    <body>
    <form action="exportpdf">
            <input type="submit" value="下载">
        </form>
    </body>
    </html>

      最终结果:完美!

     想的太多,做的太少,中间的落差就是烦恼,要么去做,要么别想 少尉【10】

  • 相关阅读:
    Ext.grid.行相关
    FORM 布局
    rs.open sql,conn,1,1全接触
    arguments.callee
    Ext.window.MessageBox xtype: messagebox ; Ext.Msg Ext.MessageBox
    Ext.grid.column
    sql
    正则
    转JS
    quickFilters
  • 原文地址:https://www.cnblogs.com/qdhxhz/p/8127206.html
Copyright © 2011-2022 走看看