Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PDF Merge Tool
#1
I want to create the Collate (merge) PDF files from page level pdf. When i am executing the below coding it showing below error message, but 4 pdf files available in the input file path. Please help us to resolve this issue. Thanks in Advance...

Error:
FileNotFoundError: [Errno 2] No such file or directory: '0001.pdf'
import contextlib
import PyPDF2
import os


user_input = input("Enter the path of your file: ")
filePath = user_input
test = []

print(filePath)
pdf_files_list = os.listdir(filePath)

"""
for pdf in pdf_files_list:
    test.append(os.path.splitext(pdf)[0])
    pdf_files_list = os.path.splitext(pdf)
    print(pdf_files_list)
"""    
    

print(pdf_files_list)


with contextlib.ExitStack() as stack:
    pdf_merger = PyPDF2.PdfFileMerger()
    print(pdf_merger)
    
    
    
    pdf = os.path.join(filePath)
    print(pdf)
    
    files = [stack.enter_context(open(pdf, 'rb')) for pdf in pdf_files_list]
    print(files)
    for f in files:
        pdf_merger.append(f)
    with open('Merged-PDF.pdf', 'wb') as f:
        pdf_merger.write(f)
snippsat write Dec-11-2021, 09:33 PM:
Added code tag in your post,look at BBCode on how to use.
Reply
#2
on line-32 add this:
os.chdir(filePath)
The reason for this is that os.listdir() return relative path,
then if not run code in same folders as pdf's will get FileNotFoundError.
Reply
#3
FYI: There are packages available that may do what you need. see: https://pypi.org/project/merge-pdf/
Reply
#4
(Dec-11-2021, 09:55 PM)snippsat Wrote: on line-32 add this:
os.chdir(filePath)
The reason for this is that os.listdir() return relative path,
then if not run code in same folders as pdf's will get FileNotFoundError.

Many thanks for your support...
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020