You can search a document for existing watermarks and modify them in place — for example, replace the text of a text watermark or swap the image of an image watermark.
Update text watermarks
Search for a watermark by its text content, then assign a new value to each match. The example below opens a document that already contains a “CONFIDENTIAL” watermark and replaces it with “APPROVED”.
fromgroupdocs.watermarkimportWatermarkerfromgroupdocs.watermark.search.search_criteriaimportTextSearchCriteriadefupdate_watermark():withWatermarker("./watermarked-document.pdf")aswatermarker:# Find the watermarks whose text matches the criteriapossible=watermarker.search(TextSearchCriteria("CONFIDENTIAL"))print("Found",len(possible),"possible watermark(s).")forwatermarkinpossible:try:watermark.text="APPROVED"exceptException:# Some found entities do not support text editing — skip thempasswatermarker.save("./output.pdf")if__name__=="__main__":update_watermark()
watermarked-document.pdf is the sample file used in this example. Click here to download it.
Image watermarks can be found with perceptual hashing (ImageDctHashSearchCriteria) and updated by assigning new bytes to image_data. The example below finds the logo watermark and replaces it with an “APPROVED” stamp:
fromgroupdocs.watermarkimportWatermarkerfromgroupdocs.watermark.search.search_criteriaimportImageDctHashSearchCriteriadefupdate_image_watermark():withWatermarker("./watermarked-document.docx")aswatermarker:criteria=ImageDctHashSearchCriteria("./logo.png")criteria.max_difference=0.9possible=watermarker.search(criteria)withopen("./stamp.png","rb")asf:image_data=f.read()forwatermarkinpossible:try:watermark.image_data=image_dataexceptException:# Some found entities do not support image editing — skip thempasswatermarker.save("./output.docx")if__name__=="__main__":update_image_watermark()