Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PyPDF2.PdfFileMerger only writes first pdf

I have several Pdfs that I want to merge together. To do this I referenced this https://pythonhosted.org/PyPDF2/PdfFileMerger.html#PyPDF2.PdfFileMerger.write Documentation as well as this Merge PDF files post as reference.
My code reads from the the directory where my pdfs lie and tries to write the new pdf into another directory

    def concatenate_pdfs(path_to_pdf_dir, output_dir):
        """merge all the pdfs that lie in output_dir into one pdf and store it in path_to_pdf_dir"""
        merger = PyPDF2.PdfFileMerger()
        for filepath in glob(f'{output_dir}*.pdf'):
            merger.append(filepath)
        merger.write(f'{path_to_pdf_dir}/output.pdf')
        merger.close()

The new pdf is created but only with the first pdf that gets parsed.

The same problem occurs when I do it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def concatenate_pdfs(path_to_pdf_dir, output_dir):
    """merge all the pdfs that lie in output_dir into one pdf and store it in path_to_pdf_dir"""
    merger = PyPDF2.PdfFileMerger()
    f1 = 'path_to_first_pdf'
    f2 = 'path_to_second_pdf'
    f3 = 'path_to_nth_pdf'
    merger.append(f1)
    merger.append(f2)
    merger.append(f3)
    merger.write(f'{path_to_pdf_dir}/output.pdf')
    merger.close()

In this case only f1 gets written to my output.pdf

>Solution :

For posterity:

Add files to the merger with merger.append(open(filepath, 'rb')) because PyPDF has some odd internal issues with file reader/writers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading