JAVA中使用Springboot和Mybatis框架导出PDF文件

首先是POJO类,表示学生信息。假设学生有id、姓名(name)和年龄(age)属性,可以创建如下的Student类:

public class Student {
    private Long id;
    private String name;
    private int age;

    // Getters and setters
}

接下来是Mapper接口和Mapper XML文件。Mapper接口定义了对数据库进行操作的方法,Mapper XML文件用于映射这些方法到具体的SQL语句。假设你的数据库表名为students,可以创建如下的Mapper接口和XML文件:

public interface StudentMapper {
    List<Student> getAllStudents();
}
<mapper namespace="com.example.mapper.StudentMapper">
    <select id="getAllStudents" resultType="com.example.pojo.Student">
        SELECT * FROM students
    </select>
</mapper>

然后是Service接口和实现类。Service层定义了业务逻辑,实现类负责实际的业务处理。这里创建一个打印学生表格的功能:

public interface StudentService {
    List<Student> getAllStudents();
    ByteArrayOutputStream generatePDFReport(List<Student> students);
}
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> getAllStudents() {
        return studentMapper.getAllStudents();
    }

    @Override
    public ByteArrayOutputStream generatePDFReport(List<Student> students) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, outputStream);
            document.open();

            PdfPTable table = new PdfPTable(3);
            table.addCell("ID");
            table.addCell("Name");
            table.addCell("Age");

            for (Student student : students) {
                table.addCell(student.getId().toString());
                table.addCell(student.getName());
                table.addCell(String.valueOf(student.getAge()));
            }

            document.add(table);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputStream;
    }
}

如果是四个字段及以上需要这样写:

 @Override
    public ByteArrayOutputStream generatePDFReport(List<ShpsOrgRoleResourceRel> shpsOrgRoleResourceRels) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, outputStream);
            document.open();

            PdfPTable table = getPdfPTable(shpsOrgRoleResourceRels);

            document.add(table);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputStream;
    }

    /**
     * 改模版
     * @param shpsOrgRoleResourceRels
     * @return
     */
    private static PdfPTable getPdfPTable(List<ShpsOrgRoleResourceRel> shpsOrgRoleResourceRels) {
        PdfPTable table = new PdfPTable(4);
        table.addCell("RoleResourceCode");
        table.addCell("RoleCode");
        table.addCell("ResourceCode");
        table.addCell("State");


        for (ShpsOrgRoleResourceRel shpsOrgRoleResourceRel : shpsOrgRoleResourceRels) {
            table.addCell(shpsOrgRoleResourceRel.getRoleResourceCode());
            table.addCell(shpsOrgRoleResourceRel.getRoleCode());
            table.addCell(shpsOrgRoleResourceRel.getResourceCode());
            table.addCell(shpsOrgRoleResourceRel.getState().toString());
        }
        return table;
    }

在这个例子中,generatePDFReport方法接受一个学生列表作为参数,并返回一个包含PDF数据的ByteArrayOutputStream。它使用iText库来生成PDF表格,将学生数据插入到表格中。

接下来是Controller层,处理HTTP请求并调用Service层的方法:

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/printStudentsPDF")
    public ResponseEntity<byte[]> printStudentsPDF() {
        List<Student> students = studentService.getAllStudents();
        ByteArrayOutputStream outputStream = studentService.generatePDFReport(students);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "students.pdf");

        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
    }
}

四个字段的Controller并且下载到桌面上的这样写:

/**
     * 导出pdf格式
     * @return
     * @throws IOException
     */
    @RequestMapping("/printShpsOrgRoleResourceRelPDF")
    public ResponseEntity<byte[]> printShpsOrgRoleResourceRelPDF() throws IOException {
        List<ShpsOrgRoleResourceRel> shpsOrgRoleResourceRels = shpsOrgRoleResourceRelService.getShpsOrgRoleResourceRelList();
        ByteArrayOutputStream outputStream = shpsOrgRoleResourceRelService.generatePDFReport(shpsOrgRoleResourceRels);

        byte[] bytes = outputStream.toByteArray();
        ByteArrayResource resource = new ByteArrayResource(bytes);
        // 保存到桌面
        String desktopPath = System.getProperty("user.home") + "/Desktop/shpsOrgRoleResourceRels.pdf";
        FileOutputStream fileOutputStream = new FileOutputStream(desktopPath);
        fileOutputStream.write(bytes);
        fileOutputStream.close();

        //输出到控制台
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "shpsOrgRoleResourceRels.pdf");

        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
    }

在这个例子中,当访问/printStudentsPDF路径时,将调用Service层的方法获取学生数据并生成PDF文件,然后将PDF文件作为响应返回。

最后是POM文件中的依赖配置,包括Spring Boot、MyBatis以及iText库的依赖。这里只展示关键部分:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version> <!-- 版本号根据实际情况调整 -->
    </dependency>

    <!-- iText PDF -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13</version> <!-- 版本号根据实际情况调整 -->
    </dependency>
</dependencies>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现文件上传和下载功能,可以借助 Spring BootMyBatis 框架提供的丰富的 API。下面是一个简单的示例代码: 文件上传: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "上传文件为空"; } try { byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); } return "文件上传成功"; } ``` 文件下载: ```java @GetMapping("/download") public ResponseEntity<byte[]> downloadFile() throws IOException { Path path = Paths.get("uploads/example.txt"); byte[] bytes = Files.readAllBytes(path); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=example.txt"); ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK); return responseEntity; } ``` 在这个示例,我们使用Spring Boot 提供的 @PostMapping 和 @GetMapping 注解来处理文件上传和下载请求,使用MyBatis 框架来实现文件上传和下载所需的持久化操作。 为了更好地组织代码,我们可以将文件上传和下载的逻辑封装成 Service 层的方法,然后在 Controller 调用这些方法。同时,我们也可以使用 Spring Boot 提供的更加便捷的配置来实现文件上传和下载,例如通过配置文件设置上传文件大小限制,设置上传文件路径等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值