IText导出pdf

1.加入依赖

<dependency>

    <groupId>com.itextpdf</groupId>

    <artifactId>itextpdf</artifactId>

    <version>5.0.6</version>

</dependency>

 <dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itext-asian</artifactId>
     <version>5.2.0</version>
 </dependency>

2.示例

@RequestMapping(value = "/downloadDiploma")
    public void downloadDiploma(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //创建文档对象,A4纸大小
        Document document = new Document(PageSize.A4);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            PdfWriter.getInstance(document, stream);
            document.open();
            //解决中文乱码问题,仅适用windows系统
            BaseFont baseFont = BaseFont.createFont("c:/windows/fonts/simkai.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            Font font = new Font(baseFont);
            PdfPTable table = new PdfPTable(2);    //创建2列的表格    
            PdfPCell cell1=new PdfPCell(new Paragraph("党课主题",font));//创建单元格
            cell1.setFixedHeight(25);//设置行高
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
            cell1.setBackgroundColor(new BaseColor(250, 250, 250));//背景色
            cell1.setColspan(2);//合并单元格
            table.addCell(cell1);            
            document.add(table,font);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置响应文档类型为pdf
        response.setContentType("application/pdf");
        //设置响应数据大小
        response.setContentLength(stream.size());
        String fname="会议记录.pdf";
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("gb2312"), "ISO8859-1"));//设置导出pdf文件的名称
        //获取响应数据流
        ServletOutputStream out = response.getOutputStream();
        //将pdf数据流写入响应数据流中
        stream.writeTo(out);
        out.flush();
        out.close();
    }
}

3.Linux系统下解决中文乱码问题:

使用资源字体(ClassPath)  注意资源文件在打包的时候需要忽略,不可以编译

String path =this.getClass().getResource("/").getPath() + "SIMKAI.TTF";

BaseFont baseFont = BaseFont.createFont(path,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);  

4.样式结果

5.参考地址:https://www.cnblogs.com/chenpi/p/5534595.html#_label1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值