From 0276bb18b2b880f5f7875896c9b7b8c0020802b7 Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Thu, 13 Jul 2023 11:51:29 -0500 Subject: [PATCH] new: Added normalize-pdf-pagewidth.py --- README.md | 2 +- normalize-pdf-pagewidth.py | 48 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 normalize-pdf-pagewidth.py diff --git a/README.md b/README.md index 20e00cb..555b0af 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![Number of scripts](https://img.shields.io/badge/number_of_scripts-35-blue) +![Number of scripts](https://img.shields.io/badge/number_of_scripts-36-blue) # Random Scripts This repository is for random scripts I wrote mostly for personal use. diff --git a/normalize-pdf-pagewidth.py b/normalize-pdf-pagewidth.py new file mode 100644 index 0000000..8cbc5d7 --- /dev/null +++ b/normalize-pdf-pagewidth.py @@ -0,0 +1,48 @@ +#!/bin/env python3 + +# This script resized all pages of a given pdf to make them all the same width. +# It can be set up to make them all the same as the min width of the given pdf, +# or the max width, or a custom width. + +from argparse import ArgumentParser +from pypdf import PdfReader, PdfWriter +from pathlib import Path + +parser = ArgumentParser( + prog = 'Normalize PDF pagewidth', + description = 'A small program that does exactly what it says', + epilog = 'For each input file \'input.pdf\', the output file will be named \'input-norm.pdf\'' +) + +parser.add_argument('filename', help = 'The name of the input file. Multiple files can be supplied at once.', nargs = '+') +parser.add_argument('-w', '--width', default = 'min', help = 'The desired width. Can be \'max\', \'min\', or a number in pixels. Defaults to min.') +args = vars(parser.parse_args()) + +w = args['width'] +if w != 'min' and w != 'max' and not w.isnumeric(): + print('Invalid width. Only min, max or numeric values are supported.') + exit(-1) + +for file in args['filename']: + print('Processing ' + file + '...') + try: + reader = PdfReader(file) + except: + print('There was some error trying to read the file.') + else: + pages = reader.pages + outfile = Path(file).stem + '-norm.pdf' + if w == 'min': + outw = min([pages[i].mediabox.width for i in range(len(pages))]) + elif w == 'max': + outw = max([pages[i].mediabox.width for i in range(len(pages))]) + else: + outw = w + writer = PdfWriter() + for page in pages: + dim = page.mediabox + outh = dim.height * (outw / dim.width) + page.scale_to(width = outw, height = outh) + writer.add_page(page) + with open(outfile, 'wb+') as f: + writer.write(f) \ No newline at end of file