All posts

Split PDF via CLI

Extract pages with Ghostscript -sPageList.

Open online converter

Packages to install

The ghostscript package provides gs. PageList accepts numbers and ranges such as 1,3,5-7.

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

How to run the command

gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -sPageList=1,3,5-7 -sOutputFile=pages.pdf input.pdf. Only the listed pages are written.

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