Created
April 18, 2024 13:03
-
-
Save elnikkis/5bbea45c4cc0f4177ec2c38c49fc5288 to your computer and use it in GitHub Desktop.
PDF分割とマージ
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
''' | |
PDFをマージして見開きにする | |
''' | |
import subprocess | |
import tempfile | |
from pathlib import Path | |
def main(args): | |
with tempfile.TemporaryDirectory() as tmpdir: | |
tmpdir_path = Path(tmpdir) | |
unitefile_path = str(tmpdir_path / 'united.pdf') | |
# unite pdfs | |
cmd = ['pdfunite'] + args.pdffiles + [unitefile_path] | |
subprocess.run(cmd, check=True) | |
# convert 2-in-1 | |
cmd = ['pdfjam', '--nup', '2x1', '--landscape', '--outfile', args.outfile, unitefile_path] | |
subprocess.run(cmd, check=True) | |
def parse_args(): | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-o', dest='outfile', nargs='?', default='twoside.pdf') | |
parser.add_argument('pdffiles', nargs='+') | |
return parser.parse_args() | |
if __name__ == '__main__': | |
args = parse_args() | |
main(args) |
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
''' | |
PDFを分割する | |
''' | |
import sys | |
import tempfile | |
import subprocess | |
from pathlib import Path | |
def main(args): | |
# parse arguments | |
ranges = [] | |
for r in args.ranges: | |
start_page, end_page = r.split('-') | |
try: | |
start_page = int(start_page) | |
end_page = int(end_page) | |
except ValueError: | |
print('Invalid page range given:', r, file=sys.stderr) | |
sys.exit(1) | |
else: | |
ranges.append((start_page, end_page)) | |
# Prepare temp dir | |
with tempfile.TemporaryDirectory() as tmpdir: | |
print(tmpdir) | |
tmpdir_path = Path(tmpdir) | |
# Split PDF | |
cmd = ['pdfseparate', args.pdf, str(tmpdir_path / 'separated-%d.pdf')] | |
subprocess.run(cmd, check=True) | |
# make pdf for each range | |
for s, e in ranges: | |
print(s, e) | |
names = [str(tmpdir_path / f'separated-{i}.pdf') for i in range(s, e+1)] | |
cmd = ['pdfunite'] + names + [f'paper_{s}-{e}.pdf'] | |
subprocess.run(cmd, check=True) | |
def parse_args(): | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('pdf') | |
parser.add_argument('ranges', nargs='+') | |
return parser.parse_args() | |
if __name__ == '__main__': | |
args = parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment