How to add watermark in PDF genereted from jsPDF?

让人想犯罪 __ 提交于 2019-12-29 09:28:05

问题


I am generating PDF from canva and using jsPDF to generate it.

https://github.com/MrRio/jsPDF

Here is my code what I am using I want to add watermark into page. Can anyone help me in that ?

 self.downloadCanvasObjectAsPDF = function () {
        canvas.deactivateAll().renderAll();

        try {
            canvas.getContext('2d');
            var imgData = canvas.toDataURL("image/jpeg", 1.0);
            var pdf = new jsPDF('p', 'mm', [297, 210]);
            pdf.addImage(imgData, 'JPEG', 5, 5);
            var namefile = 'export';
            if(namefile != null) {
                pdf.save(namefile + ".pdf");
                return true;
            }else{
                return false;
            }
        } catch(e) {
            alert("Error description: " + e.message);
        }
    };

回答1:


You can add your watermark be it an image or text manually at each page first, then add your contents so that it won't overlaps each other.

In this approach you have add/call the watermark on adding each new page too. doc.addPage();

(Or)

At the end of PDF generation you could call a function that perform adding watermarks for all pages.

Let's say I want to add watermark to all my pages after PDF generation.

function addWaterMark(doc) {
  var totalPages = doc.internal.getNumberOfPages();

  for (i = 1; i <= totalPages; i++) {
    doc.setPage(i);
    //doc.addImage(imgData, 'PNG', 40, 40, 75, 75);
    doc.setTextColor(150);
    doc.text(50, doc.internal.pageSize.height - 30, 'Watermark');
  }

  return doc;
}

Call this function before saving the PDF

function getPdf() {

  var doc = new jsPDF('p', 'pt', 'a4');

//Add content

//finally call the watermark
  doc = addWaterMark(doc);

  doc.save('test');

}

Fiddle here for reference: https://jsfiddle.net/Purushoth/f55h4hzs/



来源:https://stackoverflow.com/questions/42832164/how-to-add-watermark-in-pdf-genereted-from-jspdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!