Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to draw rect on existing <canvas> which rendered PDF using pdfjs

Task

Have a canvas in your page <canvas id="pdfCanvas"> create a fabric canvas for existing canvas new fabric.Canvas("pdfCanvas"); have mouse.down, mouse.up, mouse.move methods to enable drawing rectangles render pdf in the above canvas "pdfCanvas" using PDF.js browser now shows the rendered PDF now draw rectangles on the pdf, it hides the rendered canvas but it does draw objects

Problem

Here is the fiddle to see the issue: - run the above https://jsfiddle.net/hiitskiran/wgz8qore/2/ - you can see the fabric rectangle is hiding behind the rendered pdf - click on the pdf canvas area to see the fabric objects

like image 777
Kiran Avatar asked Jan 05 '23 01:01

Kiran


1 Answers

What I see from your fiddle is that you don't wait the result of page.render method, which is asyncronous, then, unfortunately, if you wait the page.render, the fabric.canvas instance will clean your previously filled canvas, and we can't do nothing for this. So I tried another approach: First of all, I wait the pdf.js page.render method, then I invoke the .toDataURL of your previously filled canvas so that I can have a copy of the old content, then I set your previously filled canvas as background of your new fabric.canvas and finish to draw your rectangle.

var url = 'http://www.africau.edu/images/default/sample.pdf';
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function(pdf) {
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    page.render({
      canvasContext: context,
      viewport: viewport
    }).then(function() {

      var bg = canvas.toDataURL("image/png");
      var fcanvas = new fabric.Canvas("pdfcanvas", {
        selection: false
      });
   fcanvas.setBackgroundImage(bg,fcanvas.renderAll.bind(fcanvas));
      fcanvas.setWidth(300);
      fcanvas.setHeight(300);
      var rect = new fabric.Rect({
        left: 100,
        top: 100,
        width: 50,
        height: 50,
        fill: '#FF454F',
        opacity: 0.5,
        transparentCorners: true,
        borderColor: "gray",
        cornerColor: "gray",
        cornerSize: 5
      });
      fcanvas.add(rect);
      fcanvas.renderAll();
    });
  });
});
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.js"></script>
<canvas id="pdfcanvas" style="border:1px solid black"></canvas>
like image 174
alessandro Avatar answered Jan 22 '23 09:01

alessandro