water mark on plans with python script
Published Oct. 16, 2024, 10:02 a.m. 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 reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import io
# if you dont have admin rights you need this line of codes, change UserName with you user name #import sys #sys.path.append("/tmp/TEST") #c:\users\UserName\appdata\local\programs\python\python39\lib\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
def drawText(packet,width,height,text,textsize):
c = canvas.Canvas(packet, landscape(pagesize=A0))
c.setFont('Vera', textsize)
c.translate(0, 0)
c.translate(width, height)
c.rotate(45)
c.drawString(0, 0, text)
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/25 # text size relative to width of pdf
drawText(packet,0.5*width-50, 0.5*height-50,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
add_text_to_pdf("testplan2.pdf", "testplan2_modified.pdf", "Draf Plan")
add_text_to_pdf("testplan3.pdf", "testplan3_modified.pdf", "Draf Plan")
print("finished")
Similar posts
creating watermark for multiple files modified
0 comments
There are no comments.