Skip to content

Instantly share code, notes, and snippets.

@mmparker
Created December 11, 2012 23:29
Show Gist options
  • Save mmparker/4263328 to your computer and use it in GitHub Desktop.
Save mmparker/4263328 to your computer and use it in GitHub Desktop.
A very rough Python script for printing reordered and grouped pages from a PDF using pdftk and gsview. In a study, we're able to generate participant packets in bulk - dozens at a time. But the pages in the pdf aren't in exactly the right order, and we want to be able to print them in the correct groupings to take advantage of our printer's auto…
import os
import subprocess
import glob
# Check for the existence of a "printed" folder
# If it doesn't exist, make it
if not os.path.exists(os.path.join(os.getcwd(), "printed")):
os.mkdir(os.path.join(os.getcwd(), "printed"))
# Ask the user to identify the PDF file they want to print
pdfpath = 'test.pdf'
# Ask the user for the number of forms to be printed - until I can figure
# out a way to get number of pages from Python, this will have to do
# Placeholder for asking
nforms = 5
# Using pdftk, reorder the forms to put Section A first, then cover sheet, then Sections B-E, then LTBI testing form
for i in range(nforms):
subprocess.call(['pdftk', pdfpath, 'cat', '{0}-{1}'.format(3 + 16 * i, 6 + 16 *i), '{0}-{1}'.format(1 + 16 * i, 2 + 16 *i), '{0}-{1}'.format(7 + 16 * i, 16 + 16 *i), 'output', 'reordered{0}.pdf'.format(i + 1)])
# Using gsprint, print each of the forms in the correct order and groupings
# Get the list of files
formlist = glob.glob('reordered*.pdf')
# Print each
for form in formlist:
subprocess.call(['gsprint', '-dFirstPage=1', '-dLastPage=4', form])
subprocess.call(['gsprint', '-dFirstPage=5', '-dLastPage=14', form])
subprocess.call(['gsprint', '-dFirstPage=15', '-dLastPage=16', form])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment