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 converter

Packages to install

Use ghostscript. Extract each increasing run, then pass the parts to gs in the order you want.

ghostscript
apt install
sudo apt-get update
sudo apt-get install -y ghostscript

How 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
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.pdf

Dockerfile example

Build a minimal Ubuntu image with the required packages and run the conversion inside the container.

Dockerfile
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 && docker run
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.pdf

Example commands

Run these locally after installing the packages, or inside the container from the Dockerfile.

Example 1
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.pdf
Example 2
gs -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