Search code examples
svguripdftron

Is there a way to create a Stamp annotation using a SVG as ImageData


I would like to create a custom stamp annotation using a SVG in PDFTron.

I saw someone on some google forum having the same question, and a PDFTron developer actually responded, and this is what I have so far...

const svgElement = '<svg>my svg</svg>'

const CustomStamp = function() {
   Annotations.StampAnnotation.call(this);
   this.ImageData = encodeURI('data:image/svg+xml,' + svgElement);
}

CustomStamp.prototype = new Annotations.StampAnnotation();

const CustomCreateTool = function(docViewer) {
            Tools.GenericAnnotationCreateTool.call(this, docViewer, CustomStamp);
        };

CustomCreateTool.prototype = new Tools.GenericAnnotationCreateTool();

CustomCreateTool.prototype.mouseLeftDown = function() {
            Tools.AnnotationSelectTool.prototype.mouseLeftDown.apply(this, arguments);
        };

CustomCreateTool.prototype.mouseMove = function() {
            Tools.AnnotationSelectTool.prototype.mouseMove.apply(this, arguments);
        };

CustomCreateTool.prototype.mouseLeftUp = function(e) {
            var annotation;
            Tools.GenericAnnotationCreateTool.prototype.mouseLeftDown.call(this, e);
            if (this.annotation) {
              this.annotation.Width = 50;
              this.annotation.Height = 50;
              this.annotation.X -= this.annotation.Width/2;
              this.annotation.Y -= this.annotation.Height/2;
              this.annotation.NoResize = true;
              annotation = this.annotation;
            }
            Tools.GenericAnnotationCreateTool.prototype.mouseLeftUp.call(this, e);
            if (annotation) {
              annotManager.redrawAnnotation(annotation);
            }

However, it seems that it only draws an empty box... Any help would be appreciated!


Solution

  • I reviewed your code and it seems correct. Trying it out myself I believe the issue is with your test SVG; it appears that by missing the xmlns tag it results in an invalid HTMLImage element when calling encodeURI.

    Can you try your code with the following SVG? I used it for debugging and the stamp works as expected.

    const svgElement = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg>'