在adobe生成pdf模板后,用代码填充pdf内容(添加图片与表格等)(二)

280 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第十九天,点击查看活动详情


上一章写了在PDF中添加基础文本域及赋值,这一章继续写在adobe生成pdf模板后,用代码填充pdf内容(添加图片与表格等)功能。

在实际应用中可能会需要用代码添加PDF表格数据,这时候就需要先在PDF中加入表格对应的域,设置表格域名,然后循环list数据对该域赋值。

public static void insertTable(AcroFields form, Object tempValue, PdfStamper pdfStamper) throws IOException, DocumentException {
    /**
     * 添加表格
     */
    String fonts = getChineseFont(0);//获取字体
    BaseFont bf = BaseFont.createFont(fonts, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//创建字体
    //根据表格设置的域名获取表格
    AcroFields.FieldPosition fieldPosition = form.getFieldPositions("projects").get(0);
    //设置字体大小及格式
    Font keyfont = new Font(bf, 8, Font.NORMAL);
    //计算表格的宽度
    float width = fieldPosition.position.getRight() - fieldPosition.position.getLeft();
    List dateList = ((ProjectListModel) tempValue).getProjectName();
    //根据list大小新建PdfPTable对象,并赋予对应的属性
    PdfPTable table = new PdfPTable(dateList.size());
    table.setTotalWidth(width);
    table.setLockedWidth(true);
    //设置格式为居中
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    //设置表格边框的宽度
    table.getDefaultCell().setBorder(1);
 
   
    if (dateList != null && dateList.size() > 0) {
        //循环表格第一行数据
        for (int i = 0; i < dateList.size(); i++) {
            String date = dateList.get(i).toString();
            //创建列数据
            PdfPCell cell = createCell(date, keyfont);
            table.addCell(cell);
        }
        List<ProjectValListModel> valListModels = ((ProjectListModel) tempValue).getProjectVal();
        //循环表格除第一行外的值
        for (int i = 0; i < valListModels.size(); i++) {
            List list = (List) valListModels.get(i);
            for (int j = 0; j < list.size(); j++) {
                table.addCell(createCell(list.get(j), keyfont));
            }
        }
    }
    //插入文档
    PdfContentByte cb = pdfStamper.getOverContent(1);
    table.writeSelectedRows(0, -1, 0, -1, fieldPosition.position.getLeft(), fieldPosition.position.getTop(), cb);
}
 
/**
 * 创建单元格
 *
 * @param value 显示内容
 * @return
 */
private static PdfPCell createCell(Object value, Font font) {
    //新建表格列数据
    PdfPCell cell = new PdfPCell();
    cell.setUseAscender(true);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    //设置列数据格式为居中
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBorderWidth(0);
    //将值特殊处理后放进去
    cell.setPhrase(new Phrase(getBlank(value), font));
    // 设置单元格高度
    cell.setFixedHeight(15f);
    return cell;
}
 
/**
 * 数据非空处理
 *
 * @param value
 * @return
 */
private static String getBlank(Object value) {
    if (value != null) {
        return value.toString();
    }
    return "";
}