Skip to content

Instantly share code, notes, and snippets.

@tavinus
Last active January 30, 2025 11:09
Show Gist options
  • Save tavinus/44bd6bf3d20204d654b6d5fe52342741 to your computer and use it in GitHub Desktop.
Save tavinus/44bd6bf3d20204d654b6d5fe52342741 to your computer and use it in GitHub Desktop.
Split PDFs Windows (ghostscript)
@echo off
chcp 65001 >NUL
setlocal enabledelayedexpansion
:: THIS SCRIPT
:: https://gist.github.com/tavinus/44bd6bf3d20204d654b6d5fe52342741
:: Works from CLI or Drag and Drop
:: GhostScript Download:
:: https://www.ghostscript.com/download.html
:: Originally extracted from
:: https://stackoverflow.com/a/51284876/1273636
:: detect installed ghostscript and add to PATH
set gsBaseDir=%PROGRAMFILES%\gs
set gsFullDir=__NOWHERETOBEFOUND__
for /f "delims=" %%a IN ('dir /b "%gsBaseDir%"\*') do (
IF EXIST "%gsBaseDir%"\%%a\lib (
set gsFullDir=%PROGRAMFILES%\gs\%%a
)
)
IF NOT EXIST "%gsFullDir%" GOTO NOGSFOUND
:: You can manually add your PATH here if detection fails
:: set path=C:\Program Files\gs\gs9.25\lib;C:\Program Files\gs\gs9.25\bin;%path%
set path=%gsFullDir%\lib;%gsFullDir%\bin;%path%
:: Validate input PDF File
IF NOT EXIST "%~n1%~x1" GOTO NOPDFFOUND
:START
echo Splitting "%~n1%~x1" into standalone single pages...
cd %~d1%~p1
rem getting number of pages of PDF with GhostScript
for /f "usebackq delims=" %%a in (`gswin64c -q -dNODISPLAY -c "(%~n1%~x1) (r) file runpdfbegin pdfpagecount = quit"`) do set "numpages=%%a"
for /L %%n in (1,1,%numpages%) do (
echo Extracting page %%n of %numpages%...
set "x=00%%n"
set "x=!x:~-3!"
gswin64c.exe -dNumRenderingThreads=2 -dBATCH -dNOPAUSE -dQUIET -dFirstPage=%%n -dLastPage=%%n -sDEVICE=pdfwrite -sOutputFile="%~d1%~p1%~n1-!x!.pdf" "%1"
)
shift
if NOT x%1==x goto START
pause
exit /B 0
:NOGSFOUND
echo Could not locate your GS path on Program Files.
echo Please install GS or manually tweak your PATH config.
pause
exit /B 2
:NOPDFFOUND
echo Could not locate your input PDF file.
echo Nothing to be done.
pause
exit /B 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment