Skip to content

Instantly share code, notes, and snippets.

@cowdinosaur
Created July 15, 2024 01:43
Show Gist options
  • Save cowdinosaur/c42c09ada83ac1529ac57cdbb8dd8d96 to your computer and use it in GitHub Desktop.
Save cowdinosaur/c42c09ada83ac1529ac57cdbb8dd8d96 to your computer and use it in GitHub Desktop.
Certificate Generator
import pandas as pd
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from PyPDF2 import PdfWriter, PdfReader
import io
def create_certificate(name, base_pdf, output_pdf):
packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=A4)
# Set font and size
fontname = "Helvetica"
fontsize = 24
page_width = A4[0]
text_width = can.stringWidth(name, fontname, fontsize)
x_position = (page_width - text_width) / 2 + 125
textobject = can.beginText()
textobject.setFont(fontname, fontsize)
textobject.setTextOrigin(x_position, 330)
textobject.textLine(name)
textobject.setFillGray(0.4)
can.drawText(textobject)
can.save()
# Move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfReader(packet)
existing_pdf = PdfReader(open(base_pdf, "rb"))
output = PdfWriter()
# Add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.pages[0]
page.merge_page(new_pdf.pages[0])
output.add_page(page)
# Finally, write "output" to a real file
with open(output_pdf, "wb") as outputStream:
output.write(outputStream)
def main():
# Load the CSV file
df = pd.read_csv("names.csv")
base_pdf = "base_certificate.pdf"
output_folder = "certificates/"
for index, row in df.iterrows():
name = row['Name']
output_pdf = f"{output_folder}certificate_{index + 1}.pdf"
create_certificate(name, base_pdf, output_pdf)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment