Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python PDF-Merger

ratwolf

Active Coder
A small program that merges all PDF files in a directory into a single PDF file in alphabetical order, without prioritizing uppercase letters.


Python:
import os
from pypdf import PdfWriter
 
# Directory containing PDF files
directory = r"/Users/ralf/Downloads"
 
# Initialize PdfWriter
merger = PdfWriter()
 
# Get and sort the list of PDF files in the directory (case-insensitive)
pdf_files = sorted([f for f in os.listdir(directory) if f.endswith(".pdf")], key=str.lower)
 
# Loop through each sorted PDF file
for filename in pdf_files:
    file_path = os.path.join(directory, filename)
    print(f"Adding: {file_path}")
    merger.append(file_path)
 
# Output file name
output_path = os.path.join(directory, "finalFile.pdf")
 
# Write the merged PDF to the output file
merger.write(output_path)
merger.close()
 
print(f"PDF files merged successfully into {output_path}")
 
Solution
what would be cool with this, if you added a if filename == "finalFile.pdf": return

that way if it finds the file you have already merged your dont get a merger of the merger 🙂
Thanks for the tip.
There is actually nothing that cannot be improved, but it depends on the intended use of the program.
what would be cool with this, if you added a if filename == "finalFile.pdf": return

that way if it finds the file you have already merged your dont get a merger of the merger 🙂
 
what would be cool with this, if you added a if filename == "finalFile.pdf": return

that way if it finds the file you have already merged your dont get a merger of the merger 🙂
Thanks for the tip.
There is actually nothing that cannot be improved, but it depends on the intended use of the program.
 
Solution

Buy us a coffee!

Back
Top Bottom