pdfrw
pdfrw copied to clipboard
Controlling opacity of watermark
Hello I am trying out the fancy_watermark.py example to add a watermark to a pdf. It works great. But the watermark hides the text if its over some part of the document. When I place the watermark underneath the main content it can get hidden by objects like images. Is there a way to control the opacity of watermark so that I can place on top but still can see the text underneath?
Thanks
A shot in the dark but try using a bitmap where you can adjust opacity in some kind of image editor (PS/gimp). Also background transparency.
A shot in the dark but try using a bitmap where you can adjust opacity in some kind of image editor (PS/gimp). Also background transparency.
Thanks for the great suggestion. I also tried something similar by using a PNG image with an opacity of 0.5. I first created a pdf containing the PNG image of the watermark. Then passed it to the fancy_watermark.py alongwith the original pdf. However, the watermark still hides the text. I tried different opacity values but to no avail.
Pdfrw sets pdf file version to 1.3. To the best of my knowledge 1.3 did not support transparency (transparency was added in version 1.4). If the file is really a 1.3 version then the output you're getting is correct.
Pdfrw sets pdf file version to 1.3. To the best of my knowledge 1.3 did not support transparency (transparency was added in version 1.4). If the file is really a 1.3 version then the output you're getting is correct.
Good point. I re-tested with a pdf file of version 1.7. The watermark pdf is version 1.4. Also, created the PdfWriter with version=1.4. The result is not changed. I am attaching a screenshot of part of the page shown in Adobe Acrobat Reader:
As can be seen, the watermark's background is transparent but the text in watermark hides the document's text.
While searching for a solution, I found some suggestion on adding in page (resources?) a /ExtGState object/dict with a /ca value of opacity needed. I do not know internals of PDFs, so I am not sure if this will solve the issue or if such thing is possible in pdfrw.
I tried to write a function to control the opacity of the page by modifying the ca
value in ExtGState
. Then placing the watermark underneath the text, the watermark is visible through the page contents (e.g. image), if the page opacity is set to less than 1. However, I am not successful in adding a new ExtGState
element to a page if it was not there before. So the else
part causes an error when the document is opened in the reader.
def adjust_opacity(page, opacity=0.5):
if page.inheritable.Resources:
extgstate = page.inheritable.Resources.ExtGState
if extgstate:
for k, _ in extgstate.iteritems():
if extgstate[k].Type == '/ExtGState' and extgstate[k].ca != opacity:
extgstate[k].ca = opacity
else:
page.inheritable.Resources.ExtGState = PdfDict(ca=0.5, Type='/ExtGState')
return page