如何在从 jsPDF 生成的 PDF 中添加水印?

2022-01-17 00:00:00 pdf html html5-canvas jspdf

我正在从 canva 生成 PDF 并使用 jsPDF 生成它.

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);
        }
    };

推荐答案

您可以先在每个页面手动添加水印,无论是图像还是文本,然后添加内容,使其不会相互重叠.

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.

在这种方法中,您也可以在添加每个新页面时添加/调用水印.doc.addPage();

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

(或)

在 PDF 生成结束时,您可以调用一个为所有页面添加水印的函数.

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

假设我想在 PDF 生成后为所有页面添加水印.

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;
}

在保存 PDF 之前调用这个函数

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');

}

这里提琴供参考:https://jsfiddle.net/Purushoth/f55h4hzs/

相关文章