/**
* Function 生成PDF报表
* CreateTime 2014年7月22日
* @author yyh
* @version 1.2.0
*/
public class ExportReportForPDF implements IExportReport{
/**
* Function 生成PDF报表
* CreateTime 2014年7月22日
* @author yyh
* @version 1.0.0
* @param HttpServletRequest request
* @param HttpServletResponse response
* @param Map<?,?> reportInfo 生成报表所需要的数据
*
* 说明:不能同时跨行跨列;可设置Cell宽度
* (yyh UpdateTime 2014-7-22)
*/
@Override
public void createReport(HttpServletRequest request,
HttpServletResponse response, Map<?, ?> reportInfo)
throws Exception {
String[] tableCaptionList = (String[])reportInfo.get("tableCaptionList");
String[] tableList = (String[])reportInfo.get("tableList");
String[] tableColList = (String[])reportInfo.get("tableColList");
String[] widthList = (String[])reportInfo.get("widthList");
//判断生成数据是否为空
if(tableList == null || tableList.length < 0){
System.out.println("没有导出数据");
}
//生成PDF文档
Document document = new Document(PageSize.A4, 36,36,36,36);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
String fileTitle = (String) reportInfo.get("title");
if ("".equals(fileTitle)) {
fileTitle = "export";
}
//设置文件响应信息
String showFileName = URLEncoder.encode(fileTitle + ".pdf", "UTF-8");
showFileName = new String(showFileName.getBytes("iso8859-1"), "gb2312");
//定义输出类型
response.reset();
response.setContentType("application/pdf");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-disposition", "attachment; filename="+ new String(showFileName.getBytes("gb2312"), "iso8859-1"));
PdfWriter.getInstance(document, bos);
//添加页眉
//HeaderFooter headerFooter = new HeaderFooter(new Phrase(),true);
//headerFooter.setBorder(Rectangle.NO_BORDER);
//headerFooter.setAlignment(Element.ALIGN_CENTER);
//document.setHeader(headerFooter);
//添加页脚
//HeaderFooter footer = new HeaderFooter(new Phrase("第 ",ReportFontFactory.getFontChinese(Font_Type.CONTENT)),new Phrase(" 页",ReportFontFactory.getFontChinese(Font_Type.CONTENT)));
HeaderFooter footer = new HeaderFooter(new Phrase("第 ",ReportFontFactory.getFontCambodia(Font_Type.CONTENT)),new Phrase(" 页",ReportFontFactory.getFontCambodia(Font_Type.CONTENT)));
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);
//打开doc
document.open();
// PdfPTable table = null;
// PdfPCell cell =null; // 不能同时跨行跨列
Table table = null;
Cell cell = null; // 能同时跨行跨列
Paragraph paragraph = null;
for (int i = 0; i < tableColList.length; i++) {
String colInfo = tableColList[i];
String colStr = colInfo.indexOf("#PAGINATION#") >= 0 ? colInfo.substring(0,colInfo.indexOf("#PAGINATION#")) : colInfo;
colStr = colStr.indexOf("#NOBORDER#") >= 0 ? colStr.substring(0,colStr.indexOf("#PAGINATION#")) : colStr;
int col = Integer.parseInt(colStr);
boolean flag = false; // 判断是否存在图片
if (tableCaptionList.length > 0) {
//添加标题
//paragraph = new Paragraph(""+tableCaptionList[i].replaceAll("#IMG#", ""),ReportFontFactory.getFontChinese(Font_Type.TITLE));
paragraph = new Paragraph(""+tableCaptionList[i].replaceAll("#IMG#", ""),ReportFontFactory.getFontCambodia(Font_Type.TITLE));
paragraph.setAlignment(Paragraph.ALIGN_CENTER);
paragraph.setSpacingAfter(4);
paragraph.setSpacingBefore(10);
document.add(paragraph);
flag = tableCaptionList[i].indexOf("#IMG#") >= 0 ? true : false;
}
if (col > 0) {
// table = new PdfPTable(col);
// table.setWidthPercentage(98f);// 设置table宽度所占百分比
// table.setHeaderRows(0);// 0:可导出一行
// table.setHorizontalAlignment(Element.ALIGN_CENTER);
// table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
// -----
table = new Table(col);
table.setWidth(100f);
table.setBorder(0);
table.setAutoFillEmptyCells(true);
table.setPadding(2);
// table.setAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
if(widthList.length>i)// 说明:设置表格第一行所有列的width属性
{
String[] width = widthList[i].split(",");
if (width.length > 0 ) {
int [] ai = new int[width.length];
for (int j = 0; j < width.length; j++) {
if (!"".equals(width[j].trim())) {
ai[j] = Integer.parseInt(width[j]);
}
}
table.setWidths(ai); // 设置表格Cell的宽度,注意列的数量
}
}
String[] rows = null;
Object[][] cellInfo = null;
for (int j = 0; j < tableList.length; j++) {
if (i == j) {
rows = tableList[j].split("#ROW#");
for (int k = 0; k < rows.length; k++) {
String cells[] = rows[k].split("#TD#");
if (cellInfo == null) {
cellInfo = new Object[rows.length][cells.length];
}
cellInfo[k] = cells;
}
//生成PDF数据
for(int k=0;k<cellInfo.length;k++){
Object[] datapdf=cellInfo[k];
// if (datapdf.length==1) {
// String e = URLEncoder.encode(datapdf[0].toString() , "utf-8").replaceAll("%C2%A0", "");
// e = URLDecoder.decode(e , "utf-8");
// if ("".equals("")) {
// break;
// }
// }
for (int l = 0; l < datapdf.length; l++) {
if (flag) {
String url = datapdf[l].toString().trim(); // http 形式的url
if (!"".equals(url)) {
// 转换成绝对路径得url
// String path = request.getSession().getServletContext().getRealPath("/") + "temp" + "/" + url.substring(url.lastIndexOf('/')+1);
// Image img = Image.getInstance(URLDecoder.decode(path,"utf-8"));
Image img = Image.getInstance(URLDecoder.decode(datapdf[l].toString().trim(),"utf-8"));
// 设置图片的对齐方式
img.setAlignment(1);
// 设置图片的绝对宽度和高度
img.scaleAbsoluteWidth(400);
img.scaleAbsoluteHeight(400);
document.add(img);
document.newPage();
}
}else {
String value = datapdf[l].toString().indexOf("#COLSPAN#") >= 0 ? datapdf[l].toString().substring(0,datapdf[l].toString().indexOf("#COLSPAN#")) : datapdf[l].toString();
value = value.indexOf("#ROWSPAN#") >= 0 ? value.substring(0,value.indexOf("#ROWSPAN#")) : value;
value = value.indexOf("#ALIGN#") >= 0 ? value.substring(value.indexOf("#ALIGN#")+7) : value;
value = value.indexOf("#VALIGN#") >= 0 ? value.substring(value.indexOf("#VALIGN#")+8) : value;
//paragraph=new Paragraph(value.trim() , ReportFontFactory.getFontChinese(Font_Type.CONTENT));
paragraph=new Paragraph(value.trim() , ReportFontFactory.getFontCambodia(Font_Type.CONTENT));
// cell= new PdfPCell(paragraph);
cell= new Cell(paragraph);
if (colInfo.indexOf("#NOBORDER#") >= 0) {
cell.setBorder(0);
}
cellStyleConsole(cell , datapdf[l].toString());
table.addCell(cell);
}
}
}
}
}
if (colInfo.indexOf("#PAGINATION#") >= 0) {
table.deleteLastRow();
}
if (flag) {
table.deleteLastRow();
}
//添加table到Document对象中
document.add(table);
if (colInfo.indexOf("#PAGINATION#") >= 0) {
document.newPage();
}
}
}
//关闭document
document.close();
//生成pdf文档品并响应客户端
response.setContentLength(bos.size());
ServletOutputStream out = response.getOutputStream();
response.setContentLength(bos.size());
bos.writeTo(out);
out.flush();
out.close();
bos.flush();
bos.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (document.isOpen()) {
//关闭document
document.close();
}
}
}
/**
*
* Cell样式控制:跨行、跨列、居中
* 说明:不能同时跨行跨列
* @param cell
* @param context
*/
// public void cellStyleConsole(PdfPCell cell, String context) {
public void cellStyleConsole(Cell cell, String context) {
// 默认
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中
// cell.setNoWrap(false); // 自动换行
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
int colspan = 0;
int rowspan = 0;
if (context.indexOf("#ROWSPAN#") >= 0 && context.indexOf("#COLSPAN#") >= 0) {// 跨行且跨列
colspan = Integer.parseInt(context.substring(context.indexOf("#COLSPAN#")+9).trim());
rowspan = Integer.parseInt(context.substring(context.indexOf("#ROWSPAN#")+9 , context.indexOf("#COLSPAN#")).trim());
cell.setRowspan(rowspan);
cell.setColspan(colspan);
}else if (context.indexOf("#ROWSPAN#") >= 0) {// 跨行
rowspan = Integer.parseInt(context.substring(context.indexOf("#ROWSPAN#")+9).trim());
cell.setRowspan(rowspan);
}else if (context.indexOf("#COLSPAN#") >= 0) {// 跨列
colspan = Integer.parseInt(context.substring(context.indexOf("#COLSPAN#")+9).trim());
cell.setColspan(colspan);
}
// 位置设置:居中、右、左对齐
if (context.indexOf("#ALIGN#") >=0) {
String align = context.substring(0, context.indexOf("#ALIGN#")).trim();
if ("right".equals(align)) {
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
}else if ("left".equals(align)) {
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
}else if ("center".equals(align)) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
}
// 垂直对齐方式:
if (context.indexOf("#VALIGN#") >=0) {
String vAlign = context.substring(context.indexOf("#ALIGN#")>=0?(context.indexOf("#ALIGN#")+7):0, context.indexOf("#VALIGN#")).trim();
if ("top".equals(vAlign)) {
cell.setVerticalAlignment(Element.ALIGN_TOP);
}else if ("bottom".equals(vAlign)) {
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
}else if ("middle".equals(vAlign)) {
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}
}
}
}