Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split PDF by multiple pages using PDFTK?

I am finding it hard to phrase this question and could not find an online solution for what I'm trying to do.

I know how to split a large PDF into single pages with PDFTK using the following script:

pdftk your_file.pdf burst output your_directory/page_%02d.pdf

But now I want to split the PDF by every other page, so that each new PDF has TWO (2) pages (e.g. pages 1 + 2 together, pages 3 + 4 together, 5 + 6, etc.).

I know that Acrobat does this like a champ, however I need something I can execute from Powershell.

I am open to alternatives/workarounds, like taking the single pages and combining them by two's after single bursting.

like image 644
m0chi Avatar asked May 05 '17 13:05

m0chi


2 Answers

I found Szakacs Peter's solution to be wonderful, but the bash script needed three tweaks: starting $COUNTER at 1 so that it refers to the first page of the pdf; adding double braces on line four so that (($COUNTER+1)) evaluates; another $COUNTER to make the output file names unique.

The final bash script that solved this for me was:

#!/bin/bash 
 COUNTER=1
 while [  $COUNTER -lt $NUMBEROFPAGES ]; do
     pdftk in.pdf cat $COUNTER-$(($COUNTER+1)) output out$COUNTER.pdf
     let COUNTER=COUNTER+2 
 done

Then just save this as something like burst2page.sh, do a chmod u+x burst2page.sh to make it executable, then run it with ./burst2page.sh

like image 63
Brad Smith Avatar answered Sep 24 '22 14:09

Brad Smith


Brad Smith's script is good however it won't work in that shape. When you don't define $NUMBEROFPAGES, the script throws you an error script.sh: line 3: [: 1: unary operator expected. I suggest to change it to:

#!/bin/bash 
FILE='in.pdf'
COUNTER=1
NUMBEROFPAGES=`pdftk $FILE dump_data |grep NumberOfPages | awk '{print $2}'`
while [  $COUNTER -lt $NUMBEROFPAGES ]; do
    pdftk $FILE cat $COUNTER-$(($COUNTER+1)) output out$COUNTER.pdf
    let COUNTER=COUNTER+2 
done
like image 30
Houmles Avatar answered Sep 23 '22 14:09

Houmles