Prevent concurrent function calls when using pdf.js?

I am using pdf.js to view pdf files, but the result is not suitable, please see my code.

My codes are as follows.

var aaa = function (pdf, page_number) {
      pdf.getPage(page_number).then(function(page) {
        var scale = 1.5;
        var viewport = page.getViewport(scale);
        var canvas = $('.pdf-view')[page_number-1];
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        var renderContext = {
            canvasContext: context,
            viewport: viewport
        };  
        page.render(renderContext);
    }); 
};
for (var i = 1;i < 51;i++) {
    aaa(pdf, i);
    if (i !== 50) {
        var a = '<canvas data="{{ raw_path }}" class="pdf-view hide" style="margin-bottom:10px;"></canvas>';
        $('#file-view #pdf').append(a);
    } 
}

      

There is a loop, then 50 functions ( aaa

) are executed simultaneously. The effect is disastrous and my computer gets stuck. I want to call the function right after the last function has run out very well.

Please help me improve it. Thank you so much. (Sorry, my English is also disastrous.)

+3


source to share


1 answer


To avoid running the load function and displaying the same page at the same time aaa

, you should move your call to the page load callback - .then(

so that it is called recursively. Then call the function aaa

only once with page_number = 1

.



//define page render function     
var aaa = function (pdf, page_number) {
          pdf.getPage(page_number).then(function(page) {
            var scale = 1.5;
            var viewport = page.getViewport(scale);
            var canvas = $('.pdf-view')[page_number-1];
            var context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            var renderContext = {
                canvasContext: context,
                viewport: viewport
            };  
            page.render(renderContext);

            if (i < 50) {
            //render first 50 pages but not all pages except #50
                aaa(pdf, i);
                i++;
            }

        }); 
    };

//pre-generate 50 canvases
var docFragment = document.createDocumentFragment();
for (var i = 1;i < 51;i++) {
  var c = document.createElement("canvas");
  $(c).data({{ raw_path }});
  $(c).addClass('pdf-view hide');
  $(c).css('margin-bottom', '10px');
  docfrag.appendChild(c);
}
 $('#file-view #pdf').append(docfrag);

    //call render
    var i = 1;
    aaa(pdf, i);

      

0


source







All Articles