Search code examples
ghostscriptpostscript

Ghostscript How to watermark one special page of a postscript document?


I already add watermark (or image) in every page of a .ps document by below command and gs script.

[root@localhost ~]#gs -dBATCH -dNOPAUSE -q -sDEVICE=ps2write -sOutputFile=watermarked.ps mark.ps doc_test.ps

content of mark.ps:

<<
/EndPage
{
  2 eq { pop false }
  {
    gsave
    /STSong-Light-UniGB-UTF8-H findfont 30 scalefont setfont
    newpath
    .87 setgray
    260 50 moveto 30 rotate
    (test 测试) false  charpath
    1 setlinewidth stroke
    grestore
    true
  } ifelse
} bind
>> setpagedevice

but I don't know how to specify a page to add watermark, example the .ps document is 12 pages long, I just want to add watermark on page 6, but I want the output file to contain all 12 pages document content and just page 6 has a watermark. Does anyone Ghostscript expert know how to script this requirement? Many thanks!!!


Solution

  • When the input is PostScript you can use the number your program pops from the stack, because this is the count of pages executed so far.

    If you look at the definition of EndPage in the PLRM (page 427 in the 3rd edition) you will see that the operand stack contains two numbers, a reason code on top and the count of previous showpage executions. You need to test the reason code first. If its 2, pop the count and return false. If it is not 2, then check the second number to see if its tha value that will trigger your page. If it is not then return true. If it is, then first execute your marking routine an dthen return true.

    NB it looks to me like your program is leaving the count of showpage executions on the operand stack when the reason code is 2. THis is poor practice; if called often enough you could cause a stack overflow error. Its also legal for a program to leave operands on the stack during showpage, and use them after. If you leave somethign on the stack then it would mean that program retrieving the wrong objects.

    Unfortunately, when the input is PDF, the Ghostscript PDF interpreter executes a setpagedevice on every page, and this resets the count to 0.

    So when the input is PDF you need to modify your program to keep a count of pages it has encountered so far, so that you can check it and only activate when required. Give it a unique name and store it in userdict, incrememnt it on every execution of EndPage, and run the marking part of the program only when it reaches a particular value.

    PostScript is a programming language......