使用itext生成pdf

项目背景

项目中需要打印标签信息,格式固定,每页的行数,列数都固定,开始打算使用 html 设计页面然后进行打印,但 html 页面比较麻烦,而且对浏览器兼容方面要求较高,所以最后决定使用 itext 生成 pdf 的方式。然后将 pdf 转成流输出到浏览器中。

步骤

    // 创建一个有4列的表格  
    PdfPTable table = new PdfPTable(3);
    table.setTotalWidth(new float[]{ 200, 200, 200}); //设置列宽
    table.setLockedWidth(true); //锁定列宽
    
    for(int i=0;i<3;i++){
        for(int j=0;j<8;j++){
            PdfPCell cell;
            cell = new PdfPCell(p1);
            cell.setBorderWidthLeft(3);
            cell.setBorderWidthTop(3);
            cell.setBorderWidth(0);
            cell.setBorder(0);
            cell.setPaddingLeft(35);
            cell.setPaddingRight(35);
            cell.setMinimumHeight(95); //设置单元格高度
            cell.setUseAscender(true); //设置可以居中
            cell.setHorizontalAlignment(PdfPCell.LEFT); //设置水平居中
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); //设置垂直居中
            table.addCell(cell);
        }
    }
    doc.add(table);//将table加入到pdf中
    doc.close();
    return outPath;
    }    
}    

3.将 pdf 转成流输出到浏览器,后台调用上面的方法

    public void exportPdf() {
    try {
        String pdfPath = PDFUtil.createPDF();//获取pdf路径
        HttpServletResponse response = this.getResponse();
        response.setContentType("application/pdf");  
        ServletOutputStream sos = response.getOutputStream();  
        File pdf = null;  
        //response.setHeader("Content-disposition",                              "attachment;filename=laallal.pdf");//直接下载到本地
        FileInputStream fis = null;  
        byte[] buffer = new byte[1024*1024];  
        pdf = new File(pdfPath);  
        response.setContentLength((int) pdf.length());  
        fis = new FileInputStream(pdf);  
        int readBytes = -1;  
        while((readBytes = fis.read(buffer, 0, 1024*1024)) != -1){  
            sos.write(buffer, 0, 1024*1024);  
        }  
        sos.close();  
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    renderNull();
}    

效果展示

结果展示

总结

这个过程中主要需要注意 jar 版本,然后具体生成的内容就可以自己查看 itext 的 api 进行个性化设置。

转载于:https://my.oschina.net/u/1581846/blog/1586668

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值