JavaScript+Java實現HTML頁面轉為PDF檔案儲存的方法_javascript技巧

來源:互聯網
上載者:User

需求是一個匯出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)); //寫入資料       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資料轉換為Blobfunction 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包(官方下載地址:https://sourceforge.net/projects/itext/)

@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"進階"特性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.