Saturday, May 25, 2019

jQuery convert PDF to Images Page by Page using pdfjsLib from Mozilla Foundation

First download pdf.js and pdf.workder.js from here or use direct link //mozilla.github.io/pdf.js/build/pdf.js and //mozilla.github.io/pdf.js/build/pdf.worker.js.

<script src="pdf.js"></script>

<title>PDF.js 'Hello, world!' example</title>

<h1>PDF.js 'Hello, world!' example</h1>

<canvas id="the-canvas" style="border:1px solid red;"></canvas>

<script type="text/javascript">
  var url = './sample2.pdf';

  // Loaded via <script> tag, create shortcut to access PDF.js exports.
  var pdfjsLib = window['pdfjs-dist/build/pdf'];

  // The workerSrc property shall be specified.
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';

  // Asynchronous download of PDF
  var loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise.then(function(pdf) {
    console.log('PDF loaded, total pages = ' + pdf.numPages);

    // Fetch the first page
    var pageNumber = 1;
    pdf.getPage(pageNumber).then(function(page) {
      console.log('Page loaded');

      var scale = 1.5;
      var viewport = page.getViewport({scale: scale});

      // Prepare canvas using PDF page dimensions
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      // Render PDF page into canvas context
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.promise.then(function () {
        console.log('Page rendered');
      });
    });
  }, function (reason) {
    // PDF loading error
    console.error(reason);
  });
</script>

jQuery Resize and Compress Image

This is a jQuery technique to resize image using canvas and Image object. You can resize image as you wanted.
Below is a jQuery class that will actually convert file to blob after resize done:
class ImageResizer {
  "use strict"

  static _initDone = false;

  static resize(file, options, callback) {
    this._init();

    var thisOptions = {
      maxWidth: 1200
    };
    $.extend( thisOptions, options );

    var width = thisOptions.maxWidth;
    var fileName = file.name;
    var fileType = file.type;

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event) {
      const img = new Image();
      img.src = event.target.result;
      img.onload = function() {
        if (width > img.width) {
          width = img.width;
        }
        const elem = document.createElement('canvas');
        elem.width = width;
        const scaleFactor = width / img.width;
        elem.height = img.height * scaleFactor;
        const ctx = elem.getContext('2d');
        // img.width and img.height will contain the original dimensions
        ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);

        // function(callback_function, file_type, quality_0_to_1)
        ctx.canvas.toBlob(function(blob) {
          blob.lastModifiedDate = Date.now();
          blob.name = fileName;
          blob.width = width;
          blob.height = img.height * scaleFactor;

          callback(undefined, blob);
        }, fileType, 1);
      },
        reader.onerror = function(error) {
          callback(error);
        };
    };
  }

  static _init() {
    if (!this._initDone) {
      this._initDone = true;

      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var dataURL = this.toDataURL(type, quality).split(',')[1];
            setTimeout(function() {
              var binStr = atob( dataURL ), len = binStr.length, arr = new Uint8Array(len);
              for (var i = 0; i < len; i++ ) {
                arr[i] = binStr.charCodeAt(i);
              }
              callback( new Blob( [arr], {type: type || 'image/png'} ) );
            });
          }
        });
      }
    }
  }
}
And you can use this from html page as below:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Resize Component</title>
  <script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
  <script src="image-resizer.js"></script>
  <script type="text/javascript">
    $(document).on('ready', function() {
      var image = $("#PhotoPicker");
      image.on('change', function(e) {
        $("canvas").remove();

        ImageResizer.resize(e.target.files[0], {maxWidth: 300}, function(error, blob) {
          const canvas = document.createElement('canvas');
          canvas.width = blob.width
          canvas.height = blob.height;
          const context = canvas.getContext('2d');

          var img = new Image();
          img.onload = function(){
            context.drawImage(img, 0, 0, blob.width, blob.height);
          };
          img.onerror = function(e){
            console.log('Error during loading image:', e);
          };
          img.src = URL.createObjectURL(blob);

          document.body.appendChild(canvas);
        });
      });
    });
  </script>
</head>
<body>
<input type="file" id="PhotoPicker" accept="image/*" capture="camera"><br/><br/>
</body>
</html>

How to deal with big numbers in javascript | Extremely large numbers in javascript | Large Number Addition in JavaScript | How to deal with extremly big numbers in javascript |

Javascript supports at most 53 bit integers. What this means is that integers larger than 53 bits lose precision. This article will explain how to handle addition with integers larger than 53 bits in javascript.
I'm looking for a Mathematical solution that deals with really (long, big, huge, storms) numbers. I haven't found anything yet, But I don't wanna think that this problem hasn't be solve at this time. I'm looking for an easy Number solution, like Microsoft Excel Precision (30 decimals), or a BigInteger (Java) solution. in Javascript of course.
JavaScript is only capable of handling 53-bit numbers, if you are working with a big number such as Twitter ID, which is using 64-bit number, then you need to find an external library to do that, otherwise, there will be precision lost.
View in JSFiddle
<script type="text/javascript" src="big-number.js"></script>

<script type="text/javascript">
    (function () {
        var a = new BigNumber("07777777"), b = "888888880";
        console.log(a.multiply(b).toString());
        console.log(new BigNumber("990").toString());
    })();
</script>
Download Library