pdf导出工具类

(目前只更新导出pdf表格)

导出pdf表格

1、依赖:

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.13</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>

2、工具类:

import com.crunii.micro.common.exception.BusinessException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Filename: PdfUtils
 * @Author: sheng.wanping
 * <li>Date: 2022/8/1 15:40</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class PdfUtils {

	// 定义全局的字体静态变量
	private static Font titlefont;
	private static Font textfont;
	static {
	   try {
	       BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	       titlefont = new Font(bfChinese, 8, Font.BOLD);
	       textfont = new Font(bfChinese, 8, Font.NORMAL);
	   } catch (Exception e) {
	       e.printStackTrace();
	   }
	}

    /**
 * @Filename: PdfUtils pdf工具类
 * @Author: sheng.wanping
 * <li>Date: 2022/8/1 15:40</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class PdfUtils {

    /**
     * 用于返回 简单列表PDF表格
     * @param response
     * @param tableName 表名
     * @param list 数据列表
     * @param map 中英文map(key为标题,value为字段英文名;注意:map是有顺序的,可用LinkedHashMap)
     * @param <T>
     */
    public static  <T> void pdfSingleTable(HttpServletResponse response, String tableName, List<T> list, Map<String, String> map) {
        // 1、从map中获取字段中文名和英文名
        List<String> valueList = new ArrayList<>(); // 存表格所有数据
        List<String> fieldEnList = new ArrayList<>(); // 字段英文名
        for (Map.Entry<String, String> entry : map.entrySet()) {
            valueList.add(entry.getKey());
            fieldEnList.add(entry.getValue());
        }
        // 2、用反射根据字段名获取值
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < fieldEnList.size(); j++) {
                Field field = null;
                String strValue = "";
                try {
                    field = list.get(i).getClass().getDeclaredField(fieldEnList.get(j));
                    field.setAccessible(true);
                    Object value = field.get(list.get(i));
                    if (value != null) {
                        if (value instanceof Date) {
                            strValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
                        } else {
                            strValue = String.valueOf(value);
                        }
                    } else {
                        strValue = "";
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } finally {
                    valueList.add(strValue);// 字段值
                }
            }
        }
        // 3、返回pdf
        try {
            // 3-1.新建document对象
            Document document = new Document(PageSize.A4);
            // 3-2.建立一个书写器
            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tableName+".pdf", "UTF-8"));
            ServletOutputStream out = response.getOutputStream();
            PdfWriter.getInstance(document, out);
            // 3-3.打开文档
            document.open();
            // 3-4、查询数据库数据,并存入list中
            // 3-5、设置单元格宽度
            List<Integer> mergeCellList = new ArrayList<>();
            int idx = 0;
            while (idx < (list.size() + 1) * fieldEnList.size()) {
                idx++;
                mergeCellList.add(1);
            }
            // 3-6.创建表格
            PdfPTable table = new PdfPTable(fieldEnList.size());
            for (int i = 0; i < mergeCellList.size(); i++) {
                PdfPCell cell = new PdfPCell(); // 创建行
                cell.setColspan(mergeCellList.get(i)); // 合并单元格
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                cell.setPhrase(new Phrase(valueList.get(i), new Font(bfChinese, 8, Font.NORMAL)));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                table.addCell(cell); // 添加单元格内容
            }
            // 3-7、向文档中添加内容
            document.add(table);
            // 3-8、关闭文档
            document.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("导出pdf失败");
        }
    }

    /**
     * 返回一个字节数组输出流
     * @param list 数据列表
     * @param map 中英文map(key为标题,value为字段英文名;注意:map是有顺序的,可用LinkedHashMap)
     * @param <T>
     */
    public static  <T> ByteArrayOutputStream getByteArray(List<T> list, Map<String, String> map) {
        // 1、从map中获取字段中文名和英文名
        List<String> valueList = new ArrayList<>(); // 存表格所有数据
        List<String> fieldEnList = new ArrayList<>(); // 字段英文名
        for (Map.Entry<String, String> entry : map.entrySet()) {
            valueList.add(entry.getKey());
            fieldEnList.add(entry.getValue());
        }
        // 2、用反射根据字段名获取值
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < fieldEnList.size(); j++) {
                Field field = null;
                String strValue = "";
                try {
                    field = list.get(i).getClass().getDeclaredField(fieldEnList.get(j));
                    field.setAccessible(true);
                    Object value = field.get(list.get(i));
                    if (value != null) {
                        if (value instanceof Date) {
                            strValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
                        } else {
                            strValue = String.valueOf(value);
                        }
                    } else {
                        strValue = "";
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } finally {
                    valueList.add(strValue);// 字段值
                }
            }
        }
        // 3、返回pdf
        try {
            // 3-1.新建document对象
            Document document = new Document(PageSize.A4);
            // 2.建立一个书写器
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, os);
            // 3-3.打开文档
            document.open();
            // 3-4、查询数据库数据,并存入list中
            // 3-5、设置单元格宽度
            List<Integer> mergeCellList = new ArrayList<>();
            int idx = 0;
            while (idx < (list.size() + 1) * fieldEnList.size()) {
                idx++;
                mergeCellList.add(1);
            }
            // 3-6.创建表格
            PdfPTable table = new PdfPTable(fieldEnList.size());
            for (int i = 0; i < mergeCellList.size(); i++) {
                PdfPCell cell = new PdfPCell(); // 创建行
                cell.setColspan(mergeCellList.get(i)); // 合并单元格
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                cell.setPhrase(new Phrase(valueList.get(i), new Font(bfChinese, 8, Font.NORMAL)));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                table.addCell(cell); // 添加单元格内容
            }
            // 3-7、向文档中添加内容
            document.add(table);
            document.close();
            return os;
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("导出pdf失败");
        }
    }

}

3、测试代码

	private static final Map<String, String> BUDGE_MAP = new LinkedHashMap<>();
	static {
	   BUDGE_MAP.put("主设备", "mainEquipmentExpense");
	   BUDGE_MAP.put("天线", "aerialExpense");
	   BUDGE_MAP.put("电源", "powerExpense");
	}
	
	public void testPdf(HttpServletResponse response) {
        List<Object> list = testDao.getData;// 查询数据列表
        PdfUtils.pdfSingleTable(response, "表名", list, BUDGE_MAP);// 导出pdf表格
    }
下面是一个使用 iTextPDF 5.5.10 导出 PDF 表格的示例工具类,其中包含支持单元格合并的方法: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class PDFExporter { public static void exportTableToPDF(String filePath, String[] header, String[][] data) { Document document = new Document(PageSize.A4.rotate()); try { PdfWriter.getInstance(document, new FileOutputStream(filePath)); document.open(); PdfPTable table = new PdfPTable(header.length); table.setWidthPercentage(100); for (String column : header) { PdfPCell cell = new PdfPCell(); cell.setPhrase(new com.itextpdf.text.Paragraph(column)); table.addCell(cell); } for (int row = 0; row < data.length; row++) { for (int column = 0; column < data[row].length; column++) { PdfPCell cell = new PdfPCell(); cell.setPhrase(new com.itextpdf.text.Paragraph(data[row][column])); table.addCell(cell); } } document.add(table); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { document.close(); } } public static void mergeCells(PdfPTable table, int row1, int col1, int row2, int col2) { for (int row = row1; row <= row2; row++) { for (int col = col1; col <= col2; col++) { if (row == row1 && col == col1) { continue; } PdfPCell cell = table.getRow(row).getCells()[col]; cell.setPhrase(null); cell.setPadding(0); cell.setBorder(PdfPCell.NO_BORDER); } } PdfPCell cell = table.getRow(row1).getCells()[col1]; cell.setRowspan(row2 - row1 + 1); cell.setColspan(col2 - col1 + 1); } } ``` 调用 `exportTableToPDF` 方法可以将一个二维字符串数组导出为一个 PDF 表格文件,其中第一个参数是文件路径,第二个参数是表头数组,第三个参数是数据数组。 调用 `mergeCells` 方法可以将表格中的多个单元格合并为一个单元格,其中第一个参数是目标表格,第二个参数是起始行号,第三个参数是起始列号,第四个参数是结束行号,第五个参数是结束列号。 例如,如果要将第 2 行第 3、4、5 列合并为一个单元格,可以这样调用 `mergeCells` 方法: ```java PDFExporter.mergeCells(table, 1, 2, 1, 4); ``` 其中 `table` 是导出 PDF 表格的 `PdfPTable` 对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值