-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreg_pdf_v2.py
60 lines (49 loc) · 2.21 KB
/
reg_pdf_v2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import io
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase.pdfmetrics import stringWidth
from decimal import Decimal
def add_text_to_pdf(input_pdf_path, output_pdf_path, text):
packet = io.BytesIO()
can = canvas.Canvas(packet)
text_width = Decimal(stringWidth(text, 'Helvetica', 12))
text_height = 12 # Altura del texto
existing_pdf = PdfReader(open(input_pdf_path, "rb"))
page = existing_pdf.pages[0] # Obtiene la primera página
page_width = page.mediabox.width
page_height = page.mediabox.height
x = page_width - text_width - Decimal(20) # Resta el ancho del texto y un margen de 20 puntos
y = page_height - Decimal(10) # Resta un margen de 10 puntos
# Dibuja un rectángulo blanco detrás del texto
can.setFillColorRGB(1, 1, 1) # Color blanco
can.setStrokeColorRGB(1, 1, 1) # Color blanco para el borde
can.rect(float(x), float(y) - text_height + 10, float(text_width), text_height, fill=1, stroke=1) # Ajusta la posición y del rectángulo
# Dibuja el texto
can.setFillColorRGB(0, 0, 0) # Color negro
can.drawString(float(x), float(y), text)
can.save()
packet.seek(0)
new_pdf = PdfReader(packet)
existing_pdf = PdfReader(open(input_pdf_path, "rb"))
output = PdfWriter()
page = existing_pdf.pages[0]
page.merge_page(new_pdf.pages[0])
output.add_page(page)
for page_num in range(1, len(existing_pdf.pages)):
output.add_page(existing_pdf.pages[page_num])
with open(output_pdf_path, "wb") as outputStream:
output.write(outputStream)
def process_files(directory):
for filename in os.listdir(directory):
if filename.endswith(".pdf"):
input_pdf_path = os.path.join(directory, filename)
output_pdf_path = input_pdf_path # Sobreescribe el archivo original
text = filename[:10]
add_text_to_pdf(input_pdf_path, output_pdf_path, text)
if __name__ == "__main__":
directory = input("Ingrese la ruta del directorio donde están ubicados los archivos PDF: ")
directory = directory.replace("\\", "\\\\")
process_files(directory)
print("Proceso terminado.")