jSPDF - Render Hi-Res Image

by Purushothaman Anbazhagan

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<h1>jsPDF - Render Hi-Res Image</h1>
<h3>Below is 1500px image we need to render it in 400px of PDF</h3>
<div id="qrcode-2"></div>

<div class="action">
  <button class="btn" onClick="downloadPDF()">
    Download
  </button>
</div>

SCSS

.action {
  margin: 100px;
  text-align: center;

  .btn {
    min-width: 183px;
    height: 50px;
    padding: 8px;
    box-sizing: border-box;
    background: navy;
    color:white;
  }
}

JavaScript

// const width/height of image inside pdf
const MAX_WIDTH = 400;
const MAX_HEIGHT = 400;

// 1. create QR code 
var qrcode2 = new QRCode("qrcode-2", {
  text: "https://youtube.com",
  width: 1500,
  height: 1500,
  colorDark: "#000000",
  colorLight: "#ffffff",
  correctLevel: QRCode.CorrectLevel.H
});


function downloadPDF() {

  var doc = new jsPDF("p", "mm", "a4");
  doc.setFontSize(40);
  doc.text(35, 25, 'This image is 1500px');
  doc.setFontSize(20);
  doc.text(15, 35, 'But the size of A4 page in 72dpi is 595 X 842px');
  doc.text(15, 45, 'We have to scaled down this image to fit in.');

  var hiResImage = $("#qrcode-2 img").attr("src");

  getDimensionOfBase64(hiResImage, function(width, height) {
    doc.addImage(hiResImage, 'JPEG', 35, 100, pxToMM(width), pxToMM(height));

    doc.addPage();
    doc.text(15, 55, 'After resizing..');
    resizeImage(hiResImage, function(result, width, height) {
      doc.addImage(result, 'JPEG', 35, 100, pxToMM(width), pxToMM(height));
      savePdf(doc, "high-res-image-to-pdf");
    });
  });

}

function savePdf(doc, name) {
  doc.save(name + ".pdf");
}

function pxToMM(unit) {
  //https://www.unitconverters.net/typography/pixel-x-to-millimeter.htm
  //1px = 0.2645833333mm
  return unit * 0.2645833333;
}


function getDimensionOfBase64(imageString, callback) {
  var i = new Image();

  i.onload = function() {
    callback(i.width, i.height);
  };

  i.src = imageString;
}


function resizeImage(imageString, callback) {
  var img = new Image();

  img.onload = function() {
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);


    var width = img.width;
    var height = img.height;

    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }

    canvas.width =...