├── requirements.txt ├── samples ├── cover.pdf └── docs │ ├── example.pdf │ └── sample.pdf ├── screenshots ├── cover.png ├── divider.png └── collatepdf.png ├── setup.py ├── LICENSE ├── README.md ├── .gitignore └── collatepdf.py /requirements.txt: -------------------------------------------------------------------------------- 1 | pypdf 2 | reportlab 3 | -------------------------------------------------------------------------------- /samples/cover.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/samples/cover.pdf -------------------------------------------------------------------------------- /screenshots/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/screenshots/cover.png -------------------------------------------------------------------------------- /samples/docs/example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/samples/docs/example.pdf -------------------------------------------------------------------------------- /samples/docs/sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/samples/docs/sample.pdf -------------------------------------------------------------------------------- /screenshots/divider.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/screenshots/divider.png -------------------------------------------------------------------------------- /screenshots/collatepdf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rossant/collatepdf/HEAD/screenshots/collatepdf.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | 4 | def parse_requirements(filename): 5 | """ Load requirements from a pip requirements file """ 6 | with open(filename, 'r') as f: 7 | return [line.strip() for line in f if line.strip() and not line.startswith('#')] 8 | 9 | 10 | setup( 11 | name='collatepdf', 12 | version='0.1.0', 13 | py_modules=['collatepdf'], 14 | install_requires=parse_requirements('requirements.txt'), 15 | entry_points={ 16 | 'console_scripts': [ 17 | 'collatepdf=collatepdf:main', 18 | ], 19 | }, 20 | ) 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Cyrille Rossant 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # collatepdf 2 | 3 | A simple Python script to **collate multiple PDFs into a single PDF** with: 4 | 5 | * an optional cover page, 6 | * automatic TOC generation with global page numbering, 7 | * automatic page resizing to ensure all pages in the collated PDF have the same dimensions, 8 | * an overlay bar on each page with the current file name and global page number. 9 | 10 | **Note:** this is a quick-and-dirty, alpha-quality script I wrote for my own needs. Use at your own risks. Please feel free to improve it if you find it useful. 11 | 12 | ## Structure of the collated PDF 13 | 14 | - Optional cover PDF 15 | - Auto-generated table of contents 16 | - Optional divider pages between documents 17 | - PDF documents 18 | 19 | ![](screenshots/collatepdf.png) 20 | 21 | ## Cover and table of contents 22 | 23 | ![](screenshots/cover.png) 24 | 25 | ## Optional divider page and first document page with overlay bar 26 | 27 | ![](screenshots/divider.png) 28 | 29 | ## Installation 30 | 31 | Dependencies: 32 | 33 | - Python 34 | - pypdf 35 | - reportlab 36 | 37 | Installation instructions: 38 | 39 | ```bash 40 | git clone https://github.com/rossant/collatepdf.git 41 | cd collatepdf/ 42 | pip install -e . 43 | ``` 44 | 45 | ## Usage 46 | 47 | There are two steps: 48 | 49 | - Generate an `index.txt` page from your list of PDF documents to collate, and edit it manually to specify the optional divider pages. 50 | - Generate the collated PDF. 51 | 52 | ```bash 53 | # Create the index file. 54 | collatepdf makeindex samples/docs/*.pdf -o samples/index.txt 55 | 56 | # Optionally: manually edit samples/index.txt 57 | 58 | # Generate the collated PDF with a cover PDF. 59 | collatepdf makepdf samples/index.txt -c samples/cover.pdf -o samples/collated.pdf 60 | ``` 61 | 62 | ### Index file 63 | 64 | This is the sample index file generated by the first command above: 65 | 66 | ``` 67 | # Comments start with #. 68 | # Empty lines are ignored. 69 | # Index processing is stopped with `# STOP` on a line. 70 | # PDF files are included by putting their paths on each line. 71 | # Divider pages are included as follows: `@ Some title / Subtitle below`. 72 | 73 | @ samples/docs/example 74 | samples/docs/example.pdf 75 | 76 | @ samples/docs/sample 77 | samples/docs/sample.pdf 78 | ``` 79 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | 164 | collated.pdf 165 | index.txt 166 | -------------------------------------------------------------------------------- /collatepdf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | """ 5 | A tool to collate multiple PDFs into a single PDF, with automatic TOC generation, 6 | automatic page resizing, and overlay bar incrustation on each page with the current file name and 7 | global page number. 8 | 9 | pip install -r requirements.txt 10 | 11 | # Create the index file. 12 | ./collatepdf.py makeindex samples/docs/*.pdf -o samples/index.txt 13 | 14 | # Generate the collated PDF with a cover PDF. 15 | ./collatepdf.py makepdf samples/index.txt -c samples/cover.pdf -o samples/collated.pdf 16 | 17 | """ 18 | 19 | 20 | # ------------------------------------------------------------------------------------------------- 21 | # Imports 22 | # ------------------------------------------------------------------------------------------------- 23 | 24 | import argparse 25 | from contextlib import contextmanager 26 | import gc 27 | from io import BytesIO 28 | import os 29 | import os.path as op 30 | from pathlib import Path 31 | import sys 32 | 33 | from reportlab.pdfgen import canvas 34 | from reportlab.lib.colors import white 35 | from reportlab.lib.pagesizes import A4 36 | from reportlab.lib.units import cm, inch 37 | from reportlab.pdfbase.ttfonts import TTFont 38 | from reportlab.pdfbase import pdfmetrics 39 | from pypdf import PdfReader, PdfWriter, PageObject 40 | 41 | # NOTE: weird PDF bugs appear otherwise 42 | gc.disable() 43 | 44 | 45 | # ------------------------------------------------------------------------------------------------- 46 | # Parameters 47 | # ------------------------------------------------------------------------------------------------- 48 | 49 | class Bunch: 50 | def __init__(self, **kwargs): 51 | self.__dict__.update(kwargs) 52 | 53 | 54 | PARAMS = Bunch() 55 | 56 | # PARAMS.root_dir = '.' 57 | PARAMS.page_format = A4 # (8*inch, 10*inch) 58 | PARAMS.index_file = 'samples/index.txt' 59 | PARAMS.output_file = 'samples/collated.pdf' 60 | PARAMS.cover_file = '' # 'samples/cover.pdf' 61 | 62 | # TOC params 63 | PARAMS.toc_title = "Table of contents" 64 | PARAMS.toc_font_size = 12 65 | 66 | # Divider params 67 | PARAMS.divider_font_size = 24 68 | 69 | # Overlay params 70 | PARAMS.overlay_font_size = 12 71 | PARAMS.overlay_bgcolor = (.3, .6, .9) 72 | PARAMS.overlay_edgecolor = white 73 | PARAMS.overlay_textcolor = (0, 0, 0) 74 | PARAMS.overlay_opacity = 0.9 75 | PARAMS.overlay_w = 500 76 | PARAMS.overlay_h = 20 77 | PARAMS.overlay_x = 0.6 * inch 78 | PARAMS.overlay_y = 11.21 * inch 79 | PARAMS.overlay_x_text = .65 * inch 80 | PARAMS.overlay_y_text = 11.29 * inch 81 | 82 | # Other params 83 | PARAMS.font = 'Helvetica' 84 | PARAMS.duplex = True 85 | 86 | 87 | # ------------------------------------------------------------------------------------------------- 88 | # Generic utils 89 | # ------------------------------------------------------------------------------------------------- 90 | 91 | def append_pdf(output, new): 92 | if isinstance(new, (str, Path)): 93 | new = PdfReader(new) 94 | n = new.get_num_pages() 95 | for i in range(n): 96 | output.add_page(new.get_page(i)) 97 | return n 98 | 99 | 100 | @contextmanager 101 | def make_canvas(): 102 | buffer = BytesIO() 103 | toc_canvas = canvas.Canvas(buffer, pagesize=PARAMS.page_format) 104 | try: 105 | yield toc_canvas 106 | finally: 107 | toc_canvas.save() 108 | buffer.seek(0) 109 | toc_canvas.pdf = PdfReader(buffer) 110 | toc_canvas.pdf.buffer = buffer 111 | toc_canvas.pdf.canvas = toc_canvas 112 | 113 | 114 | def iter_files(file_paths): 115 | for file_path in file_paths: 116 | if file_path.startswith('@'): 117 | yield file_path, None 118 | elif not file_path: 119 | yield None, None 120 | # elif file_path == "LEFT": 121 | # yield "LEFT", None 122 | else: 123 | # abs_path = op.join(PARAMS.root_dir, file_path) 124 | if not op.exists(file_path): 125 | print(f"********** {file_path} does not exist") 126 | continue 127 | print(file_path) 128 | pdf_reader = PdfReader(file_path) 129 | yield file_path, pdf_reader 130 | 131 | 132 | def write_pdf(writer, output_file): 133 | with open(output_file, 'wb') as f: 134 | writer.write(f) 135 | 136 | 137 | def resize_page(page, page_format): 138 | w, h = page_format 139 | new_page = PageObject.create_blank_page(width=w, height=h) 140 | new_page.merge_page(page) 141 | return new_page 142 | 143 | 144 | def count_pages(file_paths): 145 | return sum( 146 | pdf_reader.get_num_pages() 147 | for _, pdf_reader in iter_files(file_paths) if pdf_reader) 148 | 149 | 150 | def get_pretty_name(file_path, replace_slashes=True): 151 | pretty_name = file_path.replace('./', '') 152 | if replace_slashes: 153 | pretty_name = pretty_name.replace('/', ' — ') 154 | pretty_name = '.'.join(pretty_name.split('.')[:-1]) 155 | return pretty_name 156 | 157 | 158 | def set_font(font_path): 159 | font_name = op.basename(font_path) 160 | PARAMS.font = font_name 161 | pdfmetrics.registerFont(TTFont(PARAMS.font, font_path)) 162 | 163 | 164 | def ensure_even_pages(writer): 165 | n = 0 166 | if PARAMS.duplex and writer.get_num_pages() % 2 == 1: 167 | writer.add_blank_page() 168 | n = 1 169 | assert not PARAMS.duplex or writer.get_num_pages() % 2 == 0 170 | return n 171 | 172 | 173 | # ------------------------------------------------------------------------------------------------- 174 | # Index 175 | # ------------------------------------------------------------------------------------------------- 176 | 177 | def make_index(file_paths, index_file): 178 | pdf_files = [ 179 | f"@ {get_pretty_name(file, replace_slashes=False)}\n{file}\n\n" 180 | for file in file_paths if file.endswith('.pdf')] 181 | 182 | with open(index_file, 'w') as f: 183 | f.write(f"# Comments start with #.\n") 184 | f.write(f"# Empty lines are ignored.\n") 185 | f.write(f"# Index processing is stopped with `# STOP` on a line.\n") 186 | f.write(f"# PDF files are included by putting their paths on each line.\n") 187 | f.write( 188 | f"# Divider pages are included as follows: `@ Some title / Subtitle below`.\n\n") 189 | 190 | f.writelines(pdf_files) 191 | 192 | 193 | def parse_index(index_file): 194 | # index_file = op.join(root_dir, 'index.txt') 195 | with open(index_file, 'r') as f: 196 | file_paths = [] 197 | for line in f.readlines(): 198 | line = line.strip() 199 | if line.startswith("# STOP"): 200 | break 201 | if not line: 202 | continue 203 | if line == "# BLANK": 204 | file_paths.append('') 205 | # if line == "# LEFT": 206 | # file_paths.append('LEFT') 207 | if not line.startswith('#'): 208 | file_paths.append(line) 209 | else: # comment 210 | if 'PARAMS.' in line: 211 | # modify parameters defined as comment in the index file 212 | exec(line[1:].strip(), {'PARAMS': PARAMS}, {}) 213 | return file_paths 214 | 215 | 216 | # ------------------------------------------------------------------------------------------------- 217 | # TOC 218 | # ------------------------------------------------------------------------------------------------- 219 | 220 | def create_toc(canvas, toc): 221 | canvas.setFont(PARAMS.font, PARAMS.toc_font_size) 222 | canvas.drawString(1 * inch, 10.5 * inch, PARAMS.toc_title) 223 | y = 10.25 * inch 224 | for entry in toc: 225 | canvas.drawString(1 * inch, y, entry) 226 | y -= 0.25 * inch 227 | 228 | 229 | def create_divider(canvas, title): 230 | lines = title.split('/') 231 | 232 | width, height = PARAMS.page_format 233 | canvas.setPageSize(PARAMS.page_format) 234 | canvas.setFont(PARAMS.font, PARAMS.divider_font_size) 235 | 236 | total_height = len(lines) * PARAMS.divider_font_size 237 | start_y = (height + total_height) / 2 238 | 239 | for i, line in enumerate(lines): 240 | text_y = start_y - i * PARAMS.divider_font_size * 1.5 241 | text_width = canvas.stringWidth( 242 | line, PARAMS.font, PARAMS.divider_font_size) 243 | text_x = (width - text_width) / 2 244 | canvas.drawString(text_x, text_y, line) 245 | 246 | canvas.showPage() 247 | 248 | 249 | # ------------------------------------------------------------------------------------------------- 250 | # Overlay 251 | # ------------------------------------------------------------------------------------------------- 252 | 253 | def create_overlay(text): 254 | packet = BytesIO() 255 | can = canvas.Canvas(packet, pagesize=PARAMS.page_format) 256 | 257 | can.setFont(PARAMS.font, PARAMS.overlay_font_size) 258 | can.setStrokeColor(PARAMS.overlay_edgecolor) 259 | can.setFillColor(PARAMS.overlay_bgcolor) 260 | can.setFillAlpha(PARAMS.overlay_opacity) 261 | can.rect( 262 | PARAMS.overlay_x, PARAMS.overlay_y, 263 | PARAMS.overlay_w, PARAMS.overlay_h, fill=1) 264 | can.setFillColor(PARAMS.overlay_textcolor) 265 | 266 | # print(text) 267 | can.drawString(PARAMS.overlay_x_text, PARAMS.overlay_y_text, text) 268 | can.save() 269 | packet.seek(0) 270 | reader = PdfReader(packet) 271 | reader.packet = packet 272 | reader.canvas = canvas 273 | return reader 274 | 275 | 276 | # ------------------------------------------------------------------------------------------------- 277 | # Main functions 278 | # ------------------------------------------------------------------------------------------------- 279 | 280 | def add_overlay(page, name, n=0): 281 | page_number = f"p. {n} {'—' if name else ''} {name}" 282 | overlay = create_overlay(page_number) 283 | page.merge_page(overlay.get_page(0)) 284 | return page_number 285 | 286 | 287 | def collate_pdfs(file_paths, output_pdf, first_page=1): 288 | toc = [] 289 | cur_page = first_page 290 | # left = None 291 | 292 | for file_path, pdf_reader in iter_files(file_paths): 293 | n = cur_page + 1 294 | 295 | # # HACK: force the next item to start on the left page. 296 | # if not left: 297 | # left = file_path == "LEFT" 298 | # if left: 299 | # continue 300 | 301 | # Blank page 302 | if not file_path: 303 | output_pdf.add_blank_page() 304 | cur_page += 1 305 | n += 1 306 | 307 | # Divider page. 308 | elif not pdf_reader: 309 | toc_entry = file_path[1:].strip() 310 | 311 | cur_page += ensure_even_pages(output_pdf) 312 | n = cur_page + 1 313 | 314 | # Create the divider page. 315 | with make_canvas() as canvas: 316 | create_divider(canvas, toc_entry) 317 | 318 | # Add the overlay 319 | page = canvas.pdf.get_page(0) 320 | add_overlay(page, "", n=n) 321 | 322 | # Insert the divider page. 323 | output_pdf.add_page(page) 324 | 325 | # Generate the TOC entry. 326 | toc.append("") 327 | toc.append(f"p. {n:d} — {toc_entry}") 328 | 329 | # HACK: if "LEFT" is set, force the item to start on the left page. 330 | # if not left: 331 | # cur_page += ensure_even_pages(output_pdf) 332 | # else: 333 | # left = None 334 | 335 | cur_page += 1 336 | 337 | # PDF to collate. 338 | else: 339 | pretty_name = get_pretty_name(file_path, replace_slashes=True) 340 | num_pages = pdf_reader.get_num_pages() 341 | 342 | # Add TOC entry 343 | toc.append(f"p. {n:d} — {pretty_name}") 344 | 345 | # Add all pages of the current PDF. 346 | for i in range(num_pages): 347 | n = cur_page + i + 1 348 | page = resize_page(pdf_reader.get_page(i), PARAMS.page_format) 349 | add_overlay(page, pretty_name, n=n) 350 | output_pdf.add_page(page) 351 | cur_page += num_pages 352 | 353 | # # HACK: if "LEFT" is set, force the item to start on the left page. 354 | # if not left: 355 | # cur_page += ensure_even_pages(output_pdf) 356 | # else: 357 | # left = None 358 | 359 | return toc 360 | 361 | 362 | def main(): 363 | 364 | parser = argparse.ArgumentParser(description="Collate PDF tool") 365 | subparsers = parser.add_subparsers(dest='command') 366 | 367 | # makeindex command 368 | parser_makeindex = subparsers.add_parser( 369 | 'makeindex', help='Create index file') 370 | parser_makeindex.add_argument('input', nargs='+', help='Input PDF files') 371 | parser_makeindex.add_argument( 372 | '-o', '--output', required=False, help='Output index file') 373 | 374 | # makepdf command 375 | parser_makepdf = subparsers.add_parser( 376 | 'makepdf', help='Create collated PDF') 377 | parser_makepdf.add_argument('index', help='Index file') 378 | parser_makepdf.add_argument( 379 | '-o', '--output', required=False, help='Output collated PDF file') 380 | parser_makepdf.add_argument( 381 | '-c', '--cover', required=False, help='Cover PDF file') 382 | parser_makepdf.add_argument( 383 | '-f', '--font', required=False, help='Path to a TTF font') 384 | parser_makepdf.add_argument( 385 | '-d', '--duplex', required=False, action='store_true', 386 | help='Adapt to double-sided printing') 387 | 388 | args = parser.parse_args() 389 | 390 | if args.command == 'makeindex': 391 | 392 | make_index(args.input, args.output or PARAMS.index_file) 393 | 394 | elif args.command == 'makepdf': 395 | 396 | # Get the paths to the PDFs to collate from the index. 397 | file_paths = parse_index(args.index) 398 | 399 | # Font. 400 | if args.font: 401 | if not op.exists(args.font): 402 | raise ValueError(f"Path `{args.font}` does not exist.") 403 | set_font(args.font) 404 | 405 | # Duplex printing. 406 | PARAMS.duplex = args.duplex 407 | 408 | # Create the final writer. 409 | output_pdf_with_toc = PdfWriter() 410 | 411 | # Add the cover page. 412 | first_page = 1 413 | cover_file = args.cover or PARAMS.cover_file 414 | if cover_file: 415 | first_page += append_pdf(output_pdf_with_toc, cover_file) 416 | ensure_even_pages(output_pdf_with_toc) 417 | 418 | # Create the writer. 419 | output_pdf = PdfWriter() 420 | 421 | # Collate all PDFs and generate the TOC. 422 | toc = collate_pdfs(file_paths, output_pdf, first_page=first_page) 423 | 424 | # Create the TOC page. 425 | with make_canvas() as page: 426 | create_toc(page, toc) 427 | toc_pdf = page.pdf 428 | 429 | # Add the TOC. 430 | append_pdf(output_pdf_with_toc, toc_pdf) 431 | ensure_even_pages(output_pdf_with_toc) 432 | 433 | # Add the collated PDFs. 434 | append_pdf(output_pdf_with_toc, output_pdf) 435 | 436 | # Save the PDF to disk. 437 | write_pdf(output_pdf_with_toc, args.output or PARAMS.output_file) 438 | 439 | else: 440 | parser.print_help() 441 | 442 | 443 | if __name__ == "__main__": 444 | main() 445 | --------------------------------------------------------------------------------