使用 Itext 生成PDF字节数组输出流(文件流不落地)并在Servlet进行下载

一、生成PDF,所需jar包(itext-2.0.8.jar,iTextAsian.jar)


    /**
     * 生成PDF
     * @author momo
     * @since 2018-8-6
     * @return 字节数组输出流转成的字符串
     */
    public String generatePDF() {
        byte[] result=null;
        ByteArrayOutputStream baos = null;
        Document doc =null;

        try {

            Rectangle rectPageSize = new Rectangle(PageSize.A4);
            doc = new Document(rectPageSize);// 可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距

            baos = new ByteArrayOutputStream();//构建字节输出流
            PdfWriter.getInstance(doc,baos);//将PDF文档对象写入到流

            doc.open();  


            // 解决中文问题  
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  



            //第一页
            Font titleFont = new Font(bfChinese, 26, Font.BOLD);  
            Paragraph title = new Paragraph("通知书", titleFont);  
            title.setAlignment(Element.ALIGN_CENTER);//居中
            doc.add(title);


            Font smallTitleFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph smallTitle = new Paragraph("通 〔A123〕 号", smallTitleFont);  
            smallTitle.setAlignment(Element.ALIGN_CENTER);//居中
            smallTitle. setLeading(40f);
            doc.add(smallTitle);


            //换空行
            Font enterpriseFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph enterprise = new Paragraph("", enterpriseFont); 
            enterprise. setLeading(60f);
            doc.add(enterprise);


            Chunk qymc = new Chunk(" FDSAFASDFA ", enterpriseFont);
            qymc.setTextRise(1); // 上浮
            qymc.setUnderline(0.2f, -2f); // 下划线
            doc.add(qymc);

            Chunk nsrsbh = new Chunk(":12312421421)", enterpriseFont);
            doc.add(nsrsbh);


            Font syFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph sy = new Paragraph("事由: ", syFont);  
            sy.setIndentationLeft(24);// 左缩进
            sy. setLeading(30f);
            doc.add(sy);

            Font yjFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph yj = new Paragraph("依据: ", yjFont);  
            yj.setIndentationLeft(24);// 左缩进
            //yj. setLeading(30f);
            doc.add(yj);

            Font tznrFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph tznr = new Paragraph("通知内容: ",tznrFont);  
            tznr.setIndentationLeft(24);// 左缩进
            //tznr. setLeading(30f);
            doc.add(tznr);


            Font qzFont = new Font(bfChinese, 15, Font.NORMAL); 
            Paragraph qz = new Paragraph("(签章)", qzFont);  
            qz.setIndentationLeft(300);// 左缩进
            qz. setLeading(100f);
            doc.add(qz);



            //第二页
            //doc.setPageSize(rectPageSize.rotate());//定义是否横向显示
            doc.newPage(); 


            //信息数据表

            //创建PdfTable对象
            PdfPTable table=new PdfPTable(8);

            //设置各列的列宽
            table.setTotalWidth(new float[]{100,350,350});

            Font tableTitleFont=new Font(bfChinese,18,Font.BOLD);//表头
            Font tableTitle2Font=new Font(bfChinese,12,Font.BOLD);//表头2
            Font titleCellFont=new Font(bfChinese,12,Font.NORMAL);


            table.addCell(mergeRow("清单",tableTitleFont));//表头


            //表头2添加表格内容
            table.addCell(getPDFCell("序号",tableTitle2Font));
            table.addCell(getPDFCell("标题一",tableTitle2Font));
            table.addCell(getPDFCell("标题二",tableTitle2Font));
            table.addCell(getPDFCell("标题三",tableTitle2Font));


            //遍历数据集合进行添加
            for (int i = 0; i < dataList.size(); i++) {
                table.addCell(getPDFCell(i,tableTitle2Font));
                table.addCell(getPDFCell("数据一"+i,tableTitle2Font));
                table.addCell(getPDFCell("数据二"+i,tableTitle2Font));
                table.addCell(getPDFCell("数据三"+i,tableTitle2Font));
            }




            table.setWidthPercentage(110);//表宽度设置可不受页面边距影响
            doc.add(table);

            if(doc != null){
                doc.close();
            }

            String result =new String(baos.toByteArray(), "ISO-8859-1");//转字符串设置编码
            result = java.net.URLEncoder.encode(result, "ISO-8859-1");//如果跨域需设置编码


        }catch(Exception e) {
            log.error("PDF异常", e);
        }finally{
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    log.error("PDF异常", e);
                }
            }
        }

        return result;
    } 





  /**合并行的静态函数
   * 
   * @author momo
   * @since 2018-8-7
   * @param str
   * @param font
   * @return
   */
    public static PdfPCell mergeRow(String str,Font font) {

        //创建单元格对象,将内容及字体传入
        PdfPCell cell=new PdfPCell(new Paragraph(str,font));
        //设置单元格内容居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        //设置最小单元格高度
        cell.setMinimumHeight(40);

        //将该单元格所在列包括该单元格在内的8行单元格合并为一个单元格
        cell.setColspan(8);

        return cell;
    }


    /**
     * 获取指定内容与字体的单元格
     * 
     * @author momo
     * @since 2018-8-6
     * @param string
     * @param font
     * @return
     */
    public static PdfPCell getPDFCell(String string, Font font) {
        //创建单元格对象,将内容与字体放入段落中作为单元格内容
        PdfPCell cell=new PdfPCell(new Paragraph(string,font));

        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

        //设置最小单元格高度
        cell.setMinimumHeight(30);
        return cell;
    }

二、 Servlet下载

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

            String result= generatePDF();//生成PDF方法,返回字节数组文件流转成的字符串
            result = java.net.URLDecoder.decode(result, "ISO-8859-1");//如果跨域需设置解码

            ByteArrayInputStream inStream = new ByteArrayInputStream(
                            result.getBytes("ISO-8859-1"));
            // 设置输出的格式
            response.setContentType("bin");
            response.addHeader("Content-Disposition","attachment; filename=\"" + fileName+ ".zip\"");
            // 循环取出流中的数据
            byte[] b = new byte[2048];
            int len;
            try {

                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);

                inStream.close();
            } catch (IOException e) {
                        e.printStackTrace();
            }

    }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值