T
T
timka2282021-02-21 10:19:44
Python
timka228, 2021-02-21 10:19:44

How to fill a PDF in Python?

There is such a task: every month the script needs to send me a report as a pdf file. Here I am trying to fill in the finished pdf template. It is necessary that a copy of this template document be created, but already filled out.
I tried in the template pdf document to write "macros" in the places where you need to insert text, such as {date} (insert the date in this place in the document), {income} (insert income for the month), and so on. I wrote the following script with the PyPDF2 library, which only reads the template:

from PyPDF2 import PdfFileReader

pdf_document = "/root/source/statistics_template.pdf" #шаблон отчета
with open(pdf_document, "rb") as filehandle:  
    pdf = PdfFileReader(filehandle)
    pdf_writer = PdfFileWriter()
   
    info = pdf.getDocumentInfo()
    pages = pdf.getNumPages()
    
    for i in range(pages):
        page = pdf.getPage(i)
        
        page_new_text = page.extractText().replace('{date}', '01.01.2021').replace('{income}', '13 000 000') #чтение текста шаблона, замена макросов на значения

But what's next? How to write the page_new_text variable to the text of a new pdf file?
Or am I not doing it right at all? I just came up with this idea, maybe it could be better. Please help please.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question