from PIL import Image, ImageDraw, ImageFont from docx import Document from docx.shared import Inches import os # Create A4 image (approx 794x1123 px) width, height = 794, 1123 img = Image.new("RGBA", (width, height), (255, 255, 255, 0)) draw = ImageDraw.Draw(img) # Load default font try: font = ImageFont.truetype("arial.ttf", 120) except: font = ImageFont.load_default() text = "WATERMARK" text_width, text_height = draw.textsize(text, font=font) # Position for diagonal # rotate text by 45 degrees txt_layer = Image.new("RGBA", (width, height), (255, 255, 255, 0)) txt_draw = ImageDraw.Draw(txt_layer) txt_draw.text( ((width - text_width) / 2, (height - text_height) / 2), text, font=font, fill=(150, 150, 150, 80), ) rotated = txt_layer.rotate(45, expand=1) img.paste(rotated, (int((width - rotated.width) / 2), int((height - rotated.height) / 2)), rotated) # Save watermark image img_path = "/mnt/data/watermark.png" img.save(img_path) # Create Word document with watermark in header doc = Document() section = doc.sections[0] header = section.header header_para = header.paragraphs[0] run = header_para.add_run() run.add_picture(img_path, width=Inches(6.5)) # wide enough to cover page # Save docx doc_path = "/mnt/data/watermarked_document.docx" doc.save(doc_path) doc_path

Enjoying this? A quick like helps keep it online longer.

Content Expiring Soon

This content will be deleted in less than 24 hours. If you like it, you can extend its lifetime to keep it available.

0 likes
1 view
12 days left
Like what you see? Create your own
1
0
12d