PDF merger using python

Introduction

  • As a college student, while doing assignments I'll have to merge pdf documents together. Now this can be done by going to some website riddled with ads and maybe even put a watermark on your precious assignment that you worked your ass off to do.

  • Or... you can make a python script that does it for you. So that's what we are gonna do today. This is also from a video by 'Internet made coder'.

Libraries

  • The libraries necessary for this project are :

    • PyPDF2

    • os

import PyPDF2
import os

Code

  • First we need to create a PdfMerger object from the PyPDF2 library.
merger=PyPDF2.PdfMerger()
  • We then iterate through each file in a specified directory to find pdfs

  • We then check if the files are pdfs and if they are we append them to the merger object.

  • After we have iterated through every file, we can finally write all the files appended to the merger object as the final pdf.

for file in os.listdir(os.curdir): #os.curdir for current directory
    if file.endswith(".pdf"):
        merger.append(file)
merger.write("combined.pdf")
  • This is a very short piece of code that merges all the pdfs in a specified directory.

Make it all a simple shell command

  • Now if you are using linux, like me right now. I can also help you make this work using a shell script.

  • first we need to create a shell script.

  • It is preferred to place this script file in a directory that is in your path environment (preferebly ~/.local/bin)

  • We start the script with a shebang (#!), this basically tells it what kind of shell script we are using here im using zsh

#!usr/bin/zsh
  • We then write the command used to execute the python file this can include the dir to the python file.
python path/to/directory/script.py
  • If the script takes command line inputs like in our youtube video downloader we made last time, we can include that as show below with ($1) the number denoted the placement of the arguement.
python path/to/directory/script/py $1

Conclusion

Did you find this article valuable?

Support The Journey by becoming a sponsor. Any amount is appreciated!