Search code examples
pythonpdffpdfpypdf

Merge 2 PDF pages into 1 page


I would need a solution to combine PDF files. I needed some possibility to add text to the PDF template. I have been working so far by creating a PDF file with text using FPDF and merging it using PdfFileMerger. But it happens to me that he creates a new PDF file from both pages, and I should only have the text from the PDF that I generated using FPDF be generated on the PDF template.

This solution doesn't work for me because it tells me that there is no PyPDF2.pdf even though PyPDF2.pdf is properly installed: Merge two pages into pdf into one page pdf

Here is what I do with FPDF:

#work in jupyter

 
from fpdf import FPDF
from pathlib import Path
from PyPDF2 import PdfFileMerger

profile = FPDF()
profile.add_page()
profile.set_font('Arial', 'B', 16)
profile.cell(500, 200, 'Edi Graovac!')
profile.output("temp.pdf", 'F')

merger = PdfFileMerger(strict=False)
profile_pdf=open("temp.pdf", 'rb')
template=open(template_path, 'rb')

merger.append(template)
merger.merge(0,profile_pdf)
merger.write(save_path)
merger.close()

Solution

  • As I've now noted where you reference, the current usage of PyPDF has changed since that code was posted. Particularly, in regards to the use of PyPDF2.pdf, as noted here: "PyPDF2.pdf no longer exists. You can import from PyPDF2 directly". So if you are trying the solution you referenced, you should be using from PyPDF2 import PageObject, the first two lines relative the reference code should be something like this:

    from PyPDF2 import PdfFileWriter, PdfFileReader
    from PyPDF2  import PageObject
    

    Probably relative what you want in your version, more like: from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger, PageObject. Maybe.