zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    SCP 命令
    linux下IPTABLES配置详解
    Linux rpm 命令参数使用详解
    Linux(Centos7)yum安装最新redis
    YUM常用命令介绍
    Centos7下Yum安装PHP5.5,5.6,7.0
    腾讯云CentOS7.0使用yum安装mysql
    如何在CentOS 6.5上升级PHP
    第一个Python程序
    Python简介及环境部署
  • 原文地址:https://www.cnblogs.com/je-ge/p/6287017.html
Copyright © 2011-2022 走看看