Java将数据集合转换为PDF

这里写自定义目录标题

  • 将数据集合转换为pdf
    • 引入包
    • 工具类
    • 测试代码
    • 导出效果

将数据集合转换为pdf

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

引入包


    7.1.11



    com.itextpdf
    itext7-core
    ${itext.version}
    pom

工具类

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);
    }

导出效果

Java将数据集合转换为PDF_第1张图片

你可能感兴趣的:(java,pdf,开发语言)