2016-05-30 46 views
1

我在角度工作。我需要将我的JPG文件转换为base64。我使用帆布方法,我发现here。我有一个服务,调用每个图像url的其他服务,然后我需要打印这些images.My html文件不包含base64,这是因为日志说空白。我究竟做错了什么 ?jpg到base64 javascript

首先服务

.service('exportSrv', function ($cordovaPrinter, imgConvertToBase64) { 

    return { 
     prepareHtml: function (photos, itemsPerPage) { 

      //Some variables 

      switch (itemsPerPage) { 

      case 1: 
       subtitle = '1/page'; 
       head += style_100 + '</style></head>'; 
       body = '<body>'; 

       var toBase64fun = function (i) { 

        src = '../all/' + photos[i].src + '.jpg'; 

        imgConvertToBase64.toDataUrl(i, function (dataUri) { 

         console.log(dataUri); 

         if (!photos[i].iden) 
          recText = notRec; 
         if (photos[i].genre == "F") 
          icon = 'female-icon.png'; 
         else 
          icon = 'male-icon.png'; 

         var base64 = dataUri; 

         body += '<div class="container"><figure class="elements padding"><img src="' + base64 + '"alt="Den tin vrika"><figcaption><img class="icon" src="../img/all/' + icon + '"><p>Author: <i>' + photos[i].author + '</i>' + recText + '</p></figcaption></figure></div>'; 

         i++; 
         if (i <= photos.length) 
          toBase64fun(i); 
         else { 
          body += '</body>'; 
          htmlFile = '<html>' + head + body + '</html>'; 
          console.log(htmlFile); 
         } 


        }) 

       } 

       toBase64fun(0); 



      case 2: 
       { 
        //Same stuff... 
       } 

       if ($cordovaPrinter.isAvailable()) { 
        cordova.plugins.printer.print(htmlFile, 'photos: ' + subtitle, function() { 
         console.log("Print is done"); 
        }); 
       }  
       else { 
        alert("Printing is not available on device"); 
       } 

     } 
    } 

}) 

第二业务

.service('imgConvertToBase64', function() { 
    function toDataUrl(url, callback, outputFormat) { 
     var img = new Image(); 
     img.crossOrigin = 'Anonymous'; 
     img.onload = function() { 
      var canvas = document.createElement('CANVAS'); 
      var ctx = canvas.getContext('2d'); 
      var dataURL; 
      canvas.height = this.height; 
      canvas.width = this.width; 
      ctx.drawImage(this, 0, 0); 
      dataURL = canvas.toDataURL(outputFormat); 
      callback(dataURL); 
      canvas = null; 
     }; 
     img.src = url; 
    } 

    return { 
     toDataUrl: toDataUrl 
    } 
}) 
+0

看起来不像angularJS我...请提供控制器/指令和视图。另外,在一个函数中构建html并不是角度的方式,除非你在指令中,并且这看起来不像一个指令.. –

+0

我构建html文件以打印为pdf格式。我不会在设备上呈现它。我只是使用这些服务来打印它。 – Korte

回答

0

我发现了什么是错误的。它转换JPG为base64功能是异步的,所以我必须通过我的所有代码回调imgConvertToBase64.toDataUrl(i, function (dataUri) { //here })

else { 
      body += '</body>'; 
      htmlFile = '<html>' + head + body + '</html>'; 
      console.log(htmlFile); 

      //Here I had to add the function which actually prints my html. 
     } 
相关问题