栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring Boot导出Pdf文件

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot导出Pdf文件

除了常见的jsp视图外,还有pdf,excel等。不管哪种视图,都会实现SpringMvc定义的视图接口View。这篇文章就讲讲怎么使用Pdf视图----AbstractPdfView。

AbstractPdfView属于非逻辑视图,不需要任何的视图解析器(ViewResolver)去定位。它是一个抽象类,有一个抽象方法需要我们去实现。

    
    protected abstract void buildPdfdocument(Map model, document document, PdfWriter writer,
            HttpServletRequest request, HttpServletResponse response) throws Exception;

我们首先创建一个Spring Boot工程,这里的orm使用Mybatis,数据源使用Druid,为了能够使用pdf,我们需要加pom.xml中相关的依赖,下面贴出完整的pom文件

    
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.xhtmlrenderer
            core-renderer
            R8
        
        
            com.itextpdf
            itextpdf
            5.5.12
        
        
            com.alibaba
            druid
            1.1.6
        
    

继承了AbstractPdfView后,就得实现它的抽象方法,从而完成导出的逻辑,而每个控制器可能都有不同的导出逻辑,所以为了适应不同控制器的自定义导出,先定义一个导出接口。

import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.lowagie.text.document;import com.lowagie.text.pdf.PdfWriter;public interface PdfExportService {    
    
    public void make(Map model, document document, PdfWriter writer, 
            HttpServletRequest request, HttpServletResponse response);
}

注意这里导的是com.lowagie.text包下的类。

有了这个接口后,各个控制器只需要实现这个接口,就能自定义导出pdf的逻辑。

接着就是继承AbstractPdfView,通过它调度PdfExportService 的make方法就可以让控制器去实现自定义的导出逻辑。

public class PdfView extends AbstractPdfView {    
    private PdfExportService pdfExportService = null;    
    
    public PdfView(PdfExportService pdfExportService) {        this.pdfExportService = pdfExportService;
    }    
    @Override
    protected void buildPdfdocument(Map model, document document, PdfWriter writer,
            HttpServletRequest request, HttpServletResponse response) throws Exception {        
        // 调用导出服务接口类
        pdfExportService.make(model, document, writer, request, response);
    }

}

这里可以看到,在创建自定义pdf视图时,需要自定义一个导出服务接口(PdfExportService ),通过实现这个接口,每个控制器都可以自定义其导出的逻辑。

完成了上面的工作,接下来就是正常的SSM结合。首先在Spring Boot的配置文件中进行配置

# 数据库配置jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8jdbc.username = root
jdbc.password = 1311664842# mybatis 配置文件的路径mybatis_config_file = /mybatis/mybatis-config.xml# 映射文件的路径mapper_path = /mapper@Configuration// 扫描dao层@MapperScan(value = "com.codeliu.dao")public class DataSourceConfig {    
    @Value(value = "${jdbc.driver}")    private String jdbcDriver;    
    @Value(value = "${jdbc.url}")    private String jdbcUrl;    
    @Value(value = "${jdbc.username}")    private String jdbcUsername;    
    @Value(value = "${jdbc.password}")    private String jdbcPassword;    
    @Bean(value = "dataSource")    public DruidDataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcDriver);
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUsername);
        dataSource.setPassword(jdbcPassword);        return dataSource;
    }
}
@Configurationpublic class SqlSessionFactoryConfig {    // mybatis配置文件的路径
    @Value(value = "${mybatis_config_file}")    private String mybatisConfigPath;    
    // mybatis映射文件的路径
    @Value(value = "${mapper_path}")    private String mapperPath;    
    // 实体包的路径
    @Value(value = "${entity_package}")    private String entityPath;    
    @Autowired
    private DataSource dataSource;    
    @Bean(value = "sqlSessionFactory")    public SqlSessionFactoryBean getSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();        
        // mybatis配置文件的路径
        sqlSessionFactory.setConfigLocation(new ClassPathResource(mybatisConfigPath));
        
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;        // 指定映射文件的路径
        sqlSessionFactory.setMapperLocations(resolver.getResources(packageSearchPath));        // 配置数据源
        sqlSessionFactory.setDataSource(dataSource);        // 配置实体包的扫描路径
        sqlSessionFactory.setTypeAliasesPackage(entityPath);        return sqlSessionFactory;
    }
}

注意加上了@Configuration注解,表示这是一个配置类。这样Spring Boot启动的时候,就会进行相关的初始化。

现在可以来进行controller的编写。

@Controller@RequestMapping("/man")public class ManController {    
    @Autowired
    private ManService manService;    
    
    @GetMapping("/export/pdf")    public ModelAndView exportPdf() {
        List manList = manService.getManList();        // 定义pdf视图
        View view = new PdfView(exportService());
        ModelAndView mv = new ModelAndView();        // 设置视图
        mv.setView(view);        // 加入数据模型
        mv.addObject("manList", manList);        return mv;
    }    
    
    
    @SuppressWarnings("unchecked")    public PdfExportService exportService() {        // 使用Lambda表达式
        return(model, document, writer, request, response)-> {            try {                // A4纸张
                document.setPageSize(PageSize.A4);                // 标题
                document.addTitle("用户信息");                // 换行
                document.add(new Chunk("n"));                // 表格,3列
                PdfPTable table = new PdfPTable(3);                // 单元格
                PdfPCell cell = null;                // 字体,定义为蓝色加粗
                Font f8 = new Font();
                f8.setColor(Color.BLUE);
                f8.setStyle(Font.BOLD);                // 标题
                cell = new PdfPCell(new Paragraph("id", f8));                // 居中对齐
                cell.setHorizontalAlignment(1);                // 将单元格加入表格
                table.addCell(cell);                
                // 标题
                cell = new PdfPCell(new Paragraph("age", f8));                // 居中对齐
                cell.setHorizontalAlignment(1);                // 将单元格加入表格
                table.addCell(cell);                
                // 标题
                cell = new PdfPCell(new Paragraph("name", f8));                // 居中对齐
                cell.setHorizontalAlignment(1);                // 将单元格加入表格
                table.addCell(cell);                
                // 获取数据模型中的manList
                List manList = (List)model.get("manList");                for(Man man:manList) {
                    document.add(new Chunk("n"));
                    cell = new PdfPCell(new Paragraph(man.getId() + ""));                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getAge() + ""));                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(man.getName()));                    // 居中对齐
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                }                // 文档中加入表格
                document.add(table);
            } catch(documentException e) {
                e.printStackTrace();
            }
        };
    }
}

可以看到我们先通过数据库查询出数据,然后放入模型和视图(ModelAndView)中,然后设置pdf视图(PdfView)。而定义PdfView时,使用Lambda表达式实现了导出服务接口,这样就可以很方便的让每一个控制器自定义样式和数据。导出pdf文件的逻辑在exportService方法中。

启动Spring Boot文件后,输入url,显示下面的结果



作者:Java攻城玩家
链接:https://www.jianshu.com/p/eab1eaef031c


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235219.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号