国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

將html頁面保存成圖片,圖片寫入pdf的實現(xiàn)方法(推薦)

2019-11-20 08:59:32
字體:
供稿:網(wǎng)友

需求是一個導(dǎo)出pdf的功能,多方奔走終于實現(xiàn)了,走了不少彎路,而且懷疑現(xiàn)在這個方法仍是彎的。

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

前端:

首先引入  html2canvas.js

html2canvas(document.body, { //截圖對象     //此處可配置詳細參數(shù)     onrendered: function(canvas) { //渲染完成回調(diào)canvas       canvas.id = "mycanvas";        // 生成base64圖片數(shù)據(jù)       var dataUrl = canvas.toDataURL('image/png');  //指定格式,也可不帶參數(shù)       var formData = new FormData(); //模擬表單對象       formData.append("imgData", convertBase64UrlToBlob(dataUrl), "123.png"); //寫入數(shù)據(jù)       var xhr = new XMLHttpRequest(); //數(shù)據(jù)傳輸方法       xhr.open("POST", "../bulletin/exportPdf"); //配置傳輸方式及地址       xhr.send(formData);       xhr.onreadystatechange = function(){ //回調(diào)函數(shù)         if(xhr.readyState == 4){            if (xhr.status == 200) {               var back = JSON.parse(xhr.responseText);               if(back.success == true){                 alertBox({content: 'Pdf導(dǎo)出成功!',lock: true,drag: false,ok: true});               }else{                 alertBox({content: 'Pdf導(dǎo)出失敗!',lock: true,drag: false,ok: true});               }            }         }       };     }});   //將以base64的圖片url數(shù)據(jù)轉(zhuǎn)換為Blobfunction convertBase64UrlToBlob(urlData){  //去掉url的頭,并轉(zhuǎn)換為byte  var bytes=window.atob(urlData.split(',')[1]);      //處理異常,將ascii碼小于0的轉(zhuǎn)換為大于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,瀏覽器插件,F(xiàn)lash

跨域圖片需要在跨域服務(wù)器header加上允許跨域請求

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

svg圖片不能直接支持,已經(jīng)有補丁包了,不過我沒有試過。

IE9不支持FormData數(shù)據(jù)格式,也不支持Blob,這種情況下將canvas生成的64base字符串去掉url頭之后直接傳給后臺,后臺接收之后:

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

后端:

導(dǎo)入 itext jar包

 

@RequestMapping("/exportPdf")public @ResponseBody void exportPdf(MultipartHttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {  ResultData result = new ResultData();  //自定義結(jié)果格式  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"); //獲取數(shù)據(jù)    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, "導(dǎo)出成功:成功導(dǎo)出簡報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, "導(dǎo)出失敗:服務(wù)器異常");    } 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文檔損壞,找不到出錯原因,真是急死人。

最后感謝網(wǎng)絡(luò)上有關(guān)的博文和貼子以及百度搜索。

以上這篇將html頁面保存成圖片,圖片寫入pdf的實現(xiàn)方法(推薦)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新源县| 隆子县| 藁城市| 通江县| 迭部县| 莱州市| 玉环县| 遵义县| 象山县| 枣阳市| 航空| 库车县| 凉山| 冕宁县| 大竹县| 堆龙德庆县| 纳雍县| 阳谷县| 定远县| 麦盖提县| 清丰县| 宁海县| 耒阳市| 通辽市| 泗洪县| 邛崃市| 馆陶县| 永吉县| 无极县| 衡阳县| 漳浦县| 车致| 南雄市| 莱芜市| 顺平县| 云梦县| 江油市| 贡觉县| 天等县| 林口县| 莱阳市|