如何在Ghostscript输出文件名的%d后直接添加数字、A-F或空格?
关于Ghostscript输出文件名中%d格式符的语法问题及解决办法
我使用Windows 10系统,通过Scoop安装了Ghostscript 10.02.1(2023-11-01),在设置输出文件名时遇到了%d格式符的语法问题。
无效场景
当%d后紧跟十六进制数字(0-9、A-F/a-f)、空格或连字符(-)时,命令执行失败:
# PowerShell 7环境示例 gs -sDEVICE=jpeg -o "%d0.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%dF.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%d q.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%d-.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf'
CMD环境对应命令:
gs -sDEVICE=jpeg -o "%dF.jpeg" -dFirstPage=1 -dLastPage=1 "test file.pdf"
报错信息如下:
Page 1
GPL Ghostscript 10.02.1: **** Could not open the file '1-.jpeg'.
**** Error: Page drawing error occurred.
Could not draw this page at all, page will be missing in the output.
注:报错中显示的文件名1-.jpeg正是我期望从%d-.jpeg得到的结果,但命令仍执行失败。
有效场景
当%d后紧跟的字符不属于十六进制数字、空格或连字符时,命令可正常运行:
# PowerShell 7环境示例 gs -sDEVICE=jpeg -o "%dG.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%dZ.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%d! 42 F0 0F.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf' gs -sDEVICE=jpeg -o "%d~.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf'
CMD环境对应命令:
gs -sDEVICE=jpeg -o "%dg.jpeg" -dFirstPage=1 -dLastPage=1 "test file.pdf"
问题原因
Ghostscript的输出文件名格式符参考C语言printf规范,但实际解析逻辑中,%d后若紧跟十六进制数字、空格或连字符时,会被误判为格式符的修饰部分(比如宽度、填充标记等),引发解析歧义。尽管最终生成的文件名符合预期,但解析过程中的语法冲突触发了Ghostscript的文件打开错误。
解决方法
- 插入分隔字符:在
%d和后续特殊字符之间添加非触发歧义的字符(如字母p),即你当前使用的%dp foo.jpeg,简单直接。 - Shell转义处理:利用Windows Shell的转义规则,用双百分号规避格式符冲突:
- CMD环境:
gs -sDEVICE=jpeg -o "%%d foo.jpeg" -dFirstPage=1 -dLastPage=1 "test file.pdf" - PowerShell环境:
gs -sDEVICE=jpeg -o "%`%d foo.jpeg" -dFirstPage=1 -dLastPage=1 'test file.pdf'
- CMD环境:
- PostScript语法指定输出:通过PostScript代码直接设置输出文件名,绕过Shell和Ghostscript的格式符冲突:
gs -sDEVICE=jpeg -dFirstPage=1 -dLastPage=1 -c "<</OutputFile (%d foo.jpeg)>> setpagedevice" -f 'test file.pdf'
需求说明
我期望生成的文件名格式为%d foo.jpeg,目前通过%dp foo.jpeg临时解决,但希望明确问题根源并找到更直接的解决方式。
内容的提问来源于stack exchange,提问作者Maxim Kamalov
相关产品推荐
相关产品推荐

