3

I would add an image to a pdf File.

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`);

I get an error

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

I think that the error comes from btoa() it encode the path string but not the file.

How can I pass to btoa the png image instead of the path string ?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Hamza Haddad
  • 1,516
  • 6
  • 28
  • 48

2 Answers2

4

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="" />
     
jeffld
  • 726
  • 1
  • 9
  • 17
1

In case you want to print an uploaded image.


  let image = new Image();
  let source = URL.createObjectURL(e.target.files[0]); //general case
  image.src = source ;

  let pdf = new jsPDF();
  pdf.addImage(image, "jpeg", 10, 20, 300, 300);

  pdf.save("image.pdf");
}```
Zahir Masoodi
  • 546
  • 7
  • 23