Watermark using pdfmake
In Javascript, I am using pdfmake to generate a PDF document. I read it from github that it supports watermarking and the following is my use, but it gives me some random and strange characters. These characters are the same no matter what texts are provided by the watermark. Anyone got an idea?
source to share
I can't say I have a solution to this problem, but I did it for me. It seems that the function renderWatermark()
at line 465 or near line 465 or pdfmake.js has font encoding issues.
var encoded = watermark.font.encode(watermark.text);
returns an empty string and has no extended properties that the function looks for later.
By changing
pdfKitDoc.addContent('/' + encoded.fontId + ' ' + watermark.size.fontSize + ' Tf');
to
pdfKitDoc.addContent('/ ' + watermark.size.fontSize + ' Tf');
and
pdfKitDoc.addContent('<' + encoded.encodedText + '> Tj');
to
pdfKitDoc.addContent('(' + watermark.text + ') Tj');
I was able to display the watermark in the correct position, albeit with a generic font, and not whatever I chose.
source to share
I made a few more changes to get the watermark to work the way I wanted. Following are the changes I made to printer.js
pdfKitDoc.fill('darkgray'); // Change colour
pdfKitDoc.opacity(0.3); // Change opacity as watermark was too dark for my liking
Commented out below to keep the watermark text horizontal
//var angle = Math.atan2(pdfKitDoc.page.height, pdfKitDoc.page.width) * 180/Math.PI;
//pdfKitDoc.rotate(0, {origin: [pdfKitDoc.page.width/2, pdfKitDoc.page.height/2]});
// Changed width and height for proper rendering of watermark text horizontally
pdfKitDoc.addContent('' + (pdfKitDoc.page.width/2 - watermark.size.size.width/4) + ' ' + (pdfKitDoc.page.height/2 - watermark.size.size.height/4) + ' Td');
Ideally, color, opacity and enhancement; the orientation of the text must be customizable.
source to share