creating watermark for multiple files modified
Published 18. Oktober 2024 15:42 by
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter,A0,A4,landscape
from decimal import Decimal
from pathlib import Path
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.colors import Color, black, blue, red
from reportlab.pdfbase.ttfonts import TTFont
import io
import sys
import os
change xxx to your user name
sys.path.append(os.path.abspath("c:/users/xxxx/appdata/roaming/python/python310/site-packages"))
pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
draw the text
listofpdfFiles=[]
put the pdf files to watermark on the same folder as the python script
def getPdfFiles():
root = "." # take the current directory as root
for path in Path(root).glob("**/*.pdf"):
listofpdfFiles.append(path)
def drawText(packet,width,height,text,textsize):
c = canvas.Canvas(packet, landscape(pagesize=A0))
c.saveState()
#c.setFillColorRGB(255, 0, 0) #choose your font colour
red50transparent = Color( 100, 0, 0, alpha=0.5)
black50transparent = Color( 0, 0, 0, alpha=0.5)
c.setFillColor(black50transparent)
#c.setFillColorRGB(255, 0, 0) #choose your font colour
c.setFont('Vera', textsize)
c.translate(width, height)
c.rotate(30)
c.drawString(0, 0, text)
c.restoreState()
c.save()
Function to add text to an existing PDF
def add_text_to_pdf(input_pdf, output_pdf, text):
# Read the existing PDF
reader = PdfReader(input_pdf, strict=False)
writer = PdfWriter()
# create a new PDF with Reportlab
packet = io.BytesIO()
packet.seek(0)
# read your existing PDF
existing_pdf = PdfReader(input_pdf, strict=False)
output = PdfWriter()
# add the "watermark" (which is the new pdf) on the existing page
for i in range(len(existing_pdf.pages)):
page = reader.pages[i]
width = float(page.mediabox.width)
height = float(page.mediabox.height)
# actual size of the pdf file
lox = 0.5*float(page.mediabox.width)*25.4/72
locy = 0.5*float(page.mediabox.height)*25.4/72
print(width,height)
#print(2*locx,2*locy)
textsize=width/20 # text size relative to width of pdf
textsize2=height/20
print("textsize",textsize)
faktor=3
drawText(packet,0.5*width-faktor*textsize, 0.5*height-faktor*textsize2,text,textsize)
new_pdf = PdfReader(packet)
page = existing_pdf.pages[i]
page.merge_page(new_pdf.pages[0])
output.add_page(page)
# finally, write "output" to a real file
outputStream = open(output_pdf, "wb")
output.write(outputStream)
outputStream.close()
Example usage
getPdfFiles()
change the path to where your pdf files will be copied 'C:/Users/xxxx/Documents/pdfcopy/'
for fl in listofpdfFiles:
add_text_to_pdf(fl, 'C:/Users/xxxx/Documents/pdfcopy/'+fl.__str__(), "Vorläufige Plan")
print("finished")
Similar posts
water mark on plans with python script
0 comments
There are no comments.