Java将数据集合转换为PDF

将数据集合转换为pdf

依赖itext7包将数据集合转换导出为PDF文件

引入包

<properties>
    <itext.version>7.1.11</itext.version>
</properties>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>${itext.version}</version>
    <type>pom</type>
</dependency>

工具类

package xxxxxxxxxxxxxxxxxxxxx;

import cn.hutool.core.date.DateTime;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * TO PDF Utils
 *
 * @author linxifengbao
 * @Date 2023/7/14
 **/
public class ToPdfUtils {

    /**
     * excel 写入到 pdf
     * @param workbook      excel的workbook
     * @param outFilePath   要写入的pdf文件详细路径(带.pdf,例如写到项目根目录:"output.pdf")
     * @throws IOException
     */
    public static void excelToPdf(org.apache.poi.ss.usermodel.Workbook workbook, String outFilePath) throws IOException {
        PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(outFilePath)));
             Document document = new Document(pdf, PageSize.A4.rotate())) {

            Sheet sheet = workbook.getSheetAt(0);
            int column = sheet.getRow(0).getLastCellNum();
            int row = sheet.getPhysicalNumberOfRows();

            Table table = new Table(column - sheet.getRow(0).getFirstCellNum());

            String str = null;
            for (int i = sheet.getFirstRowNum(); i < row; i++) {
                for (int j = sheet.getRow(0).getFirstCellNum(); j < column; j++) {
                    //获取excel单元格
                    org.apache.poi.ss.usermodel.Cell cell = sheet.getRow(i).getCell(j);
                    if (cell.getCellType() == CellType.NUMERIC) {
                        str = (int) cell.getNumericCellValue() + "";
                    } else {
                        str = cell.getStringCellValue();
                    }
                    Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
                    table.addCell(cells);
                }
            }
            document.add(table);

        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * excel 写入到 pdf 点击浏览器直接下载 pdf
     * @param workbook      excel的workbook
     * @param response
     * @throws IOException
     */
    public static void excelToPdfForBrowserDownload(org.apache.poi.ss.usermodel.Workbook workbook,
                                                    HttpServletResponse response,
                                                    String fileName) throws ServletException, IOException {
        String currentTimeStr = cn.hutool.core.date.DateUtil.format(new DateTime(new Date().getTime()), "yyyyMMddHHmmss");
        fileName = fileName + currentTimeStr + ".pdf";
        // 设置响应头,告诉浏览器下载文件
        response.reset();
        response.setCharacterEncoding("utf-8");
        fileName = java.net.URLEncoder.encode(fileName,"UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        response.setContentType("application/pdf");
        // 将PDF内容写入响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(outputStream));
             Document document = new Document(pdf, PageSize.A4.rotate())) {

            Sheet sheet = workbook.getSheetAt(0);
            int column = sheet.getRow(0).getLastCellNum();
            int row = sheet.getPhysicalNumberOfRows();

            Table table = new Table(column - sheet.getRow(0).getFirstCellNum());

            String str = null;
            for (int i = sheet.getFirstRowNum(); i < row; i++) {
                for (int j = sheet.getRow(0).getFirstCellNum(); j < column; j++) {
                    //获取excel单元格
                    org.apache.poi.ss.usermodel.Cell cell = sheet.getRow(i).getCell(j);
                    if (cell.getCellType() == CellType.NUMERIC) {
                        str = (int) cell.getNumericCellValue() + "";
                    } else {
                        str = cell.getStringCellValue();
                    }
                    Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
                    table.addCell(cells);
                }
            }
            document.add(table);

        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

    private static String getSuffix(String filePath) {
        int dotIndex = filePath.lastIndexOf(".");
        return filePath.substring(dotIndex + 1);
    }

    /**
     * 数据集合 写入到 pdf 点击浏览器直接下载 pdf
     * @param headList       表头数据
     * @param columnNameList 字段名数据
     * @param dataList       列表数据
     * @param fileName       文件名
     * @param response
     * @throws IOException
     */
    public static void dataToPdfForBrowserDownload(List<String> headList,
                                                   List<String> columnNameList,
                                                   List<Map<String, Object>> dataList,
                                                   HttpServletResponse response,
                                                   String fileName) throws ServletException, IOException {
        String currentTimeStr = cn.hutool.core.date.DateUtil.format(new DateTime(new Date().getTime()), "yyyyMMddHHmmss");
        fileName = fileName + currentTimeStr + ".pdf";
        // 设置响应头,告诉浏览器下载文件
        response.reset();
        response.setCharacterEncoding("utf-8");
        fileName = java.net.URLEncoder.encode(fileName,"UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        response.setContentType("application/pdf");
        // 将PDF内容写入响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
        try (PdfDocument pdf = new PdfDocument(new PdfWriter(outputStream));
             Document document = new Document(pdf, PageSize.A4.rotate())) {
            //设置表格列数
            Table table = new Table(headList.size());
            // 设置表格宽度为页面宽度的百分比
            table.useAllAvailableWidth();
            //添加表头数据
            for (String itemHead : headList) {
                table.addCell(new Cell().setFont(pdfFont).add(new Paragraph(itemHead)));
            }
            //添加表格内数据
            if(dataList != null && dataList.size() > 0) {
                for (Map<String, Object> itemDataMap : dataList) {
                    for (String columnName : columnNameList) {
                        String str = itemDataMap.get(columnName) == null ? "" : itemDataMap.get(columnName).toString();
                        Cell cell = new Cell().setFont(pdfFont).add(new Paragraph(str));
                        table.addCell(cell);
                    }
                }
            }
            document.add(table);
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * 数据集合 写入到 pdf 点击浏览器直接下载 pdf
     * 带contentLength设置
     *
     * @param headList       表头数据
     * @param columnNameList 字段名数据
     * @param dataList       列表数据
     * @param fileName       文件名
     * @param response
     * @throws IOException
     */
    public static void dataToPdfForBrowserDownloadWithProgress(List<String> headList,
                                                               List<String> columnNameList,
                                                               List<Map<String, Object>> dataList,
                                                               HttpServletResponse response,
                                                               String fileName) throws ServletException, IOException {
        String currentTimeStr = cn.hutool.core.date.DateUtil.format(new DateTime(new Date().getTime()), "yyyyMMddHHmmss");
        fileName = fileName + currentTimeStr + ".pdf";
        // 设置响应头,告诉浏览器下载文件
        response.reset();
        response.setCharacterEncoding("utf-8");
        fileName = java.net.URLEncoder.encode(fileName,"UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        response.setContentType("application/pdf");
        // 响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 内存字节数组流对象
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
        try {
            // 将pdfWriter与一个ByteArrayOutputStream对象关联起来,以便将PDF写入内存中的字节数组
            PdfWriter pdfWriter = new PdfWriter(baos);
            PdfDocument pdf = new PdfDocument(pdfWriter);
            Document document = new Document(pdf, PageSize.A4.rotate());
            //设置表格列数
            Table table = new Table(headList.size());
            // 设置表格宽度为页面宽度的百分比
            table.useAllAvailableWidth();
            //添加表头数据
            for (String itemHead : headList) {
                table.addCell(new Cell().setFont(pdfFont).add(new Paragraph(itemHead)));
            }
            //添加表格内数据
            if(dataList != null && dataList.size() > 0) {
                for (Map<String, Object> itemDataMap : dataList) {
                    for (String columnName : columnNameList) {
                        String str = itemDataMap.get(columnName) == null ? "" : itemDataMap.get(columnName).toString();
                        Cell cell = new Cell().setFont(pdfFont).add(new Paragraph(str));
                        table.addCell(cell);
                    }
                }
            }
            document.add(table);

            // 关闭文档
            document.close();
            // 获取PDF内容的字节数组
            byte[] byteArray = baos.toByteArray();
            // 设置response的内容长度
            response.setContentLength(byteArray.length);
            // 输出PDF内容到response的输出流中
            response.getOutputStream().write(byteArray);

        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }


}

测试代码

    @GetMapping("/testDataToPdf")
    public void testDataToPdf(HttpServletResponse httpServletResponse) throws ServletException, IOException {
        List<String> headList = Arrays.asList("姓名", "年龄");
        List<String> columnNameList = Arrays.asList("name", "age");
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("id", i);
            itemMap.put("name", "张" + i);
            itemMap.put("age", new Random().nextInt(50) + 1);
            dataList.add(itemMap);
        }
        String fileName = "测试";
        ToPdfUtils.dataToPdfForBrowserDownloadWithProgress(headList, columnNameList, dataList, httpServletResponse, fileName);
    }

导出效果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值