Skip to content

Instantly share code, notes, and snippets.

@tatsu38
Last active June 23, 2023 05:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatsu38/31316daf1200ab0146c33051341c4d72 to your computer and use it in GitHub Desktop.
Save tatsu38/31316daf1200ab0146c33051341c4d72 to your computer and use it in GitHub Desktop.
PythonとpikepdfでPDFを右綴じ(R2L)にする
#!/usr/bin/env python3
import pikepdf
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('input')
parser.add_argument('output')
parser.add_argument('--pagelayout', type=str, default='TwoPageRight', choices=['SinglePage', 'OneColumn', 'TwoColumnLeft', 'TwoColumnRight', 'TwoPageLeft', 'TwoPageRight'])
parser.add_argument('--direction', type=str, default='R2L', choices=['L2R', 'R2L'])
args = parser.parse_args()
pdf = pikepdf.open(args.input)
version = pdf.pdf_version
if args.pagelayout is not None:
if not hasattr(pdf.Root, 'PageLayout') \
or pdf.Root.PageLayout != '/' + args.pagelayout:
pdf.Root.PageLayout = pikepdf.Name('/' + args.pagelayout)
if 'TwoPageLeft' == args.pagelayout or 'TwoPageRight' == args.pagelayout:
version = max(version, '1.5')
if args.direction is not None:
if not hasattr(pdf.Root, 'ViewerPreferences'):
pdf.Root.ViewerPreferences = pikepdf.Dictionary()
if not hasattr(pdf.Root.ViewerPreferences, 'Direction') \
or pdf.Root.ViewerPreferences.Direction != '/' + args.direction:
pdf.Root.ViewerPreferences.Direction = pikepdf.Name('/' + args.direction)
pdf.save(args.output, min_version=version, linearize=True)
# sample:
# ./r2l.py old.pdf new.pdf
# ./r2l.py old.pdf new.pdf --pagelayout TwoPageLeft --direction L2R
#
# --pagelayout:
# SinglePage -> 単一ページ表示
# OneColumn -> スクロールを有効にする
# TwoPageLeft -> 見開きページ表示
# TwoColumnLeft -> 見開きページでスクロール
# (default)TwoPageRight -> 見開きページ表示 + 見開きページ表示で表紙を表示(表紙は単独表示)
# TwoColumnRight -> 見開きページでスクロール + 見開きページ表示で表紙を表示(表紙は単独表示)
#
# --direction:
# L2R -> 左綴じ(横書き)
# (default)R2L -> 右綴じ(縦書き)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment