How to crop pdf using Ghostscript (without enterin

2019-07-21 23:24发布

问题:

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.

回答1:

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


回答2:

This worked for me in a DOS batch file and using drag and drop:

    "c:\Program Files\gs\gs9.21\bin\gswin64c.exe" ^
 -dBATCH -dNOPAUSE -q -sDEVICE=bbox %1 2> CropBox.txt

for /f "tokens=2 delims=:" %%G IN (CropBox.txt) DO Set MyVar= %%G

"c:\Program Files\gs\gs9.21\bin\gswin64c.exe" -dNOPAUSE -dBATCH^
 -sDEVICE=pdfwrite ^
 -sOutputFile=%1.pdf ^
 -c "[/CropBox [%MyVar%] /PAGES pdfmark" -f %1


回答3:

Essentially, no. You need to extract the information from the output of the bbox device, and send that separately to the pdfwrite device.

Your best bet is to write a script to do it.