Skip to content

Instantly share code, notes, and snippets.

@rjz
Created January 5, 2020 01:13
Show Gist options
  • Save rjz/9bc1301d32a9cec7850ea2acefac1f89 to your computer and use it in GitHub Desktop.
Save rjz/9bc1301d32a9cec7850ea2acefac1f89 to your computer and use it in GitHub Desktop.
Convert PDF pages into a printable booklet on Linux using psutils
#! /bin/bash
#
# Use `psutils` to convert a PDF into a printable booklet.
#
# Usage:
#
# $ ./pdf_to_booklet.sh my_file.pdf
#
# Distributed under terms of the MIT license.
DOCUMENT_MEDIA='Tabloid 792 1224'
IN_PAPER=letter
PAGE_MEDIA=$(echo $DOCUMENT_MEDIA | cut -d' ' -f1)
PAGE_SIZE=$(echo $DOCUMENT_MEDIA | cut -d' ' -f2-)
OUT_PAPER=$(echo "$PAGE_MEDIA" | tr '[:upper:]' '[:lower:]')
# Fix a known bug where `psnup` always (?) outputs `Letter`-size documents:
#
# See: https://bugs.launchpad.net/ubuntu/+source/psutils/+bug/396025
fix_psnup_media() {
sed "s/Letter/${PAGE_MEDIA}/"
sed "s/612 792/${PAGE_SIZE}/"
}
# Convert PDF into Postscript
pdftops -level3 -paper $IN_PAPER $1 $1.ps
# Reorder pages and place (two to a page) on larger paper
psbook -q -s4 $1.ps \
| psnup -q -p $OUT_PAPER -P $IN_PAPER -2 \
| fix_psnup_media \
| ps2pdf -sPAPERSIZE=$OUT_PAPER - $1.booklet.pdf
@Mer7cer7
Copy link

Mer7cer7 commented Feb 3, 2022

Could the order of the pages be changed for a staple bound booklet, where I would open to the middle of the booklet and put 2 or 3 staples in the center to create its spine?

Assuming the first and last page of the PDF file is the book cover, the output PDF should go:

1st page (outside cover of booklet) - 1st and last page of original PDF
2nd page (inside cover of booklet) - 2nd and 2nd to last page of the original PDF
3rd page (outside 1st and last page of booklet) - 3rd and 3rd to last page of the original PDF
4th page (inside 1st and last page of booklet) - 4th and 4th to last page of the original PDF
...until you get to the center of the booklet and middle of the original PDF.

If the original PDF has an odd number of pages, I assume you would have to add a blank page 2nd to the last of the original PDF (as the last page of the original will be the back cover).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment