Spring Boot 系列教程18-itext导出pdf下载

Java操作pdf框架

iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。

最终下载效果

这里写图片描述

pom.xml

<!-- itext方式导出pdf -->
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>4.2.2</version>
</dependency>

UserController.download方法

  • 简单的飞起
// 下载pdf文档
  @RequestMapping("/download")
  public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // 告诉浏览器用什么软件可以打开此文件
    response.setHeader("content-Type", "application/pdf");
    // 下载文件的默认名称
    response.setHeader("Content-Disposition", "attachment;filename=user.pdf");

    Document document = new Document();
    PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    List<User> list = userRepository.findAll();
    for (User user : list) {
      PdfPTable table = new PdfPTable(3);
      PdfPCell cell = new PdfPCell();
      cell.setPhrase(new Paragraph(user.getId().toString()));
      table.addCell(cell);
      document.add(table);

      cell = new PdfPCell();
      cell.setPhrase(new Paragraph(user.getName().toString()));
      table.addCell(cell);
      document.add(table);

      cell = new PdfPCell();
      cell.setPhrase(new Paragraph(user.getAge().toString()));
      table.addCell(cell);
      document.add(table);
    }
    document.close();
  }

其他关联项目

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值