使用jsPDF将本地图像打印为pdf

时间:2019-04-19 17:04:14

标签: javascript html jspdf

我会将图像添加到pdf文件中。

const pdf = new jsPDF('l', 'px', 'a4');
const imgData = 'data:image/jpeg;base64,' + btoa(`assets/img/brand/png/Logos.png`);
console.log(imgData);
pdf.addImage(imgData, 'jpeg', 15, 40, 180, 160);
pdf.save(`ind.pdf`);

我遇到错误

 Error: addImage does not support files of type 'UNKNOWN'

我认为错误来自btoa(),它编码路径字符串而不是文件。

如何将png图像而不是路径字符串传递给btoa?

1 个答案:

答案 0 :(得分:2)

When I was trying to use an image file instead of a Base64 encoded image I had trouble with the version of jsPDF. After I changed to use the latest version of jsPDF, then this worked.

function fnProcess() {

  var img = new Image();
  var src = "https://www.jeffld.com/img/so/testimage001.png";
  img.src = src;

  console.log("Create jsPDF object");
  var pdf = new jsPDF("p", "pt", "letter");

  console.log("Add Image");
  pdf.addImage(img, "png", 10, 10, 150, 150);

  console.log("Save PDF");
  pdf.save("file.pdf");
  console.log("done");
}
<!-- Latest version of jsPDF Version 1.5.3 Built on 2018-12-27T14:11:42.696Z -->
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>

<button onclick="fnProcess()">Process</button>

<p>Image to PDF</p>    
<img id="activityLogo" src="https://www.jeffld.com/img/so/testimage001.png" alt="" />