Append a text on the fly to a pdf

If you want to add a page with a text created on the fly to an existing pdf, use this code. I made this to add a valutation to a student work made in a pdf. When you run this script it asks you to add the name, grade, date and then it attaches the text in a new page at the end and saves a new pdf.

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from glob import glob
import os

def createNewPdf(text):
    packet = io.BytesIO()
    # create a new PDF with Reportlab
    can = canvas.Canvas(packet, pagesize=letter)
    counter = 0
    for line in text:
        can.drawString(50, 700 - counter, line)
        counter += 20
    can.save()
    # move to the beginning of the StringIO buffer
    packet.seek(0)
    # read the pdf yet created
    new_pdf = PdfFileReader(packet)
    return new_pdf


def readExistigPdf():
    # read your existing PDF
    print("Current directory", os.getcwd())
    filename = glob("*.pdf")[0]
    existing_pdf = PdfFileReader(open(filename, "rb"))
    return existing_pdf, filename


def merge(page=0):
    output = PdfFileWriter()
    page = existing_pdf.getPage(page)
    page.mergePage(new_pdf.getPage(0))
    # add the "watermark" (which is the new pdf) on the existing page
    output.addPage(page)
    # finally, write "output" to a real file
    with open(filename[:-4] + "_valutazione.pdf", "wb") as outputStream:
        output.write(outputStream)

def mergeFull(page=0):
    output = PdfFileWriter()
    merger = PdfFileMerger()
    for file in [existing_pdf, new_pdf]:
        merger.append(file)
    # add the "watermark" (which is the new pdf) on the existing page
    
    # finally, write "output" to a real file
    with open(filename[:-4] + "_valutazione.pdf", "wb") as outputStream:
        merger.write(outputStream)


testo = """
This is a test

Valutazione 16/18


""".splitlines()


new_pdf = createNewPdf(testo)
existing_pdf, filename = readExistigPdf()
# Put a page as argument starting from 0=first page
mergeFull()
os.startfile(filename[:-4] + "_valutazione.pdf")

Version 2

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from glob import glob
import os
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
filename = filedialog.askopenfilename(initialdir = ".",title = "Select file",filetypes = (("pdf files","*.pdf"),("all files","*.*")))






def createNewPdf(text):
    packet = io.BytesIO()
    # create a new PDF with Reportlab
    can = canvas.Canvas(packet, pagesize=letter)
    counter = 0
    for line in text:
        can.drawString(50, 700 - counter, line)
        counter += 20
    can.save()
    # move to the beginning of the StringIO buffer
    packet.seek(0)
    # read the pdf yet created
    new_pdf = PdfFileReader(packet)
    return new_pdf


def readExistigPdf():
    # read your existing PDF
    # print("Current directory", os.getcwd())
    # filename = glob(os.getcwd() + "\\*.pdf")[0]
    # print(filename)
    existing_pdf = PdfFileReader(open(filename, "rb"))
    return existing_pdf, filename


def merge(page=0):
    output = PdfFileWriter()
    page = existing_pdf.getPage(page)
    page.mergePage(new_pdf.getPage(0))
    # add the "watermark" (which is the new pdf) on the existing page
    output.addPage(page)
    # finally, write "output" to a real file
    with open(filename[:-4] + "_valutazione.pdf", "wb") as outputStream:
        output.write(outputStream)

def mergeFull(page=0):
    output = PdfFileWriter()
    merger = PdfFileMerger()
    for file in [existing_pdf, new_pdf]:
        merger.append(file)
    # add the "watermark" (which is the new pdf) on the existing page
    
    # finally, write "output" to a real file
    with open(filename[:-4] + "_valutazione.pdf", "wb") as outputStream:
        merger.write(outputStream)

prova = input("Prova: ")
name = input("Nome: ")
voto = input("voto: ")
data = input("Data: ")

testo = f"""
Prova {prova}
Alunno/a: {name}
Valutazione {voto}

     Castelnuovo Cilento, {data}
Prof. Giovanni Gatto
""".splitlines()


new_pdf = createNewPdf(testo)
existing_pdf, filename = readExistigPdf()
# Put a page as argument starting from 0=first page
mergeFull()
os.startfile(filename[:-4] + "_valutazione.pdf")

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.