'modify an existing pdf in python without creating another one

I am a beginner on python, I am trying to modify an existing pdf but I can't find any documentation that allows me to modify the pdf without creating another one. Most of the examples create another pdf. I would like to open a pdf, modify it and save the modification to the same pdf without creating another one. I am using python 3.9 and here is my code that does not work and is not really what I want because it creates a new pdf in output

from fpdf import FPDF
from pdfrw import PageMerge, PdfReader, PdfWriter

IN_FILEPATH = "../test.pdf"
OUT_FILEPATH = "../test1.pdf"
ON_PAGE_INDEX = 1
UNDERNEATH = False  

def new_content():
    fpdf = FPDF()
    fpdf.add_page()
    fpdf.set_font("helvetica", size=36)
    fpdf.text(50, 50, "Hello!")
    reader = PdfReader(fdata=bytes(fpdf.output()))
    return reader.pages[0]

writer = PdfWriter(trailer=PdfReader(IN_FILEPATH))
PageMerge(writer.pagearray[ON_PAGE_INDEX]).add(new_content(), prepend=UNDERNEATH).render()
writer.write(OUT_FILEPATH)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source