PDFMake.js Tutorial to Insert External Image From URL to PDF Document Using Base64 Code in Javascript Full Project For Beginners

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PDFMake</title>
</head>

<body>
<img id="imageid" crossorigin="anonymous" src="https://images.pexels.com/photos/5911018/pexels-photo-5911018.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.70/pdfmake.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.70/vfs_fonts.js"></script>
<script>
  // playground requires you to assign document definition to a variable called dd
  var base64 = getBase64Image(document.getElementById("imageid"));

  let docDefinition = {
      content: [
        {
          text: 'PDF Generated with Image from external URL',
          fontSize : 20
        },
        {
          image:base64
          
        }        
      ]
    };
  pdfMake.createPdf(docDefinition).download();

  function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
</script>

</html>

Leave a Reply