2

I have a pdf and I am in need to replace even and odd pages. If I want to be more specific, I must replace (2n-1) page numbers with (2n) ones (1-->2, 2-->1, 3-->4, 4-->3, and the like). How should I do that?

Is there any free software that can do this job for me?

  • 1
    Does this answer your question? [Exchange odd and even pages in a pdf file?](https://unix.stackexchange.com/questions/184799/exchange-odd-and-even-pages-in-a-pdf-file) – sjy Sep 04 '21 at 14:34

1 Answers1

5

With poppler-utils tools you could extract the pages to separate files, reorder & save them into an array and join the elements of that array to produce a new document:

pdfseparate original.pdf piece-%04d.pdf
reordered=()
set -- piece*.pdf
while (($#)); do
  if [ $# -ge 2 ]; then
    reordered+=("$2" "$1")
    shift 2
  else
    reordered+=("$1")
    shift
  fi
done
pdfunite "${reordered[@]}" final.pdf
rm -f piece-*.pdf
unset reordered

If your document has more than 9999 pages adjust the format specifier e.g. %05d

don_crissti
  • 79,330
  • 30
  • 216
  • 245
  • Thank you so much! It worked! I entered what you wrote line-by-line and cared about indentations and it worked nice and tidy! :D – Mehdi Abbassi Feb 01 '19 at 08:14
  • Thank you, Don! this would work for other file types like DjVu, too! very elegant. – Maxim Oct 31 '19 at 18:56
  • Great solution! One thing: I got `I/O Error: Couldn't open file 'piece-0253.pdf': Too many open files.` so I had to do `ulimit -n 512` to increase the limit. – Matt Sephton Jul 28 '21 at 22:30
  • See [Exchange odd and even pages in a pdf file?](https://unix.stackexchange.com/questions/184799/exchange-odd-and-even-pages-in-a-pdf-file) for a much simpler solution: `pdftk infile.pdf shuffle even odd output outfile.pdf`. – sjy Sep 04 '21 at 14:33