首页 > 代码库 > 使用flying-saucer,利用HTML来生成PDF文件(裴东辉)
使用flying-saucer,利用HTML来生成PDF文件(裴东辉)
1、导入maven依赖
<flyingSaucer.version>9.1.0</flyingSaucer.version>
<!-- flying-saucer -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>${flyingSaucer.version}</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-core</artifactId>
<version>${flyingSaucer.version}</version>
</dependency>
2、利用Html来导出简单的PDF文件
@RequestMapping("/pdfLoad") public void pdfLoad(@RequestParam("pdfHtmlData")String pdfHtmlData,@RequestParam("fileName")String fileName,@RequestParam("borswerInfo")String borswerInfo, HttpServletRequest request,HttpServletResponse response){ log.info("pdfHtmlData:"+pdfHtmlData+";fileName:"+fileName+";borswerInfo:"+borswerInfo); InputStream in=null; OutputStream out=null; try { String tempPdfFile=FileUploadRestController.class.getResource("/").getPath(); tempPdfFile=tempPdfFile+"/public/upload/"+System.currentTimeMillis()+".pdf"; File dest=new File(tempPdfFile); //检测是否存在目录 if(!dest.getParentFile().exists()){ dest.getParentFile().mkdirs(); } FileOutputStream tempout=new FileOutputStream(tempPdfFile); //构建一个html页面(前台通过js来控制传递) //根据Html页面来构建一个Document DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(pdfHtmlData.getBytes("UTF-8"))); //根据Document来填充iTextRenderer ITextRenderer iTextRenderer=new ITextRenderer(); iTextRenderer.setDocument(doc, null); ITextFontResolver fontResolver = iTextRenderer.getFontResolver(); String pdfFontPath=FileUploadRestController.class.getResource("/plugins/pdf-font/simsun.ttf").getPath();//request.getSession().getServletContext().getRealPath("upload/pdf/font"); fontResolver.addFont(pdfFontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); iTextRenderer.layout(); //利用iTextRenderer生成pdf文件 iTextRenderer.createPDF(tempout); tempout.flush(); tempout.close(); //文件下载 File downloadFile = new File(tempPdfFile); //文件名 JSONObject borswerInfoObj=JSONObject.parseObject(borswerInfo); if (null!=borswerInfoObj&&"ie".equals(borswerInfoObj.get("browser"))) { fileName=java.net.URLEncoder.encode(fileName, "UTF-8"); fileName=fileName.replace("+", "%20"); //IE下文件名称带空格会转换为加号 response.setHeader("charset", "charset=UTF-8"); } else { fileName=new String(fileName.getBytes(),Charset.forName("ISO8859-1")); response.setHeader("charset", "charset=ISO8859-1"); } //输出设置 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename="+fileName); response.setContentLengthLong(downloadFile.length()); in=new FileInputStream(downloadFile); out=response.getOutputStream(); IOUtils.copy(in,out); response.flushBuffer(); }catch (Exception e) { e.printStackTrace(); }finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
3、pdfHtmlData参数为
//导出PDF文件 $(‘body‘).delegate(".pdfLoad","click",function(){ WebIndex.queryParam.limit=10000; Logger.info(WebIndex.queryParam); $.ajax({type:‘post‘,url:webIface.rootUrl+‘/fileManager/list/‘,dataType: ‘json‘,data:WebIndex.queryParam}).done(function(data){ Logger.info(data); if(data.code==1){ var ifile=$(‘body‘).find(‘#load-pdf‘); var fileName="文件上传和下载列表.pdf"; //构造pdf打印html数据 var pdfHtmlData=http://www.mamicode.com/‘‘;"text/css">‘; pdfHtmlData+=‘ body{font-family:SimSun;margin: 5px;font-size:12px;text-align:center;}‘; pdfHtmlData+=‘ table{border:0;border-top:1px solid #000;border-left:1px solid #000;width:100%;line-height:20px}‘; pdfHtmlData+=‘ table thead{background-color:#EEE}‘; pdfHtmlData+=‘ table td{border:0;border-bottom:1px solid #000;border-right:1px solid #000;padding:5px;white-space:nowrap}‘; pdfHtmlData+=‘ .title{padding-bottom:20px;font-size:16px;text-align:center;width:100%;line-height:20px;}‘; pdfHtmlData+=‘ .fl{padding-left:20px;text-align:left;}‘; pdfHtmlData+=‘ @page{size:297mm 210mm;}‘; pdfHtmlData+=‘ </style>‘; pdfHtmlData+=‘ </head>‘; pdfHtmlData+=‘ <body>‘; pdfHtmlData+=‘ <div class="title">文件上传和下载列表统计(第1页)</div>‘; pdfHtmlData+=‘ <table cellpadding="0px" cellspacing="0px" >‘; pdfHtmlData+=‘ <thead><td width="10%">标号</td><td width="40%">文件名</td><td width="15%">上传人</td><td width="20%">上传时间</td><td width="15%">下载次数</td></thead>‘; $.each(data.list,function(num,detail){ if(num!=0&&num%20==0){ pdfHtmlData+=‘ </table>‘; pdfHtmlData+=‘ <div style="height:1px;"></div>‘; pdfHtmlData+=‘ <div class="title">文件上传和下载列表统计(第‘+(num/20+1)+‘页)</div>‘; pdfHtmlData+=‘ <table cellpadding="0px" cellspacing="0px" >‘; pdfHtmlData+=‘ <thead><td width="10%">标号</td><td width="40%">文件名</td><td width="15%">上传人</td><td width="20%">上传时间</td><td width="15%">下载次数</td></thead>‘; } pdfHtmlData+=‘<tr><td>‘+(num+1)+‘</td><td class="fl">‘+detail.fileName+‘</td><td>‘+detail.uploader+‘</td><td>‘+detail.loadDate+‘</td><td>‘+detail.downLoadCount+‘</td></tr>‘; }); pdfHtmlData+=‘ </table>‘; pdfHtmlData+=‘ </body>‘; pdfHtmlData+=‘</html>‘; var borswerInfo=JSON.stringify(getBrowserInfo()); var time=Date.parse(new Date())/1000; if(ifile.length==0){ var loadhtml=‘‘; loadhtml+=‘<form method="post" id="load-pdf" action="‘+webIface.rootUrl+‘/fileUpload/pdfLoad/" style="display:none">‘; loadhtml+=‘ <input class="load-pdfHtmlData" name="pdfHtmlData" >‘; loadhtml+=‘ <input class="load-fileName" name="fileName" >‘; loadhtml+=‘ <input class="load-borswerInfo" name="borswerInfo" >‘; loadhtml+=‘ <input class="load-time" name="time" >‘; loadhtml+=‘</form>‘; $(‘body‘).append(loadhtml); ifile=$(‘body‘).find(‘#load-pdf‘); } ifile.find(‘.load-pdfHtmlData‘).attr("value",pdfHtmlData); ifile.find(‘.load-fileName‘).attr("value",fileName); ifile.find(‘.load-borswerInfo‘).attr("value",borswerInfo); ifile.find(‘.load-time‘).attr("value",time); ifile.submit(); } }).fail(function(erorEvent){ alert(erorEvent.statusText); }); WebIndex.queryParam.limit=8; });
4、预览pdf效果。
使用flying-saucer,利用HTML来生成PDF文件(裴东辉)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。