簡體   English   中英

html2canvas 和 jsPDF 不保存外部主機的圖像

[英]html2canvas and jsPDF not save image of external host

在我的代碼中,我試圖捕獲 div 內的所有內容,包括 styles 和圖像。 如果圖像屬於當前主機,則保存沒有問題,如果它們屬於外部主機,則不會保存...

<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.0.272/jspdf.debug.js"></script>

<div id="printDiv">
  <h2>Hello World</h2>
  <p>
    this content will be printed.
  </p>
  
  <img src="https://i.pinimg.com/originals/33/b8/69/33b869f90619e81763dbf1fccc896d8d.jpg" />
</div>
<button type="button" id="pdfDownloader">Download</button>

<script>
$(document).ready(function(){

    //pdf   
    $("#pdfDownloader").click(function(){
    
        html2canvas(document.getElementById("printDiv"), {
            onrendered: function(canvas) {

                var imgData = canvas.toDataURL('image/png');
                console.log('Report Image URL: '+imgData);
                var doc = new jsPDF('p', 'mm', [297, 210]); //210mm wide and 297mm high
                
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample.pdf');
            }
        });

    });
    
    
})
</script>

我可以使用什么替代方法在 pdf 中保存帶有外部鏈接的圖像?

您可以使用 jQuery 和 canvas2image 來執行此操作

 $(function() { $("#pdfDownloader").click(function() { var imgURL = $("#printDiv").find('img').attr('src'); html2canvas($("#printDiv"), { onrendered: function(canvas) { var context= canvas.getContext("2d"); // returns the 2d context object var img = new Image() //creates a variable for a new image img.src= imgURL; // specifies the location of the image context.drawImage(img,0,50); // draws the image at the specified x and y location // Convert and download as image theCanvas = canvas; document.body.appendChild(canvas); // Convert and download as image Canvas2Image.saveAsPNG(canvas); $("#img-out").append(canvas); } }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/0.4.1/html2canvas.js"></script> <script type="text/javascript" src="http://www.nihilogic.dk/labs/canvas2image/base64.js"></script> <script type="text/javascript" src="http://www.nihilogic.dk/labs/canvas2image/canvas2image.js"></script> <div id="printDiv"> <h2>Hello World</h2> <p> this content will be printed. </p> <img src="https://i.pinimg.com/originals/33/b8/69/33b869f90619e81763dbf1fccc896d8d.jpg"> </div> <button type="button" id="pdfDownloader">Download</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM