Search code examples
pdfcropghostscriptbounding-box

How to crop pdf using Ghostscript (without entering manually Bounding Box)


I need to crop a pdf-file to its Bounding Box. First I calculate actual Bounding Box:

gswin64c.exe ^
  -o nul ^
  -sDEVICE=bbox ^
  input.pdf

the result

%% HiResBoundingBox: 156.350019 391.521011 445.919963 446.259010

I substitute into the

gswin64c.exe ^
  -o output.pdf ^
  -sDEVICE=pdfwrite ^
  -dUseCropBox=true ^
  -c "[/CropBox [156.350019 391.521011 445.919963 446.259010] /PAGES pdfmark" ^
  -f input.pdf

is there a way to substitute the Bounding Box automatically?

thank you.


Solution

  • What you need is called command substitution. Please refer to help by 'for /?' command

    For simplicity I have separated answer into two files

    First file (getbb.bat) get bounding box

    @echo off
    "C:\Program Files\gs\gs9.02\bin\gswin64c.exe"^
      -o nul -sDEVICE=bbox %1 2>&1 | find "ResBoundingBox"
    

    Second file (replacebb.bat)

    @echo off
    
    for /f "tokens=2 delims=:" %%b in ('getbb.bat %1') do (
    call :Trim bbox %%b
    "C:\Program Files\gs\gs9.02\bin\gswin64c.exe" ^
      -o output.pdf -sDEVICE=pdfwrite -dUseCropBox=true ^
      -c "[/CropBox [%bbox%] /PAGES pdfmark" -f input.pdf
    )
    exit /b
    
    :Trim
    SetLocal EnableDelayedExpansion
    set Params=%*
    for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
    exit /b