@RequestMapping(value = "/exportPdf.do", method = RequestMethod.POST) public void exportPdf(HttpServletRequest request, HttpServletResponse response) throws DocumentException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String fileName=""; //PdfWriter pdfWriter=null; //字体格式设置 BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font FontChinese=new Font(bfChinese,10,Font.NORMAL); //1创建document对象 Rectangle rectPageSize=new Rectangle(PageSize.A4); //下面代码设置页面横置 //创建document对象并指定边框 Document doc=new Document(rectPageSize,80,80,80,80); Document document=new Document(); fileName ="平台更新公告详情"+DateUtil.generateStandardDateTimeFormat2(new Date()) + ".pdf"; //response.setContentType("application/pdf"); //fileName=new String(fileName.getBytes(),"UTF-8"); //response.setHeader("Content-disposition","attachment; FileName="+fileName); ByteArrayOutputStream bos= new ByteArrayOutputStream(); //OutputStream out=response.getOutputStream(); //buffer.writeTo(out); PdfWriter.getInstance(document,bos); //buffer.close(); //out.flush(); document.open(); //创建表格 PdfPTable table = new PdfPTable(3); table.addCell(new Paragraph("内容",FontChinese)); table.addCell(new Paragraph("时间",FontChinese)); table.addCell(new Paragraph("创建人",FontChinese)); // table.addCell(new Paragraph("告警次数",FontChinese)); // table.addCell(new Paragraph("合格率",FontChinese)); //////// Notice notice =new Notice(); List<Notice> hjllist=noticeService.queryPage(notice); SimpleDateFormat datafDateFormat=new SimpleDateFormat("yyyy-MM-dd"); ////// for(int i = 0 ; i < hjllist.size();i++){ table.addCell(new Paragraph(hjllist.get(i).getNotice_content(),FontChinese)); table.addCell(new Paragraph(datafDateFormat.format(hjllist.get(i).getNotice_time()),FontChinese)); table.addCell(new Paragraph(hjllist.get(i).getCreateUser(),FontChinese)); // table.addCell(new Paragraph(hjllist.get(i).getAlarmtravel().toString(),FontChinese)); // table.addCell(new Paragraph(hjllist.get(i).getQualifiedrate(),FontChinese)); } document.add(table); document.close(); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/pdf"); response.setContentLength(bos.size()); OutputStream out1=response.getOutputStream(); bos.writeTo(out1); out1.flush(); }
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.9</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
//导出pdf,点击导出按钮触发此事件 function exportPdf(){ var form = $("<form method=‘post‘></form>"); form.attr("action",getRootPath()+"/sy/notice/exportPdf.do"); form.appendTo("body").submit(); }
效果图:
:
原文:http://www.cnblogs.com/ZC987053660/p/6380687.html