【问题标题】:Adding Image to a PDF using jspdf makes the image black使用 jspdf 将图像添加到 PDF 会使图像变黑
【发布时间】:2015-02-16 21:09:28
【问题描述】:

当我尝试将 URL 中的图像添加到 PDF 文件时,图像完全变黑。
但是当我再次单击下载 pdf 按钮时,图像被添加到 PDF.Only 当我第一次这样做时,图像是黑色的。

 function getBase64Image(url) {

alert(url);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = url;
img.style.height ="181px";
img.style.width ="183px";
//img.crossOrigin ="Anonymous";

context.drawImage(img,0,0);

var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
document.body.appendChild(img);


var doc = new jsPDF('landscape');

doc.addImage(img,'JPEG',0,0,50,50);
doc.save('Saved.pdf');

 }

getBase64Image("http://localhost:64931/jspdf/download.png");

【问题讨论】:

    标签: javascript image pdf-generation jspdf


    【解决方案1】:

    我昨天遇到了同样的问题,写这个答案以防有人觉得它有用

    我想达到什么目的?

    • 我正在将文档 (pdf) 转换为 blob,然后在打印对话框中打开它,但图像是黑色的。

      var blob = new Blob([doc.output()], { type: "application/pdf" });

    这就是我尝试将其转换为 blob 的方式。 但这导致了黑色图像

    解决方案

    • jsPDF 允许我们在输出函数中添加参数。

    [](jsPDF output api)

    添加类型为 bloburl 对我有用,因为我正在使用 blob url 打开打印对话框

      let iframe = document.createElement("iframe"); //load content in an iframe to print later
        document.body.appendChild(iframe);
    
        //* print dialogue
        iframe.style.display = "none";
        iframe.src = blobURL;
        console.log(blobURL) // same blobURL that was received from jsPDF
        iframe.onload = function () {
          setTimeout(function () {
            iframe.focus();
            iframe.contentWindow.print(); // opens a print dialogue box
          }, 1);
        };
    

    【讨论】:

      【解决方案2】:

      当您像这样更改代码时会发生什么:

      将 JPEG 更改为 PNG,这对我有用。

      function getBase64Image(url) {
      
      alert(url);
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var img = new Image();
      img.src = url;
      img.style.height ="181px";
      img.style.width ="183px";
      //img.crossOrigin ="Anonymous";
      
      context.drawImage(img,0,0);
      
      var dataURL = canvas.toDataURL("image/png");
      alert(dataURL);
      document.body.appendChild(img);
      
      
      var doc = new jsPDF('landscape');
      
      doc.addImage(img,'PNG',0,0,50,50);
      doc.save('Saved.pdf');
      
       }
      
      getBase64Image("http://localhost:64931/jspdf/download.png");
      

      【讨论】:

        猜你喜欢
        • 2013-10-04
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多