2017-07-18 79 views
1

我有一个网页,我希望打印一些HTML。 为此,我使用html2canvasjsPDF从html导出图像到jsPDF

我遇到的问题是它不打印HTML中显示的图像。

我的HTML和CSS如下所示(complete code in fiddle):

.handsomeHtml { 
background: red; 
} 

.crazyFrog { 
background: url('http://e-cdn-images.deezer.com/images/artist/01eb92fc47bb8fb09adea9f763bb1c50/500x500.jpg'); 
width: 500px; 
height: 500px; 
} 

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"> 
</script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"> 
</script> 

<div id="someHtml" class="handsomeHtml"> 
    Hello, handsome HTML 
<br> 
<img class="crazyFrog"></img> 
</div> 

<button id="savePDFbutton" onclick="savePDF()"> 
    save pdf 
</button> 

预期结果:

enter image description here

实际PDF结果

enter image description here

回答

4

检查此工作代码。

您还可以在fiddle上检查代码。

<!DOCTYPE html> 
 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
 
    <head> 
 
     <title></title> 
 
     <script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script> 
 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script> 
 
     <script type="text/javascript"> 
 
      var testDivElement = document.getElementById('someHtml'); 
 

 
      function savePDF() { 
 
       var imgData; 
 
       html2canvas($("#someHtml"), { 
 
        useCORS: true, 
 
        onrendered: function (canvas) { 
 
         imgData = canvas.toDataURL(
 
          'image/png'); 
 
         var doc = new jsPDF('p', 'pt', 'a4'); 
 
         doc.addImage(imgData, 'PNG', 10, 10); 
 
         doc.save('sample-file.pdf'); 
 
         window.open(imgData); 
 
        } 
 
       }); 
 
      } 
 

 

 
     </script> 
 
     <style> 
 
      .handsomeHtml { 
 
       background: red; 
 
      } 
 

 
      .crazyFrog { 
 
       background: url('http://e-cdn-images.deezer.com/images/artist/01eb92fc47bb8fb09adea9f763bb1c50/500x500.jpg'); 
 
       width: 500px; 
 
       height: 500px; 
 
      } 
 
     </style> 
 
    </head> 
 
    <body> 
 
     <div id="someHtml" class="handsomeHtml"> 
 
      Hello, handsome HTML 
 
     <br /> 
 
      <img class="crazyFrog"></img> 
 
     </div> 
 
     <br /> 
 
     <button id="savePDFbutton" onclick="savePDF()"> 
 
      save pdf 
 
     </button> 
 
    </body> 
 
    </html>

1

这可能是jsPDF库无法解析“over the wire”图像,您是否试图将其作为base64编码图像直接包含在CSS中?

+0

谢谢,实际工作,但恐怕我不能一切转换为base64 – methgaard