本文概述了如何通过Itext生成包含表格的pdf文档,包含简单的表格格式设置,迭代添加表格数据等实践。解决了中文字不能显示或显示乱码的问题。最后输出到HttpResponse流中供用户下载。
本文提供的示例较为直观简单,仅做抛砖引玉之用。
jar包下载
itextpdf-5.3.2.jar
itext-asian.jar(解决中文显示)
Itext使用工具类
/**
* @author zhangt
* @date 创建时间:2017年5月27日 下午16:07:00
*/
package test.tools;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPRow;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.jfinal.plugin.activerecord.Record;
public class ToolExportPdf {
/**
* 获取输出流
* @param list
* @param title
* @param headers
* @param columns
* @return
* @throws DocumentException
* @throws IOException
*/
public static ByteArrayOutputStream getOutputStream(List<Record> list, String title, String[] headers, String[] columns) throws DocumentException, IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//表头列数需与字段列数相同
if(headers.length!=columns.length){
return baos;
}
//文档对象
Document document = new Document();
//定义输出对象,将文档对象填装
PdfWriter writer = PdfWriter.getInstance(document, baos);
//中文字兼容
BaseFont baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont);
document.open();
//设定文档标题
document.add(new Paragraph(title,font));
//获取文档列数
int colNum = headers.length;
//新建表格
PdfPTable table = new PdfPTable(colNum);
table.setWidthPercentage(100); // 宽度100%填充
table.setSpacingBefore(10f); // 前间距
table.setSpacingAfter(10f); // 后间距
//设置文档行
List<PdfPRow> listRow = table.getRows();
//设置列宽
float[] columnWidths = {3f, 3f };
table.setWidths(columnWidths);
//表头行
PdfPCell cellsH[]= new PdfPCell[colNum];
PdfPRow rowH = new PdfPRow(cellsH);
for(int i=0;i<headers.length;i++){
cellsH[i] = new PdfPCell(new Paragraph(headers[i],font));
cellsH[i].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cellsH[i].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
}
listRow.add(rowH);
//数据行
for(Record item:list){
PdfPCell cells[]= new PdfPCell[colNum];
PdfPRow row = new PdfPRow(cells);
for(int i=0;i<headers.length;i++){
if(item.get(columns[i])!=null){
cells[i] = new PdfPCell(new Paragraph(String.valueOf(item.get(columns[i])),font));
}else{
cells[i] = new PdfPCell(new Paragraph("--",font));
}
}
listRow.add(row);
}
document.add(table);
document.close();
return baos;
}
/**
* 生成包含时间戳的文件名称
* @param prefix
* @param postfix
* @return
*/
public static String generateDownLoadName(String prefix, String postfix){
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return prefix + sdf.format(now) + "." + postfix;
}
}
生成pdf文档并输入到HttpResponse
//数据列表
List<Record> list = {name:"测试名称", count:64};
String[] columns = {"name","count"};
String[] headers = {"名称","数量"};
try {
ByteArrayOutputStream baos = ToolExportPdf.getOutputStream(list, "统计列表", headers, columns);
//获取HttpResponse
HttpServletResponse response = this.getResponse();
response.addHeader("Content-disposition", "inline; filename=" + ToolExportPdf.generateDownLoadName("num_", "pdf"));
response.setContentType("application/pdf");
response.setContentLength(baos.size());
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
renderNull();
} catch (IOException | DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
经测试可以正常使用。