Last active
February 21, 2024 02:58
-
-
Save cynthiahqy/7ee66d9eb26ee0ae412b18234017b3bb to your computer and use it in GitHub Desktop.
script for adding blank pages between pdf pages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import sys, getopt, os | |
try: | |
from PyPDF2 import PdfReader, PdfWriter | |
# print("pypdf2 Already installed") | |
except ImportError as e: | |
print("Error -> ", e) | |
## adapted from: | |
## https://stackoverflow.com/questions/46569188/adding-blank-page-to-odd-paged-pdf-in-python | |
## https://github.com/mstamy2/PyPDF2/blob/master/Sample_Code/basic_features.py | |
def add_blank(ifile, ofile): | |
try: | |
with open(ifile, 'rb') as input1: | |
pdf=PdfReader(input1) | |
if pdf.is_encrypted: | |
print(f"The file {ifile} is encrypted and cannot be processed.") | |
sys.exit(1) | |
numPages=len(pdf.pages) | |
print('Adding blank pages to', ifile, 'with', numPages, 'pages') | |
outPdf=PdfWriter() | |
for i in range(numPages): | |
outPdf.add_page(pdf.pages[i]) | |
outPdf.add_blank_page() | |
with open(ofile, 'wb') as outStream: | |
outPdf.write(outStream) | |
print('Output file is :', ofile) | |
except: | |
print("something went wrong") | |
## adapted from https://www.tutorialspoint.com/python/python_command_line_arguments.htm | |
def main(argv): | |
inputfile = '' | |
outputfile = '' | |
try: | |
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) | |
except getopt.GetoptError: | |
print('add_blank_pages.py -i <inputfile> -o <outputfile>') | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print('add_blank_pages.py -i <inputfile> -o <outputfile>') | |
sys.exit() | |
elif opt in ("-i", "--ifile"): | |
inputfile = arg | |
elif opt in ("-o", "--ofile"): | |
outputfile = arg | |
if outputfile.endswith('.pdf'): | |
pass | |
else: | |
outputfile = outputfile + '.pdf' | |
try: | |
if os.path.isfile(inputfile): | |
add_blank(inputfile, outputfile) | |
else: | |
print(f"Input file {inputfile} does not exist.") | |
sys.exit(1) | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
sys.exit(1) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to use
pyPDF2
v3.0.0 -- eventually update topypdf