1 year ago
#356782
bas25z
Using ReportLab and PyPDF2, how do I diagonally align text through the middle of a landscape pdf/power point?
I am trying to diagonally place a text watermark over pdf slides. The issue I am having is that if the text is too long or short it is not centered correctly or it gets cut off due to the x and y coordinates of the drawstring method being hardcoded. Is there a way to center the text watermark diagonally each time regardless of the length of the text?
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, landscape
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.lib.colors import HexColor
from reportlab.lib.units import inch
import os
"""
Refer to an image if you want to add an image to a watermark.
Fill in text if you want to watermark with text.
Alternatively, following settings will skip this.
picture_path = None
text = None
"""
text = 'SAMPLE'
# Folder in which PDF files will be watermarked. (Could be shared folder)
folder_path = '/Users/b/Documents/watermark'
c = canvas.Canvas('watermarkText.pdf', pagesize = landscape(letter))
width, height = landscape(letter)
print(width,height)
if text:
c.translate(inch,inch)
c.setFontSize(22)
c.setFont('Helvetica-Bold', 50)
c.setFillColorRGB(0.55,0.55,0.55)
c.setFillAlpha(0.3)
c.rotate(30)
c.drawString(2.5*inch, -.5*inch, text)
c.save()
watermark = PdfFileReader(open("watermarkText.pdf", "rb"))
for file in os.listdir(folder_path):
if file.endswith(".pdf"):
output_file = PdfFileWriter()
input_file = PdfFileReader(open(folder_path + '/'+ file, "rb"))
page_count = input_file.getNumPages()
for page_number in range(page_count):
input_page = input_file.getPage(page_number)
input_page.mergePage(watermark.getPage(0))
output_file.addPage(input_page)
output_path = folder_path + '/'+ file.split('.pdf')[0] + '_watermarked' + '.pdf'
with open(output_path, "wb") as outputStream:
output_file.write(outputStream)
python
reportlab
pypdf
0 Answers
Your Answer