Created
July 22, 2021 14:24
-
-
Save mkyt/72592c50c49f02b235baa9ba216168b7 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
set_pdf_dir.py | |
Set direction and/or page layout properties of PDF files. | |
Usage: | |
$ ./set_pdf_dir.py -l r2l -d book -o my_pdf_1.pdf my_pdf_2.pdf | |
""" | |
import argparse | |
from enum import Enum | |
from pathlib import Path | |
import pikepdf | |
class Direction(Enum): | |
R2L = "/R2L" | |
L2R = "/L2R" | |
class PageLayout(Enum): | |
SinglePage = "/SinglePage" | |
OneColumn = "/OneColumn" | |
TwoPageLeft = "/TwoPageLeft" | |
TwoPageRight = "/TwoPageRight" | |
TwoColumnLeft = "/TwoColumnLeft" | |
TwoColumnRight = "/TwoColumnRight" | |
def set_direction(doc, d): | |
doc.root.ViewerPreferences = pikepdf.Dictionary( | |
{ | |
"/Direction": pikepdf.Name(d.value), | |
} | |
) | |
def set_layout(doc, pl): | |
doc.root.PageLayout = pikepdf.Name(pl.value) | |
cmd_arg_dir = { | |
"r2l": Direction.R2L, | |
"l2r": Direction.L2R, | |
} | |
cmd_arg_layout = { | |
"single": PageLayout.SinglePage, | |
"facing": PageLayout.TwoPageLeft, | |
"book": PageLayout.TwoPageRight, | |
} | |
parser = argparse.ArgumentParser( | |
description="Set direction / page layout for PDF files." | |
) | |
parser.add_argument( | |
"--direction", "-d", choices=list(cmd_arg_dir.keys()), help="page direction" | |
) | |
parser.add_argument( | |
"--layout", "-l", choices=list(cmd_arg_layout.keys()), help="page layout" | |
) | |
parser.add_argument( | |
"--overwrite", | |
"-o", | |
action="store_true", | |
default=False, | |
help="overwrite existing file", | |
) | |
parser.add_argument("input_files", type=Path, nargs="+", help="input PDF files") | |
args = parser.parse_args() | |
for f in args.input_files: | |
if f.suffix.lower() != ".pdf": | |
continue | |
print('processing "{}"'.format(f)) | |
doc = pikepdf.Pdf.open(f, allow_overwriting_input=args.overwrite) | |
if args.direction: | |
set_direction(doc, cmd_arg_dir[args.direction]) | |
if args.layout: | |
set_layout(doc, cmd_arg_layout[args.layout]) | |
if args.overwrite: | |
doc.save() | |
else: | |
doc.save(f.with_suffix(".modified.pdf")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment