package cn.ccccltd.conc.smp.service.pdf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.alibaba.druid.util.StringUtils;
import com.aliyun.openservices.shade.org.apache.commons.codec.binary.Base64;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
@Component
public class ExportPdfUtils {
@Autowired
private PdfUploadHelper pdfUploadHelper;
private static final Logger logger = LoggerFactory.getLogger(ExportPdfUtils.class);
/**
* font relative path 字体样式文件路径
*/
public static final String FONT_PATH = "/mnt/admin/SIMKAI.TTF";
/*
标题行宽
*/
public static final int TITLE_ROWSPAN_NUM_3 = 3;
/**
* 审批记录默认表格列数( PDF 列款 )
*/
public static final int DEFAULT_WFC_COLUMN_14 = 14;
/**
* 字体样式 - 未定义的
*/
public static final int STYLE_NORMAL = Font.UNDEFINED;
//最小单元格高度
private static final int MINIMUM_HEIGHT_20 = 20;
/**
* 标题<br>字体大小</>
*/
public static final int TITLE_FONT_SIZE_16 = 16;
/**
* 二级字体大小
*/
public static final int SECOND_TITLE_FONT_SIZE_12 = 12;
/**
* 默认字体大小
*/
public static final int DEFAULT_FONT_SIZE_8 = 8;
/**
* 右<br>对齐</>
*/
public static final int ALIGN_RIGHT = PdfPCell.ALIGN_RIGHT;
/**
* 左对齐
*/
public static final int ALIGN_LEFT = PdfPCell.ALIGN_LEFT;
/**
* 居中对齐
*/
public static final int ALIGN_MIDDLE = PdfPCell.ALIGN_CENTER;
/**
* 字体样式全路径
*
* @return
* @throws FileNotFoundException
*/
public static String getFontResourcesPath() {
return FONT_PATH;
}
/**
* 组装文本单元格
*
* @param data 单元格内容
* @param fontsize 字体大小
* @param style:字体样式 (Font.BOLD=加粗,UNDEFINED默认)
* @param colspanNum:列宽数
* @param rowspan 行宽数
* @param elePosition 对齐方式 :ExportPdfUtils.ALIGN_LEFT=左对齐,excel表格位置
*/
public static PdfPCell createFontPdfPCell(String data, int fontsize, int style, int colspanNum, int rowspan, int elePosition) {
Font font = setUpPdfStyle(fontsize, style);
PdfPCell cell = new PdfPCell(new Phrase(data, font));
cell.setHorizontalAlignment(elePosition);// 单元格对齐方式
cell.setColspan(colspanNum);// 合并列数
cell.setMinimumHeight(MINIMUM_HEIGHT);
cell.setRowspan(rowspan);
return cell;
}
/*
创建 标题 单元格
*/
public static PdfPCell createTitlePdfCell(String context) {
return createFontPdfPCell(context, TITLE_FONT_SIZE, Font.BOLD, DEFAULT_WFC_COLUMN, TITLE_ROWSPAN_NUM, PdfPCell.ALIGN_CENTER);
}
/*
创建 基本信息 单元格
*/
public static PdfPCell createBasicPdfCell(String context, int colSpan, int rowSpan) {
return createFontPdfPCell(context, DEFAULT_FONT_SIZE, Font.NORMAL, colSpan, rowSpan, PdfPCell.ALIGN_LEFT);
}
/*
创建 清单 单元格
*/
public static PdfPCell createBillPdfCell(String context,int colSpan){
return createFontPdfPCell(context, DEFAULT_FONT_SIZE, Font.NORMAL, colSpan, 1, PdfPCell.ALIGN_CENTER);
}
/**
* 设置默认字体
*
* @param fontsize 字体大小
* @param style:字体样式 (Font.BOLD=加粗,Font.UNDEFINED默认)
* @return
* @throws DocumentException
* @throws IOException
*/
public static Font setUpPdfStyle(int fontsize, int style) {
try {
String fontResourcesPath = getFontResourcesPath();// 字体文件路径
BaseFont abf = BaseFont.createFont(fontResourcesPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(abf, fontsize, style);// 设置默认字体
return font;
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("创建pdf字体异常" + e.getMessage());
}
}
/**
* 组装图片单元格
*
* @param decodeBase64Str
* @param colspanNum
* @param rowspan
* @return
*/
public static PdfPCell createImagePdfPCell(String decodeBase64Str, int colspanNum, int rowspan) {
Image image;
int width = 60;
int height = 40;
try {
if (StringUtils.isEmpty(decodeBase64Str)) {
PdfPCell cell = new PdfPCell(new Phrase(decodeBase64Str));
cell.setColspan(colspanNum);
cell.setRowspan(rowspan);
return cell;
} else {
byte[] decodeBase64 = Base64.decodeBase64(decodeBase64Str);
image = Image.getInstance(decodeBase64);
image.scaleAbsolute(width, height);
image.scaleToFit(60, 40);
PdfPCell cell = new PdfPCell(image, false);
cell.setColspan(colspanNum);
cell.setRowspan(rowspan);
cell.setPadding(2);
cell.setHorizontalAlignment(ALIGN_MIDDLE);
return cell;
}
} catch (Exception e) {
logger.error("生成PDF 表格失败", e);
throw new BusinessException(TipsMsg.CRETAE_PDF_CELL_ERROR.getCode(),
TipsMsg.CRETAE_PDF_CELL_ERROR.getTipsMsg());
}
}
/**
* 创建table
*
* @param tableColumns
* @return
*/
public static PdfPTable createPdfPTable(int tableColumns) {
PdfPTable table = new PdfPTable(tableColumns);// numcolumns:列数
return table;
}
/**
* 创建cell 表格去除模板
*
* @param data
* @param fontsize
* @param style
* @param colspanNum
* @param rowspan
* @param elePosition
* @return
*/
public static PdfPCell creatTitlePdfCellNoBorder(String data, int fontsize, int style, int colspanNum, int rowspan, int elePosition) {
try {
Font font = setUpPdfStyle(fontsize, style);
PdfPCell cell = new PdfPCell(new Phrase(data, font));
cell.enableBorderSide(-1);//去除边框
cell.setHorizontalAlignment(elePosition);// 单元格对齐方式
cell.setColspan(colspanNum);// 合并列数
cell.setMinimumHeight(30);
cell.setRowspan(rowspan);
return cell;
} catch (Exception e) {
logger.error("生成PDF 表格cell失败", e);
throw new BusinessException(TipsMsg.CRETAE_PDF_CELL_ERROR.getCode(),
TipsMsg.CRETAE_PDF_CELL_ERROR.getTipsMsg());
}
}
/**
* 表格列数
*
* @param tableColumns 表格列数
* @param data:表格列数据
* @return
*/
public static PdfPTable createPdfPTable(int tableColumns, List<PdfPCell> data) {
PdfPTable table = new PdfPTable(tableColumns);// numcolumns:列数
if (CollectionUtils.isEmpty(data)) {
PdfPCell cell = createFontPdfPCell("暂无数据", TITLE_FONT_SIZE, Font.UNDEFINED, tableColumns, 1, Element.ALIGN_CENTER);
table.addCell(cell);
} else {
for (PdfPCell item : data) {
table.addCell(item);
}
}
return table;
}
/**
* 生成审批pdf
*
* @param data table 表格数据
* @param fileName
*/
public FileRspBo mutilTableCreatePdf(List<PdfPTable> data, String fileName, ReqInfo reqInfo) {
Document document = null;
FileRspBo fileRspBo = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
try {
Rectangle A4t = new RectangleReadOnly(842, 595);
document = new Document(A4t, 16, 16, 16, 16);
PdfWriter.getInstance(document, outputStream);
document.open();
if (CollectionUtils.isEmpty(data)) {
PdfPCell cell = createFontPdfPCell("暂无数据", TITLE_FONT_SIZE, Font.UNDEFINED, 14, 1, Element.ALIGN_CENTER);
PdfPTable table = new PdfPTable(14);// numcolumns:列数
table.addCell(cell);
data.add(table);
}
data = Optional.ofNullable(data).orElse(new ArrayList<>());
for (PdfPTable item : data) {
document.add(item);
}
return fileRspBo;
} catch (Exception e) {
logger.error("生成PDF失败", e);
throw new BusinessException(TipsMsg.CRETAE_PDF_CELL_ERROR.getCode(),
TipsMsg.CRETAE_PDF_CELL_ERROR.getTipsMsg());
} finally {
if (document != null) {
document.close();
// 上传到oss
fileRspBo = pdfUploadHelper.uploadFileToOss(new ByteArrayInputStream(outputStream.toByteArray()), fileName, reqInfo);
return fileRspBo;
}
}
}
/**
* 生成pdf,上传到oss
*
* @param data
* @param tableColumns
* @throws IOException
*/
public FileRspBo dataToPdf(List<PdfPCell> data, int tableColumns, String fileName, ReqInfo reqInfo) {
Document document = null;
FileRspBo fileRspBo = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
try {
logger.debug("11");
Rectangle A4t = new RectangleReadOnly(842, 595);
document = new Document(A4t, 16, 16, 16, 16);
PdfWriter.getInstance(document, outputStream);
logger.debug("22");
document.open();
data = Optional.ofNullable(data).orElse(new ArrayList<>());
PdfPTable table = createPdfPTable(tableColumns);
logger.debug("33");
if (CollectionUtils.isEmpty(data)) {
PdfPCell cell = createFontPdfPCell("暂无数据", TITLE_FONT_SIZE, Font.UNDEFINED, tableColumns, 1, Element.ALIGN_CENTER);
data.add(cell);
}
for (PdfPCell item : data) {
table.addCell(item);
}
logger.debug("44");
document.add(table);
return fileRspBo;
} catch (Exception e) {
logger.error("客户端生成PDF失败"+fileName, e);
throw new BusinessException(TipsMsg.CRETAE_PDF_CELL_ERROR.getCode(),
TipsMsg.CRETAE_PDF_CELL_ERROR.getTipsMsg());
} finally {
if (document != null) {
logger.debug("55");
document.close();
// 上传到oss
logger.debug("66");
fileRspBo = pdfUploadHelper.uploadFileToOss(new ByteArrayInputStream(outputStream.toByteArray()), fileName, reqInfo);
return fileRspBo;
}
}
}
/**
*审批通过后mq驱动生成pdf文件
* @param data
* @param tableColumns
* @throws IOException
*/
public byte[] mqCreatePdfStream(List<PdfPCell> data, int tableColumns) {
Document document = null;
byte[] fileData = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
try {
Rectangle A4t = new RectangleReadOnly(842, 595);
document = new Document(A4t, 16, 16, 16, 16);
PdfWriter.getInstance(document, outputStream);
document.open();
data = Optional.ofNullable(data).orElse(new ArrayList<>());
PdfPTable table = createPdfPTable(tableColumns);
if (CollectionUtils.isEmpty(data)) {
PdfPCell cell = createFontPdfPCell("暂无数据", TITLE_FONT_SIZE, Font.UNDEFINED, tableColumns, 1, Element.ALIGN_CENTER);
data.add(cell);
}
for (PdfPCell item : data) {
table.addCell(item);
}
logger.debug("44");
document.add(table);
return fileData;
} catch (Exception e) {
logger.error("客户端生成PDF失败", e);
throw new BusinessException(TipsMsg.CRETAE_PDF_CELL_ERROR.getCode(),
TipsMsg.CRETAE_PDF_CELL_ERROR.getTipsMsg());
} finally {
if (document != null) {
logger.debug("mqCreatePdfStream create pdf Stream----------");
document.close();
return outputStream.toByteArray();
}
}
}
}
PDF导出工具
这个Java类库用于生成PDF文件,包含字体设置、图片处理、单元格创建及表格组装等方法。主要使用iTextPDF库,支持字体资源路径配置、单元格对齐、合并及内容填充等功能。此外,还提供了上传生成的PDF到OSS的服务。
摘要由CSDN通过智能技术生成