Search code examples
phphtmlpdf-generationghostscriptfpdf

Merge signature image onto a pdf loaded in a div


For a project I need to load a pdf file onto a div. On clicking a button a canvas will be opened where the user will draw his signature and then on clicking the add button present in the canvas, the user should be able to place the canvas signature as an image on to the pdf. At last on clicking the final button the image should get merged onto the pdf.

I did the above task in the following way:

  1. Converted pdf into series of images using GhostScript.
  2. Loaded the converted images onto a div.
  3. On clicking the button a canvas will be opened and the user will sign in it and on clicking the add button present in the canvas, the user will be able to place the image onto the image of pages loaded in the div.
  4. I obtain the page Id which is the page number and the signature image placed coordinate using e.clientX and e.clientY.
  5. Then I pass all those 3 values to a php script which uses fpdf and fpdi to merge the image onto the pdf.
  6. I'm not able to place the image properly because e.clientX and e.clientY makes use of pixel as units where as fpdf uses mm as units. I'm trying to sort out that.

Is there any other way to do this in a simpler way. i.e., directly loading the pdf onto the div and merging the signature instead of what I've explained above.


Solution

  • You may try Firefox's PDF.js, which you can make use of, in your project. A sample code would be:

    PDFJS.getDocument('helloworld.pdf').then(function(pdf) {
      // Using promise to fetch the page
      pdf.getPage(1).then(function(page) {
        var scale = 1.5;
        var viewport = page.getViewport(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
        };
        page.render(renderContext);
      });
    });