Is it possible in Ghostscript to add watermark to every page in PDF

ghostscriptjpegpdfpostscriptwatermark

I convert PDF -> many JPEG and many JPEG -> many PDF using ghostscript. I need to add watermark text on every converted JPEG (PDF) page. Is it possible using only Ghostscript and PostScript?

The only way I found:

gswin32c -q -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -sOutputFile=output.pdf watermark.ps input.pdf

But this will insert watermark.ps watermark on first separate page in output.pdf.

Can I do this on output PDF pages directly?

Can I do this on output JPEG pages directly?

<<
   /BeginPage
   { gsave
       /Helvetica_Bold 120 selectfont
       .85 setgray 130 70 moveto 50 rotate (Sample) show
     grestore
   } bind
>> setpagedevice

If I use /EndPage instead of /BeginPage – it says setpagedevice is not applicable…

How to remake this script for /EndPage?

Best Answer

Bit too big for a comment, so I've added a new answer. The EndPage procedure (see page 441 of the PostScript Language Reference Manual) takes two additional parameters on the stack, a count of pages emitted so far, and a reason code.

You can use the count of pages to do interesting things like duplexing, or only marking even pages or whatever, but I assume in this case you don't want it, so you just 'pop' it from the stack.

The reason code tells you why the page is being emitted, again you probably don't care so you just pop the value.

Finally the EndPage must return a boolean value to the interpreter saying whether or not to transmit the page (this allows you to do other interesting things, like only printing the first 10 pages and so on).

So you need to initially remove two values, execute your code and return a boolean. Pretty trivial:

<<
   /EndPage
   { pop pop %% *BEFORE* gsave as that puts a gsave object on the stack
     gsave
     /Helvetica_Bold 120 selectfont
     .85 setgray 130 70 moveto 50 rotate (Sample) show
     grestore
     true %% transmit the page, set to false to not transmit the page
   } bind
>> setpagedevice
Related Topic