All posts
Rearrange PDF pages via CLI
Ghostscript PageList only accepts increasing pages, so extract runs and merge them in the new order.
Open online converterPackages to install
Use ghostscript. Extract each increasing run, then pass the parts to gs in the order you want.
ghostscript
sudo apt-get update
sudo apt-get install -y ghostscriptHow to run the command
PageList=3,1,2,4 is rejected. Extract page 3, then 1-2, then 4, and merge: gs ... -sOutputFile=reordered.pdf p3.pdf p1-2.pdf p4.pdf.
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=3 -sOutputFile=p3.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1-2 -sOutputFile=p1-2.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=4 -sOutputFile=p4.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=reordered.pdf p3.pdf p1-2.pdf p4.pdfDockerfile example
Build a minimal Ubuntu image with the required packages and run the conversion inside the container.
FROM ubuntu:24.04
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ghostscript && \
rm -rf /var/lib/apt/lists/*
WORKDIR /work
docker build -t rearrange-pdf .
docker run --rm -v "$PWD:/work" -w /work rearrange-pdf \
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=3 -sOutputFile=p3.pdf input.pdfExample commands
Run these locally after installing the packages, or inside the container from the Dockerfile.
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=3 -sOutputFile=p3.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1-2 -sOutputFile=p1-2.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=4 -sOutputFile=p4.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=reordered.pdf p3.pdf p1-2.pdf p4.pdfgs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=4 -sOutputFile=p4.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=3 -sOutputFile=p3.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=2 -sOutputFile=p2.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1 -sOutputFile=p1.pdf input.pdf
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sOutputFile=reversed.pdf p4.pdf p3.pdf p2.pdf p1.pdf