package com.exce;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
/**
* 导出PDF,弹出下载框.
* 使用的jar包: iText-2.1.7.jar
*/
public class ExportPDFAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ExportPDFAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
try {
//1:创建com.lowagie.text.Document的对象
Document document = new Document(PageSize.A4,20,20,20,20);
//2: 创建PdfWriter的对象去侦听上面创建的文档,并把这个文档写入到你定义的输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
//3: 打开文档
document.open();
//4: 添加内容到文档中
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFont = new Font(bfChinese, 20, Font.BOLD,Color.RED);
Font tontChinese = new Font(bfChinese, 12, Font.NORMAL);
document.add(new Paragraph("导出PDF文件数据如下",titleFont));
document.add(new Paragraph(" ",titleFont));
PdfPTable table = new PdfPTable(8);
for(int i=0;i<800;i++) {
if (i == 0) {
PdfPCell cell = new PdfPCell();
cell.setColspan(8);
cell.setBackgroundColor(new Color(120,120,120));
cell.addElement(new Paragraph("表格头" , new Font(bfChinese, 14, Font.BOLD,Color.GREEN)));
table.addCell(cell);
} else {
PdfPCell cell = new PdfPCell();
cell.setBorderColor(Color.BLUE);
cell.addElement(new Paragraph("内容"+i , tontChinese));
table.addCell(cell);
}
}
document.add(table);
//5: 关闭文档
document.close();
//设置为下载文件弹框,和文件名编码
response.setHeader("Content-disposition","attachment; filename=\""+new String("PDF文件".getBytes(), "ISO8859-1") +".pdf\"");
//设置文件大小
response.setContentLength(baos.size());
ServletOutputStream outputStream = response.getOutputStream();
//6: 将PDF文件输出到流中去.
baos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
//在web.xml配置<span style="font-family: Arial, Helvetica, sans-serif;">ExportPDFAction 该servlet </span>