将html页面保存成图片,图片写入pdf的实现方法(推

需求是一个导出pdf的功能,多方奔走终于实现了,走了不少弯路,而且怀疑现在这个方法仍是弯的。

有个jsPDF 插件可以在前端直接生成pdf,很简便,但不支持IE。

前端:

首先引入  html2canvas.js

html2canvas(document.body, { //截图对象 //此处可配置详细参数 onrendered: function(canvas) { //渲染完成回调canvas canvas.id = "mycanvas"; // 生成base64图片数据 var dataUrl = canvas.toDataURL('image/png'); //指定格式,也可不带参数 var formData = new FormData(); //模拟表单对象 formData.append("imgData", convertBase64UrlToBlob(dataUrl), "123.png"); //写入数据 var xhr = new XMLHttpRequest(); //数据传输方法 xhr.open("POST", "../bulletin/exportPdf"); //配置传输方式及地址 xhr.send(formData); xhr.onreadystatechange = function(){ //回调函数 if(xhr.readyState == 4){ if (xhr.status == 200) { var back = JSON.parse(xhr.responseText); if(back.success == true){ alertBox({content: 'Pdf导出成功!',lock: true,drag: false,ok: true}); }else{ alertBox({content: 'Pdf导出失败!',lock: true,drag: false,ok: true}); } } } }; } }); //将以base64的图片url数据转换为Blob function convertBase64UrlToBlob(urlData){ //去掉url的头,并转换为byte var bytes=window.atob(urlData.split(',')[1]); //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob( [ab] , {type : 'image/png'}); }

兼容性:Firefox 3.5+, Chrome, Opera, IE10+

不支持:iframe,浏览器插件,Flash

跨域图片需要在跨域服务器header加上允许跨域请求

access-control-allow-origin: *  access-control-allow-credentials: true

svg图片不能直接支持,已经有补丁包了,不过我没有试过。

IE9不支持FormData数据格式,也不支持Blob,这种情况下将canvas生成的64base字符串去掉url头之后直接传给后台,后台接收之后:

String base64 = Img.split(",")[1]; BASE64Decoder decode = new BASE64Decoder(); byte[] imgByte = decode.decodeBuffer(base64);

后端:

导入 itext jar包

@RequestMapping("/exportPdf") public @ResponseBody void exportPdf(MultipartHttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { ResultData result = new ResultData(); //自定义结果格式 String filePath = "c:\\exportPdf2.pdf"; String imagePath = "c:\\exportImg2.bmp"; Document document = new Document(); try{ Map getMap = request.getFileMap(); MultipartFile mfile = (MultipartFile) getMap.get("imgData"); //获取数据 InputStream file = mfile.getInputStream(); byte[] fileByte = FileCopyUtils.copyToByteArray(file); FileImageOutputStream imageOutput = new FileImageOutputStream(new File(imagePath));//打开输入流 imageOutput.write(fileByte, 0, fileByte.length);//生成本地图片文件 imageOutput.close(); PdfWriter.getInstance(document, new FileOutputStream(filePath)); //itextpdf文件 // document.setPageSize(PageSize.A2); document.open(); document.add(new Paragraph("JUST TEST ...")); Image image = Image.getInstance(imagePath); //itext-pdf-image float heigth = image.getHeight(); float width = image.getWidth(); int percent = getPercent2(heigth, width); //按比例缩小图片 image.setAlignment(Image.MIDDLE); image.scalePercent(percent+3); document.add(image); document.close(); result.setSuccess(true); operatelogService.addOperateLogInfo(request, "导出成功:成功导出简报Pdf"); }catch (DocumentException de) { System.err.println(de.getMessage()); } catch (Exception e) { e.printStackTrace(); result.setSuccess(false); result.setErrorMessage(e.toString()); try { operatelogService.addOperateLogError(request, "导出失败:服务器异常"); } catch (Exception e1) { e1.printStackTrace(); } } response.getWriter().print(JSONObject.fromObject(result).toString()); } private static int getPercent2(float h, float w) { int p = 0; float p2 = 0.0f; p2 = 530 / w * 100; p = Math.round(p2); return p; }

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。

处理速度快,支持很多PDF"高级"特性。

但是itext出错的时候不会报错,直接跳过去,回头看pdf文档损坏,找不到出错原因,真是急死人。

最后感谢网络上有关的博文和贴子以及百度搜索。

以上这篇将html页面保存成图片,图片写入pdf的实现方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjxgp.html