【发布时间】:2017-08-05 08:03:28
【问题描述】:
正如问题所述,我想编写一个批处理脚本,该脚本使用 GhostScript 来反转 PDF 文件的所有颜色并将结果放在子目录中。我已经安装了 GhostScript,然后尝试将路径添加到环境变量,但调用未被识别,因此我将可执行文件的副本放在与似乎成功调用 GhostScript 的批处理文件相同的目录中。我正在使用this post 上找到的以下 GhostScript 代码作为模板:
gs -o output.pdf \
-sDEVICE=pdfwrite \
-c "{1 exch sub}{1 exch sub}{1 exch sub}{1 exch sub} setcolortransfer" \
-f input.pdf
您将在下面找到我目前对该批处理文件的尝试,这是我的第一个批处理文件,因此感谢您提供任何建议:
SETLOCAL EnableDelayedExpansion
@ECHO OFF
:: Setting some variables...
SET outdir=InvertedOutputs
SET gs=gswin64c.exe
:: Check for the inverted output directory,
:: make the directory if it doesn't exist.
IF NOT EXIST %outdir% MKDIR %outdir%
:: Iterate through all files in current directory.
FOR %%f IN (*) DO (
:: Set the GhostScript / PostScript commands, before if statement.
SET commands="{1 exch sub}{1 exch sub}{1 exch sub}{1 exch sub} setcolortransfer"
:: Check that file extension is correct.
IF %%~xf == .pdf (
%gs% -o %outdir%\%%~f -sDEVICE=pdfwrite -c !commands! -f %%~f
)
)
ECHO.
PAUSE
我已经编辑了代码,以反映每个@aschipfl 注释启用延迟扩展的添加。以下错误仍然存在:
Error: /undefinedfilenmae in ...
【问题讨论】:
-
您需要delayed expansion,因为您正在编写和在一个带括号的代码块中读取相同的变量...
-
我以为我只是在读取源文件并写入子目录中的新文件?我不打算修改原始文件,只是阅读它。
-
不,我说的是环境变量:您在同一块中分配变量
commands,稍后您将通过%commands%扩展它;这不起作用,因为当一个块被解析时会读取变量;要在代码执行时阅读它们,您需要将setlocal EnableDelayedExpansion放在该块之前的某个位置(通常在脚本顶部),然后使用!commands!而不是%commands%... -
查看我上面的代码更改 - 我启用了延迟扩展并将变量声明也移到了块之外。但我仍然得到以下输出:
Error: /undefinedfilename in ... -
我建议对 cmets 使用
rem而不是::,因为后者可能会导致意外行为;此外,将""放在文件路径周围(-o "%outdir%\%%~f"和-f "%%~f")。我无法为您提供gs本身的帮助,因为我不知道此命令...
标签: windows batch-file pdf ghostscript