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
I know this was a kind of short blog but my exams kind of didnt let me put too much time on this I'm sorry.
But i did learn about the PyPDF2 library and about hwo to make a custom shell command today.
Thank you for reading and like ,always, any advice is accepted.
git - https://github.com/P-M-Manmohan/Python/tree/main/scripts_make_life_easier
original video - https://www.youtube.com/watch?v=vEQ8CXFWLZU&t=600s