首页>代码>使用jfreechart和itext实现导出报表和表格到pdf文档>/PdDFExportDemo/src/com/ptengine/web/datacenter/csv/ExportPDF.java
package com.ptengine.web.datacenter.csv; import java.awt.Color; import java.awt.Font; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.ui.RectangleInsets; import com.itextpdf.text.BadElementException; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.ptengine.conf.Configure; import com.ptengine.data.Site; import com.ptengine.factory.BeansFactory; import com.ptengine.logic.SiteHandlerAction; import com.ptengine.util.AES; import com.ptengine.util.ComUtil; import com.ptengine.util.StringTools; import com.ptengine.util.UTFEncodingUtil; import com.ptengine.web.datacenter.csv.ReportFontFactory.Font_Type; public class ExportPDF extends HttpServlet{ private static final long serialVersionUID = 1L; private String encoding="UTF-8"; protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException{ request.setCharacterEncoding(encoding); response.setContentType("text/html;charset=gb2312"); List<List<String>> headList = ExportPDF.getHeadList(参数1,参数2,参数3,参数4,参数5,参数6);//获得头数据 List<String[]> list=new ArrayList<String[]>();//获得body数据 list=//获得body数据 大家可以写为死数据 不从数据库中取值 但要注意格式正确 //设置文件响应信息 String showFileName =URLEncoder.encode("导出实例.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")); //生成PDF文档 Document document=new Document(PageSize.A4, 50, 50, 50, 50); ByteArrayOutputStream bos= new ByteArrayOutputStream(); try { PdfWriter.getInstance(document, bos); } catch (DocumentException e1) { e1.printStackTrace(); } //打开doc document.open(); //添加标题 try { Paragraph paragraph=new Paragraph(tfilename,ReportFontFactory.getFontChinese(Font_Type.HEADER)); paragraph.setAlignment(Paragraph.ALIGN_CENTER); document.add(paragraph); document.add(Chunk.NEWLINE); } catch (DocumentException e1) { e1.printStackTrace(); } //构建一个表格 PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100f); table.setSpacingBefore(3f); table.getDefaultCell().setBorder(0);//设置表格默认为无边框 PdfPCell cell =null; //生成表头 if (headList != null && headList.size() > 0) { for (int i =0;i<headList.size();i++) { List<String> rowList = headList.get(i); for(int j=0;j<rowList.size();j++){ try { cell= new PdfPCell(new Paragraph(rowList.get(j),ReportFontFactory.getFontChinese(Font_Type.HEADER))); } catch (DocumentException e) { System.out.println("生成表头error"); e.printStackTrace(); } table.addCell(cell); } } } PdfPTable table1 = new PdfPTable(11); table1.setWidthPercentage(100f); table1.getDefaultCell().setBorder(0);//设置表格默认为无边框 PdfPCell cell1 =null; if (list != null && list.size() > 0) { for(int i=0;i<list.size();i++){ String[] arr= list.get(i); for(int j=0;j<arr.length;j++){ try { cell1= new PdfPCell(new Paragraph(""+arr[j],ReportFontFactory.getFontChinese(Font_Type.CONTENT))); } catch (DocumentException e) { System.out.println("生成体error"); e.printStackTrace(); } table1.addCell(cell1); } } } //添加table到Document对象中 //这儿是取值获取数据,这是传入报表的数据 List<String> list1=new ArrayList<String>(); List<String> list2=new ArrayList<String>(); for(int i=0;i<list.size();i++){ if(i==0){ }else{ list1.add(list.get(i)[1]); list2.add(list.get(i)[3]); } } //这部分是用的jfreechart的画图 JFreeChart chart = createChart(createDataset(list1,list2)); BufferedImage bi = chart.createBufferedImage(600, 600); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ImageIO.write(bi,"png", out1); byte[] data = out1.toByteArray(); Image image; try { image = Image.getInstance(data); image.scalePercent(90); image.setAlignment(Image.MIDDLE); // 图片位置 PdfPTable imageTable = new PdfPTable(2); imageTable.setWidthPercentage(60); document.add(table); document.add(table1); document.add(image); document.add(imageTable); } catch (BadElementException e) { System.out.println("添加图片error"); } catch (DocumentException e) { System.out.println("ai"); } //关闭document document.close(); //生成pdf文档品并响应客户端 response.setContentLength(bos.size()); ServletOutputStream out = response.getOutputStream(); response.setContentLength(bos.size()); bos.writeTo(out); out.close(); out.flush(); bos.close(); bos.flush(); } /** * @author artisamSplit * @return List<List<String>> * @since 14.04.28 */ public static List<List<String>> getHeadList(String csvname,String rangeparam,String filterparam,String rangetype,String starttime,String endtime){ List<List<String>> headList = new ArrayList<List<String>>(); List<String> secondList1 = new ArrayList<String>(); secondList1.add("统计站点名称:"); secondList1.add("飞鹤乳业"); List<String> secondList2 = new ArrayList<String>(); secondList2.add("统计站点范围:"); secondList2.add("www.feihe.com"); List<String> secondList3 = new ArrayList<String>(); secondList3.add("过滤器类型:"); secondList3.add(filterparam); List<String> secondList4 = new ArrayList<String>(); secondList4.add("合参页面:"); secondList4.add("www.feihe.com"); List<String> secondList5 = new ArrayList<String>(); secondList4.add("开始时间:"); secondList4.add(starttime); List<String> secondList6 = new ArrayList<String>(); secondList4.add("结束时间:"); secondList4.add(endtime); headList.add(secondList1); headList.add(secondList2); headList.add(secondList3); headList.add(secondList4); headList.add(secondList5); headList.add(secondList6); return headList; } /** * @author artisamSplit * @param XYDataset */ private static XYDataset createDataset(List<String> list1,List<String> list2) { TimeSeries s1 = new TimeSeries("FW"); for(int i=1;i<=12;i++){ if(i%12==0){ s1.add(new Month(12, 2005+i/12-1), Integer.parseInt(list1.get(i-1))); }else{ s1.add(new Month(i%12, 2005+i/12), Integer.parseInt(list1.get(i-1))); } } TimeSeries s2 = new TimeSeries("PV"); for(int i=1;i<=12;i++){ if(i%12==0){ s2.add(new Month(12, 2005+i/12-1), Integer.parseInt(list2.get(i-1))); }else{ s2.add(new Month(i%12, 2005+i/12), Integer.parseInt(list2.get(i-1))); } } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); return dataset; } /** * @author artisamSplit * @param dataset * @return chart */ private static JFreeChart createChart(XYDataset dataset) { StandardChartTheme sct = new StandardChartTheme("CN"); sct.setExtraLargeFont(new Font("隶书", Font.BOLD, 8)); sct.setRegularFont(new Font("隶书", Font.BOLD, 8)); sct.setLargeFont(new Font("隶书", Font.BOLD, 8)); ChartFactory.setChartTheme(sct); JFreeChart chart = ChartFactory.createTimeSeriesChart( "访问量对比曲线图", // title "PV", // x-axis label "访问量", // y-axis label dataset, // data true, // create legend? true, // generate tooltips? false // generate URLs? ); try{ chart.setBackgroundPaint(Color.white); XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setDrawSeriesLineAsPath(true); } DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy")); }catch(Exception e){ System.out.println("error"); } return chart; } }