All posts

Delete PDF pages via CLI

Ghostscript keeps the pages you list: deleting a page means listing everything else.

Open online converter

Packages to install

Use ghostscript. Put the pages you want to keep in -sPageList.

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

How to run the command

To drop page 2 from a 10-page file, keep 1,3-10: gs ... -sPageList=1,3-10 -sOutputFile=cleaned.pdf input.pdf. The range 2- means “from page 2 to the end”.

gs
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1,3-10 -sOutputFile=cleaned.pdf input.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 delete-pages-pdf .
docker run --rm -v "$PWD:/work" -w /work delete-pages-pdf \
  gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1,3-10 -sOutputFile=cleaned.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=1,3-10 -sOutputFile=cleaned.pdf input.pdf
Example 2
gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=2- -sOutputFile=without-first.pdf input.pdf