Created
March 21, 2023 07:55
-
-
Save mybeky/42162e8ec1e6417a8c404e133e5ed0a8 to your computer and use it in GitHub Desktop.
A Python script to merge every two pages of a PDF file into one page
This file contains 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
# pip install PyMuPDF | |
# usage: python merge.py input_file.pdf | |
import sys | |
import fitz | |
def merge_pages(input_file, output_file): | |
with fitz.open(input_file) as doc: | |
new_doc = fitz.open() | |
for i in range(0, doc.page_count, 2): | |
page_rect = doc[i].rect | |
rect = fitz.Rect(0, 0, page_rect.width, page_rect.height) | |
new_page = new_doc.new_page(width=rect.width, height=rect.height * 2) | |
new_page.show_pdf_page(rect, doc, i) | |
if i + 1 < doc.page_count: | |
rect = fitz.Rect( | |
0, doc[i].rect.height, page_rect.width, page_rect.height * 2 | |
) | |
new_page.show_pdf_page(rect, doc, i + 1) | |
new_doc.save(output_file) | |
if __name__ == "__main__": | |
try: | |
input_file = sys.argv[1] | |
except IndexError: | |
print("Usage: python merge.py input_file.pdf") | |
sys.exit(1) | |
if not input_file.endswith(".pdf"): | |
print("Input file must be a PDF file") | |
sys.exit(1) | |
output_file = input_file[:-4] + "_merged.pdf" | |
merge_pages(input_file, output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment