Java 使用itext生成pdf以及下载
使用方法:
1.需要两个jar包:
iText-5.0.6.jar //必须使用该版本,否则缺少相关的方法
TextAsian.jar
//是为了文档中正常显示中文所必须引用的包
TextAsian.jar使用时并不是单纯的引入就可以了,还需要进一步处理该jar包,否则无法显示
(无奈当时没有保存那个解决方法的链接,所以以后要用正确的包的话,就去毕设项目下找该包)
2以下是一个完整的例子。
一、要生成pdf的jsp页面
<%@ page language="java" import="java.util.*,utils.*,entity.*,dao.*" pageEncoding="utf-8"%> <%@ include file="top.jsp" %> <% /*------------------------------操作记录-----------------------------------*/ DoOperation dp=new DoOperation(); Operation op=new Operation(); User user=(User) session.getAttribute("UserBean"); String IP=(String) session.getAttribute("IP"); op=dp.getOperation(IP, user.getId()+"", "舆情报告", "成功"); OperationCl oc=new OperationCl(); oc.addOperation(op); %> <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <meta charset="gbk"> <title>舆情报告</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="author" content="puyuetian qq632827168"> <meta name="renderer" content="webkit"> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link rel="stylesheet" href="./css/invatation/upload.css" /> <link rel="stylesheet" href="./css/invatation/default.css" /> <script charset="utf-8" src="./js/invatation/kindeditor-min.js"></script> <script charset="utf-8" src="./js/invatation/zh_CN.js"></script> <script charset="utf-8" src="./js/invatation/puyuetian.js"></script> <script language="javascript" type="text/javascript" src="./js/My97DatePicker/WdatePicker.js"></script> <link rel="stylesheet" href="./css/invatation/amazeui.min.css"> <link rel="stylesheet" href="./css/invatation/app.css"> <!--[if (gte IE 9)|!(IE)]><!--> <script src="./js/invatation/jquery.min.js"></script> <!--<![endif]--> <script src="./js/invatation/amazeui.min.js"></script> </head> <body> <style> .hook-mail-forgotpassword-a { font-size: 12px; display: block; text-align: right; } </style> <br> <div class="am-container"> <div class="am-container"> <div style="background-color: white;padding: 1.6rem;"> <style> .am-breadcrumb li { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 360px; } </style> <link rel="stylesheet" href="./css/invatation/edit.css"> <script> var editor; KindEditor.ready(function(K) { editor = K.create('textarea[name=content]', { width : '100%', height : '360px', resizeType : 1, allowPreviewEmoticons : false, allowImageUpload : false, items : [ 'source', '|', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'table', 'code', 'image', 'link', 'quickformat' ] }); }); </script> <a name="post"></a> <div class="am-container" style="background:white"> <form name="form_post" class="am-form am-form-horizontal" method="post" action="reportServlet"> <div class="text" style=" text-align:center;font-size:26px;">舆情报告</div> <br> <div class="am-form-group "> <input type="text" style="width:560px;" name="title" placeholder="舆情事件" value="" onfocus="readsortdiv('visible')" autocomplete="off"> <div id="readsortdiv" class="readsortdiv"></div> </div> <div class="am-form-group "> <input name="time" class="Wdate" type="text" placeholder="发生时间" onClick="WdatePicker()" style="width:220px;"> </div> <div class="am-form-group"> <select name="area" style="margin: 10px 0px;width:360px;"> <option value="0">发生地区</option> <option value='和平区'>和平区</option> <option value='南开区'>南开区</option> <option value='河东区'>河东区</option> <option value='河西区'>河西区</option> <option value='河北区'>河北区</option> <option value='红桥区'>红桥区</option> <option value='西青区'>西青区</option> <option value='塘沽区'>塘沽区</option> <option value='汉沽区'>汉沽区</option> <option value='东丽区'>东丽区</option> <option value='大港区'>大港区</option> <option value='津南区'>津南区</option> <option value='北辰区'>北辰区</option> <option value='武清区'>武清区</option> <option value='宝坻区'>宝坻区</option> <option value='宁河县'>宁河县</option> <option value='静海县'>静海县</option> <option value='蓟县'>蓟县</option> </select> </div> <div class="am-form-group"> <textarea name="summary" placeholder="舆情概述"></textarea> </div> <div class="am-form-group"> <textarea name="data" placeholder="相关数据"></textarea> </div> <div class="am-form-group"> <textarea name="result" placeholder="结论"></textarea> </div> <div class="am-form-group"> <textarea name="advise" placeholder="部门意见"></textarea> </div> <div class="am-form-group"> <input type="submit" class="am-btn am-btn-primary" value="生成PDF" /> </div> </form> </div> </div> </div> <link rel="stylesheet" href="./css/invatation/hdrive.css"> <script defer="defer"> var $USER = Array(); $USER['ID'] = "2"; $USER['USERNAME'] = "游客"; $USER['NICKNAME'] = "匿名游客"; $USER['QUANXIAN'] = "bbcode,download,lookread,lookuser,reply,search"; $USER['TIANDOU'] = "0"; $USER['JIFEN'] = "0"; $USER['QIANDAODAYS'] = "79"; $USER['QIANDAOTIME'] = "1452392237"; $USER['SEX'] = "机器人"; $USER['BIRTHDAY'] = "0"; $USER['MAIL'] = "632827168@qq.com"; $USER['QQ'] = "632827168"; $USER['PHONE'] = "保密"; $USER['SIGN'] = "系统用户组 - 游客"; $USER['FRIENDS'] = "_1_"; $USER['READLEVEL'] = "0"; var $GET = Array(); $GET['C'] = "edit"; $GET['TYPE'] = "read"; $GET['SORTID'] = "0"; var $SET = Array(); $SET['QIANDAOJIFEN'] = "10"; $SET['QIANDAOTIANDOU'] = "10"; var $QIANDAOED = 'FALSE'; function windowonscroll() { //页面滚动事件 //navmove(); } function loadinghere() { //页面加载至此事件 $newmessagenum = '492'; if ($newmessagenum != '') { $newmessagenum = parseInt($newmessagenum); $title = "您有新条新消息。"; document.getElementById("mf_m_new").style.visibility = 'visible'; document.getElementById("mf_m").title = $title; } if ($USER['ID'] != 2) { showxunzhang(); showuserlevelprogressbar(); } qiandao(0); } function loadcomplete() { //页面加载完成事件,异步数据驱动 var s = document.createElement('script'); s.src = 'http:\/\/tongji.hadsky.com\/tongji.php?domain=' + document.domain + '&allurl=' + encodeURIComponent(document.location); //alert(encodeURI(document.location)); document.getElementsByTagName('head')[0].appendChild(s); } try { loadinghere(); } catch (e) { //TODO handle the exception } window.onscroll = windowonscroll; //创建全局驱动框架 var cifrm = document.createElement('iframe'); cifrm.name = 'ifrm'; cifrm.id = 'ifrm'; cifrm.style.display = 'none'; document.getElementsByTagName('body')[0].appendChild(cifrm); window.onload = loadcomplete; </script> <script src="./js/invatation/upload.js"></script> <link rel="stylesheet" href="./css/invatation/footer.css" /> <div class="am-container"> <div style="background-color: white;padding: 1.6rem;"> <p class="am-text-center am-article-meta" style="padding-top:4.8rem;padding-bottom:1.6rem;"> 梦虽然遥不可及,但并不是不可能实现;只要坚持,就会离梦越来越近!</p> </div> </div> </body> </html>
二、处理请求的servlet
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.OperationCl; import dao.ReportCl; import entity.Operation; import entity.Report; import entity.User; import utils.DoOperation; import utils.DoPDF; import java.text.SimpleDateFormat; import java.util.Date; public class reportServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); /*------------------操作记录-------------------*/ DoOperation dp=new DoOperation(); Operation op=new Operation(); HttpSession session = request.getSession(); User user=(User) session.getAttribute("UserBean"); String IP=(String) session.getAttribute("IP"); op=dp.getOperation(IP, user.getId()+"", "舆情报告", "成功"); OperationCl oc=new OperationCl(); oc.addOperation(op); //前台接收数据 String title=request.getParameter("title"); String time=request.getParameter("time"); String area=request.getParameter("area"); String summary=request.getParameter("summary"); String data=request.getParameter("data"); String result=request.getParameter("result"); String advise=request.getParameter("advise"); //得到用户id int userID=user.getId(); //文档路径和命名 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式 String str=df.format(new Date());// new Date()为获取当前系统时间 String filePath="F://MyEclipseWorkspace2014//MyData//WebRoot//WEB-INF//report//"+str+"report.pdf"; String fileName=str+"report.pdf";//在文件名前加上时间,文件名不再重复 //生成pdf文档 DoPDF doPdf=new DoPDF();//生成pdf的类 doPdf.getPDF(filePath, title, time, area, summary, data, result, advise); } }
三、真正生成pdf文档的类DoPDF
package utils; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; public class DoPDF { public void getPDF(String filePath,String title,String time,String area, String summary,String data,String result,String advise) throws IOException{ Document document = new Document(PageSize.A4); try { try { PdfWriter.getInstance(document, new FileOutputStream(filePath)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } document.open(); BaseFont bfCN; Font fontCN ; bfCN = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", false); fontCN = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK); PdfPTable table = new PdfPTable(4); table.setTotalWidth(new float[]{66,84,66,84}); // 设置字体大小 PdfPCell cell = new PdfPCell(new Phrase("舆情报告",fontCN)); cell.setColspan(4); cell.setBorderWidth(0);//设置表格的边框宽度为0 cell.setMinimumHeight(30); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); PdfPCell cell1 = new PdfPCell(new Phrase("舆情事件",fontCN)); cell1.setColspan(1); cell1.setBorderWidth(1);//设置表格的边框宽度为0 cell1.setMinimumHeight(30); table.addCell(cell1); PdfPCell cell2 = new PdfPCell(new Phrase(title,fontCN)); cell2.setColspan(3); cell2.setBorderWidth(1);//设置表格的边框宽度为0 cell2.setMinimumHeight(30); table.addCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase("发生时间",fontCN)); cell3.setColspan(1); cell3.setBorderWidth(1);//设置表格的边框宽度为0 cell3.setMinimumHeight(30); table.addCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase(time,fontCN)); cell4.setColspan(1); cell4.setBorderWidth(1);//设置表格的边框宽度为0 cell4.setMinimumHeight(30); table.addCell(cell4); PdfPCell cell5 = new PdfPCell(new Phrase("发生地区",fontCN)); cell5.setColspan(1); cell5.setBorderWidth(1);//设置表格的边框宽度为0 cell5.setMinimumHeight(30); table.addCell(cell5); PdfPCell cell6 = new PdfPCell(new Phrase(area,fontCN)); cell6.setColspan(1); cell6.setBorderWidth(1);//设置表格的边框宽度为0 cell6.setMinimumHeight(30); table.addCell(cell6); PdfPCell cell7 = new PdfPCell(new Phrase("舆情概述",fontCN)); cell7.setColspan(4); cell7.setBorderWidth(1);//设置表格的边框宽度为0 cell7.setMinimumHeight(30); table.addCell(cell7); PdfPCell cell8 = new PdfPCell(new Phrase(summary,fontCN)); cell8.setColspan(4); cell8.setBorderWidth(1);//设置表格的边框宽度为0 cell8.setMinimumHeight(90); table.addCell(cell8); PdfPCell cell9 = new PdfPCell(new Phrase("相关数据",fontCN)); cell9.setColspan(4); cell9.setBorderWidth(1);//设置表格的边框宽度为0 cell9.setMinimumHeight(30); table.addCell(cell9); PdfPCell cell10 = new PdfPCell(new Phrase(data,fontCN)); cell10.setColspan(4); cell10.setBorderWidth(1);//设置表格的边框宽度为0 cell10.setMinimumHeight(90); table.addCell(cell10); PdfPCell cellA = new PdfPCell(new Phrase("结论",fontCN)); cellA.setColspan(4); cellA.setBorderWidth(1);//设置表格的边框宽度为0 cellA.setMinimumHeight(30); table.addCell(cellA); PdfPCell cellB = new PdfPCell(new Phrase("cell B",fontCN)); cellB.setColspan(4); cellB.setBorderWidth(1);//设置表格的边框宽度为0 cellB.setMinimumHeight(90); table.addCell(cellB); PdfPCell cellC = new PdfPCell(new Phrase(advise,fontCN)); cellC.setColspan(4); cellC.setBorderWidth(1);//设置表格的边框宽度为0 cellC.setMinimumHeight(30); table.addCell(cellC); PdfPCell cellD = new PdfPCell(new Phrase("cell D",fontCN)); cellD.setColspan(4); cellD.setBorderWidth(1);//设置表格的边框宽度为0 cellD.setMinimumHeight(90); table.addCell(cellD); PdfPCell cellE = new PdfPCell(new Phrase("领导意见",fontCN)); cellE.setColspan(2); cellE.setBorderWidth(1);//设置表格的边框宽度为0 cellE.setMinimumHeight(30); table.addCell(cellE); PdfPCell cellF = new PdfPCell(new Phrase("审批意见",fontCN)); cellF.setColspan(2); cellF.setBorderWidth(1);//设置表格的边框宽度为0 cellF.setMinimumHeight(30); table.addCell(cellF); PdfPCell cellM = new PdfPCell(new Phrase("",fontCN)); cellM.setColspan(2); cellM.setBorderWidth(1);//设置表格的边框宽度为0 cellM.setMinimumHeight(70); table.addCell(cellM); PdfPCell cellN = new PdfPCell(new Phrase("",fontCN)); cellN.setColspan(2); cellN.setBorderWidth(1);//设置表格的边框宽度为0 cellN.setMinimumHeight(70); table.addCell(cellN); document.add(table); }catch (DocumentException e) { e.printStackTrace(); } finally { document.close(); } } }
四、文档下载的servlet
package servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); /*-----------------接收文件名和文件路径-----------------------------------*/ String filename = request.getParameter("filename"); String path = request.getParameter("filepath"); //System.out.println(filename); response.setContentType(getServletContext().getMimeType(filename)); response.setHeader("Content-Disposition","attachment;filename="+filename); //String fullFileName=getServletContext().getRealPath("/download/"+filename); InputStream in=new FileInputStream(path); OutputStream out = response.getOutputStream(); //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while((len=in.read(buffer))>0){ //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } //关闭文件输入流 in.close(); //关闭输出流 out.close(); } }