Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gabe-husain Added PDF to Booklet Conversion Feature #409

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions BookletMakerfromPDF/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Booklet Maker written by Gabriel Husain

## Introduction

This quick CLI will take in a pdf and then reorder the pages so you can print it using two per page setting, allowing you to staple the pages together.

This was made because PDF readers like acrobat are expensive and Preview has no automatic booklet setting

## How it Works

This will see if your PDF is of a length of a multiple of 4, then reorders the pages in the proper format so you can print on a double sided page with 4 pages per sheet. Perfect for academic papers printed at home to save paper and ink.

### Why 4?

4 is required since we will be separating it so each page is placed properly:

#### e.g. 12 pages

This will print with 3 sheets since 12 // 4 = 3

Sheet 1 side 1: pg 12 pg 1 `[ 12 `| 1 `]
Sheet 1 side 2: pg 2 pg 11`[ 1 `| 11 `]

Sheet 2 side 1: pg 10 pg 3 `[ 10 `| 3 `]
Sheet 2 side 2: pg 4 pg 9`[ 4 `| 9 `]

Sheet 3 side 1: pg 8 pg 5 `[ 8 `| 5 `]
Sheet 3 side 2: pg 6 pg 7`[ 6 `| 7 `] `( Center fold `)

#### Page Numbers from example in order

12, 1, 2, 11, 10, 3, 4, 9, 8, 5, 6, 7.

## How to Use

1. Make sure you have Python installed on your system. This script requires Python 3.6 or higher.

>[!TIP]
> If you are using Mac, you can easily start it off by just running setup.sh which will set up a new venv for you and install PyPDF2 and make the file executable

2. Install the required dependency by running the following command:
```
pip install PyPDF2
```

3. Save the `bookl3t.py` script to your desired location.

4. Open a terminal or command prompt and navigate to the directory where you saved the script.
### Running the script

5. Run the script using the following command:
```
python bookl3t.py input.pdf output.pdf
```
Replace `input.pdf` with the path to your input PDF file, and `output.pdf` with the desired path and filename for the output booklet PDF.

For example:
```
python bookl3t.py /path/to/input.pdf /path/to/output.pdf
```

6. The script will process the input PDF and generate a new PDF in booklet format. The output PDF will be saved at the specified output path.

7. If the script runs successfully, you will see a message printed in the terminal:
```
Booklet created successfully!
```

If an error occurs during the booklet creation process, an error message will be displayed instead.

### Debugging

By default, the script prints debug information to the console, including page counts, padding pages needed, and the page arrangement for each sheet. If you don't want to see this information, you can modify the `create_booklet` function call in the script and set the `debug` parameter to `False`:

```python
create_booklet(input_path, output_path, debug=False)
```

## To Print:

To print your new file, make sure you've selected double sided (! Short Edges !), collate pages, 2 pages per sheet:
![[Pasted image 20241210173200.png]]
![[Pasted image 20241210172851.png]]

### Requirements

- Python 3.6 or higher
- PyPDF2 library

Make sure to have the necessary dependencies installed before running the script.

## Contact & License

Created by Gabriel Husain - gabe.husain [at] gmail [dot] com
GitHub: [gabe-husain](https://github.com/gabe-husain)

This project is licensed under MIT.
95 changes: 95 additions & 0 deletions BookletMakerfromPDF/bookl3t.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from PyPDF2 import PdfReader, PdfWriter
import math

def create_booklet(input_path, output_path, debug=True):
"""
Convert a PDF into a booklet format where pages are arranged for duplex printing
with short-edge flipping. Handles both even and odd page counts correctly.

Args:
input_path (str): Path to the input PDF file
output_path (str): Path where the output PDF will be saved
debug (bool): Whether to print debug information
"""
# Read the input PDF
reader = PdfReader(input_path)
writer = PdfWriter()

# Get total number of pages
total_pages = len(reader.pages)

# For booklet printing, we need a multiple of 4 pages
remainder = total_pages % 4
padding_needed = (4 - remainder) if remainder != 0 else 0
total_needed = total_pages + padding_needed

if debug:
print(f"Original page count: {total_pages}")
print(f"Remainder when divided by 4: {remainder}")
print(f"Padding pages needed: {padding_needed}")
print(f"Final page count needed: {total_needed}")

# Create a list of all pages
pages = []
for i in range(total_pages):
pages.append(reader.pages[i])

# Create a single blank page if needed
blank_page = None
if padding_needed > 0:
blank_page = writer.add_blank_page(
width=pages[0].mediabox.width,
height=pages[0].mediabox.height
)
# Add the blank pages to our pages list
for _ in range(padding_needed):
pages.append(blank_page)

# Calculate number of sheets
sheets = total_needed // 4

if debug:
print(f"Number of sheets: {sheets}")
print("\nPage arrangement:")

# Create a new writer for the final output
final_writer = PdfWriter()

# Arrange pages in booklet order
for sheet in range(sheets):
# Calculate the page numbers for this sheet
last_page = total_needed - 1 - (sheet * 2)
first_page = sheet * 2
second_page = (sheet * 2) + 1
second_last_page = total_needed - 2 - (sheet * 2)

if debug:
print(f"\nSheet {sheet + 1}:")
print(f" Front: {last_page + 1} and {first_page + 1}")
print(f" Back: {second_page + 1} and {second_last_page + 1}")

# Add the pages in the correct order to the final writer
final_writer.add_page(pages[last_page])
final_writer.add_page(pages[first_page])
final_writer.add_page(pages[second_page])
final_writer.add_page(pages[second_last_page])

# Save the output PDF
with open(output_path, 'wb') as output_file:
final_writer.write(output_file)

if __name__ == "__main__":
import sys

if len(sys.argv) != 3:
print("Usage: python script.py input.pdf output.pdf")
sys.exit(1)

input_path = sys.argv[1]
output_path = sys.argv[2]

try:
create_booklet(input_path, output_path)
print("\nBooklet created successfully!")
except Exception as e:
print(f"Error creating booklet: {str(e)}")
Binary file added BookletMakerfromPDF/printSetting1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added BookletMakerfromPDF/printSetting2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions BookletMakerfromPDF/setup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/bin/bash

# Only run for *nix systems
# Check if Python is installed
if ! command -v python &> /dev/null
then
echo "Python is not installed. Please install Python and try again."
exit 1
fi

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
source venv/bin/activate

# Install the required dependencies
pip install PyPDF2

# Make the bookl3t.py script executable
chmod +x bookl3t.py

echo "Setup complete. You can now run the bookl3t.py script."