使用Ghostscript合并PDF文件,如何包含原始文件名?

9

我有大约250个单页pdf文件,它们的名称如下:

file_1_100.pdf,
file_1_200.pdf, 
file_1_300.pdf, 
file_2_100.pdf, 
file_2_200.pdf, 
file_2_300.pdf, 
file_3_100.pdf, 
file_3_200.pdf, 
file_3_300.pdf
...etc

我正在使用以下命令将它们合并为单个pdf文件:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf file*pdf

它的工作表现完美,正确地将它们组合在一起。但是,当我查看finished.pdf时,我希望有一个参考,告诉我每一页的原始文件名。
有人有什么建议吗?我是否可以添加引用文件的页面名称或其他内容呢?

这里的Python脚本看起来很有前途:http://blog.tremily.us/posts/PDF_bookmarks_with_Ghostscript/ - Geremia
2个回答

9

将文件名放入书签列表中并让许多PDF查看器显示非常容易。

这可以使用PostScript使用“pdfmark”distiller操作符完成。例如,使用以下内容:

gs -sDEVICE=pdfwrite -o finished.pdf control.ps

其中control.ps包含用于打印页面和输出书签(/OUT) pdfmarks的PS命令:

(examples/tiger.eps) run [ /Page 1 /Title (tiger.eps) /OUT pdfmark
(examples/colorcir.ps) run [ /Page 2 /Title (colorcir.ps) /OUT pdfmark

请注意,您还可以使用 PowerShell 进行枚举,以自动执行整个过程:
/PN 1 def
(file*.pdf) {
  /FN exch def
  FN run
  [ /Page PN /Title FN /OUT pdfmark % do the file and bookmark it by filename
  /PN PN 1 add def % bump the page number
} 1000 string filenameforall

注意,filenameforall 枚举的顺序未指定,因此您可能需要使用 Ghostscript 扩展 .sort ( array lt .sort lt ) 对列表进行排序以控制顺序。
此外,在考虑了这个问题后,我也意识到,如果输入文件有多页,则可以使用“PageCount”设备属性将书签设置为正确的页码。
[
  (file*.pdf) { dup length string copy } 1000 string filenameforall
] % create array of filenames
{ lt } .sort % sort in increasing alphabetic order
/PN 1 def
{ /FN exch def
  /PN currentpagedevice /PageCount get 1 add def % get current page count done (next is one greater)
  FN run [ /Page PN /Title FN /OUT pdfmark % do the file and bookmark it by filename
} forall

以上代码创建了一个字符串数组(将它们复制到唯一的字符串对象中,因为filenameforall函数只会覆盖给定的字符串),然后对其进行排序,并最终使用forall运算符处理该字符串数组。通过使用PageCount设备属性获取已经生成的页面数量,书签的页码(PN)将是正确的。我已将此片段测试为'control.ps'。


4
非常抱歉,但这个表述非常不清楚。有没有可能解释一下tiger.epscolorcir.ps是什么,以及1000是用来干什么的? - puk

1

要在每个页面上盖章文件名,您可以使用ghostscript和pdftk的组合。取自https://superuser.com/questions/171790/print-pdf-file-with-file-path-in-footer

gs \
-o outdir\footer.pdf \
-sDEVICE=pdfwrite \
-c "5 5 moveto /Helvetica findfont 9 scalefont setfont (foobar-filename.pdf) show"

pdftk \
foobar-filename.pdf \
stamp outdir\footer.pdf \
output outdir\merged_foobar-filename.pdf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接