Created
February 4, 2025 01:14
-
-
Save jkerhin/e7d179c8da32c314c1de8d09ed2cda53 to your computer and use it in GitHub Desktop.
Combine and rotate PDFs
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
| """Combine multiple PDFs into one, optionally rotating them | |
| Requires "pypdf" library, tested with v5.2.0 at time of writing | |
| MIT No Attribution | |
| Copyright (c) 2025 Joe Kerhin | |
| Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
| """ | |
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = [ | |
| # "pypdf>5.0", | |
| # ] | |
| # /// | |
| import argparse | |
| from pathlib import Path | |
| from typing import List | |
| from pypdf import PdfReader, PdfWriter | |
| def combine_and_rotate(filenames: List[str], rot_deg_cw: int) -> PdfWriter: | |
| writer = PdfWriter() | |
| for fname in filenames: | |
| with PdfReader(fname) as reader: | |
| for page in reader.pages: | |
| writer.add_page(page.rotate(rot_deg_cw)) | |
| return writer | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Combine and rotate PDFs") | |
| parser.add_argument( | |
| "-r", | |
| "--rotation-deg-cw", | |
| default=0, | |
| type=int, | |
| help="Degrees (clockwise) to rotate each page of input PDFs", | |
| ) | |
| parser.add_argument( | |
| "-o", | |
| "--output-name", | |
| type=str, | |
| help="Output file name. If not provided, combine input filenames", | |
| ) | |
| parser.add_argument("filenames", nargs="+") | |
| args = parser.parse_args() | |
| out_name = args.output_name | |
| if out_name is None: | |
| out_name = "_".join(Path(f).stem for f in args.filenames) | |
| out_name += ".pdf" | |
| writer = combine_and_rotate(args.filenames, args.rotation_deg_cw) | |
| with open(out_name, "wb") as hdl: | |
| writer.write(hdl) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment