If I'm understanding your requirement correctly, would you please try:
pdftk A=odd.pdf B=even.pdf shuffle A B output final.pdf
Then the final.pdf
will have interleaved pages such as:
odd.pdf 1 2 3 ..
even.pdf 1 2 3 ..
--------------------------------
final.pdf 1 2 3 4 5 6 ..
[Edit]
As the cat
command of pdftk
is not indended to be used in the loop,
we need to use some tricks:
#!/bin/bash
# caclurate the page counts of the two files
pagesA=$(pdftk odd.pdf dump_data | awk '/NumberOfPages/ {print $2}')
pagesB=$(pdftk even.pdf dump_data | awk '/NumberOfPages/ {print $2}')
# determine which file has more pages
if (( pagesA < pagesB )); then
min=$pagesA
max=$pagesB
remainder=even.pdf
else
min=$pagesB
max=$pagesA
remainder=odd.pdf
fi
# at first, append the 1st pages
pdftk A=odd.pdf B=even.pdf cat A1 B1 output output.pdf
# append pages up to the common last pages
for (( i = 2; i <= min; i++ )); do
pdftk A=odd.pdf B=even.pdf C=output.pdf cat C A"$i" B"$i" output tmp.pdf
mv -f tmp.pdf output.pdf
done
# append remaining pages
for (( i = min+1; i <= max; i++ )); do
pdftk A=$remainder C=output.pdf cat C A"$i" output tmp.pdf
mv -f tmp.pdf output.pdf
done
It first merges the first pages to generate the initial pdf file as an "appendee"
then append the remaining pages in the next loop by renaming the output file each time.
If you are not forced to use the pdftk
command within the loop, here is
an alternative which will be faster and more efficient:
#!/bin/bash
# caclurate the page counts of the two files
pagesA=$(pdftk odd.pdf dump_data | awk '/NumberOfPages/ {print $2}')
pagesB=$(pdftk even.pdf dump_data | awk '/NumberOfPages/ {print $2}')
# determine which file has more pages
if (( pagesA < pagesB )); then
min=$pagesA
max=$pagesB
remainder="B"
else
min=$pagesB
max=$pagesA
remainder="A"
fi
# generate a list of pages up to the common last page
for (( i = 1; i <= min; i++ )); do
pages+=(A"$i" B"$i")
done
# append a list of remaining pages
for (( i = min+1; i <= max; i++ )); do
pages+=("$remainder$i")
done
pdftk A=odd.pdf B=even.pdf cat "${pages[@]}" output output.pdf
You'll see how the list is expanded by putting echo
command in front of the pdftk
command.