user Itext to marge pdf model

1,在controller中,对页面传入的值进行填充到模版中

/**
     * 1,验证登录信息webuserInfo
     * 2,判断用户名和企业名是否为"",并对用户名和企业名进行解码
     * 3,加载本地的PDF模版文件;设置文件名,并为中文文件名进行编码
     * 4,调用工具方法,进行模版内容的替换,
     * 5,清空响应对象,设置响应头
     * 设置响应头为指定的文件名,设置相应的编码类型,设置响应的类型为pdf文件
     * 6,调用输出流,将处理过后的byte数组输出
     * @throws IOException 
     * 
response.setContentType()的String参数及对应类型
<option   value="image/bmp">BMP</option>   
<option   value="image/gif">GIF</option>   
<option   value="image/jpeg">JPEG</option>   
<option   value="image/tiff">TIFF</option>   
<option   value="image/x-dcx">DCX</option>   
<option   value="image/x-pcx">PCX</option>   
<option   value="text/html">HTML</option>   
<option   value="text/plain">TXT</option>   
<option   value="text/xml">XML</option>   
<option   value="application/afp">AFP</option>   
<option   value="application/pdf">PDF</option>   
<option   value="application/rtf">RTF</option>   
<option   value="application/msword">MSWORD</option>   
<option   value="application/vnd.ms-excel">MSEXCEL</option>   
<option   value="application/vnd.ms-powerpoint">MSPOWERPOINT</option>   
<option   value="application/wordperfect5.1">WORDPERFECT</option>   
<option   value="application/vnd.lotus-wordpro">WORDPRO</option>   
<option   value="application/vnd.visio">VISIO</option>   
<option   value="application/vnd.framemaker">FRAMEMAKER</option>   
<option   value="application/vnd.lotus-1-2-3">LOTUS123</option>

     */

    @RequestMapping("/loadProxyPdf")
    public String loadProxyPdf(
            @RequestParam(value = "enterpriseName", required = true) String enterpriseName,
            @RequestParam(value = "realName", required = true) String realName,
            @RequestParam(value = "mPhone", required = true) String mPhone,
            @RequestParam(value = "email", required = true) String email,
            HttpSession session, HttpServletRequest request,
            HttpServletResponse response){
            UserInfo userInfo = (UserInfo) session.getAttribute("webuserInfo");
            if (null == userInfo) {
                return "redirect:ixinweb/denglu";
            }
            if (StringUtils.isNotBlank(enterpriseName)&&StringUtils.isNotBlank(realName)) {
                try {
                    enterpriseName = URLDecoder.decode(enterpriseName,"UTF-8");
                    realName = URLDecoder.decode(realName,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            InputStream is = null;
            OutputStream os = null;
            try{
                is = UserInfoWebController2.class.getClassLoader().getResourceAsStream("/porxy.pdf");
                String fileName = "授权书.pdf";
                fileName = encodeFilename(fileName, request);
                byte[] b = PDFUtils2.readPDF(is, enterpriseName, realName, mPhone, email).toByteArray();
                response.reset();
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-disposition", "attachment;filename="
                        + fileName);
                response.setContentType("application/pdf");
                os = response.getOutputStream();
                os.write(b);
                os.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        return null;
    }


    public String encodeFilename(String filename, HttpServletRequest request){
        /**
         * 获取客户端浏览器和操作系统信息 在IE浏览器中得到的是:User-Agent=Mozilla/4.0 (compatible; MSIE
         * 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
         * 在Firefox中得到的是:User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1;
         * zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
         */
        //1,获取用户的浏览器
        String agent = request.getHeader("User-Agent");
        String newFileName="";
        try {
            if (null!=agent&&(-1 != agent.indexOf("Trident"))) {
                newFileName = URLEncoder.encode(filename, "UTF-8");
                if(filename.length()>150)//解决IE 6.0 bug
                    newFileName=new String(filename.getBytes("GBK"),"ISO-8859-1");
                return newFileName;
            }
            if (null!=agent && (-1 != agent.indexOf("Mozilla"))) {
                return MimeUtility.encodeText(filename, "UTF-8", "B");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

2,编写PDF工具类,实现内容的替换



import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class PDFUtils2 {


    /**
     * 编程思路:
     * 获取pdf模版的输入流,对模版的可编辑区域进行填充和替换
     * 1,创建PdfReader(inputstream)
     * 2, BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); 
     * 3,创建PdfStamper和AcroFields
     * ByteArrayOutputStream out = new ByteArrayOutputStream();  
            PdfStamper stamp = new PdfStamper(PdfReader, outputstream);  
            AcroFields form = PdfStamper.getAcroFields();
            4,对表单可编辑区域进行填充 
     * form.setFieldProperty(key, "textfont", bfChinese, null);  
     * 5对表单内容进行替换
                form.setField(key, value); 
     * 参考:http://blog.csdn.net/polo_longsan/article/details/39254867
     * 
     * 表单模版中设置了可编辑区域的名称,所以要按名称去对应上对应的区域
     */
    public static ByteArrayOutputStream readPDF(InputStream is,
            String enterpriseName, String realName, String mPhone, String email)
            throws Exception{
        PdfReader pdfReader = new PdfReader(is);
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(pdfReader, out);
        AcroFields form = stamper.getAcroFields();
        //对可编辑区域进行内容填充
        form.setFieldProperty("enterpriseName", "textfont", bfChinese, null);
        form.setFieldProperty("realName", "textfont", bfChinese, null);
        form.setFieldProperty("mPhone", "textfont", bfChinese, null);
        form.setFieldProperty("email", "textfont", bfChinese, null);
        form.setFieldProperty("nowdate", "textfont", bfChinese, null);
        //
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        form.setField("enterpriseName", enterpriseName);
        form.setField("realName", realName);
        form.setField("mPhone", mPhone);
        form.setField("email", email);
        form.setField("nowdate", simpleDateFormat.format(new Date()));
        stamper.setFormFlattening(true);  
        stamper.close();  
        pdfReader.close(); 
        return out;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值