Search code examples
pdfghostscript

GhostScript draw text with alpha


GhostScript version: 9.53.3

I need to stamp a pdf with (Entwurf) for all pages.

<<
   /EndPage
   {
     gsave
       /Helvetica-Bold 120 selectfont .5 .setfillconstantalpha .45 setgray
       130 430 moveto 30 rotate (Entwurf) show -30 rotate
       130 130 moveto 30 rotate (Entwurf) show -30 rotate
     grestore
     true
   } bind
>> setpagedevice

Without .5 .setfillconstantalpha this script runs successfully. I have used 0.5 .setopacityalpha before but it crashes the same way and is deprecated since 9.53.

cat start.pdf | gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=/workspace/test.pdf Watermark_def.ps -
Error: /undefined in /--.endpage--
Operand stack:
   (/tmp/gs_KvXeWS)   --nostringval--   --dict:7/16(L)--   false   --dict:4/6(L)--   2   0   2   0.5
Execution stack:
   %interp_exit   .runexec2   --nostringval--   .endpage   --nostringval--   2   %stopped_push   --nostringval--   .endpage   .endpage   false   1   %stopped_push   1990   1   3   %oparray_pop   1989   1   3   %oparray_pop   1977   1   3   %oparray_pop   .endpage   1978   3   3   %oparray_pop   .endpage   .endpage   2   1   12   .endpage   %for_pos_int_continue   .endpage   1938   4   7   %oparray_pop   .endpage   1820   6   7   %oparray_pop   .endpage   9   .endpage
Dictionary stack:
   --dict:731/1123(ro)(G)--   --dict:1/20(G)--   --dict:80/200(L)--   --dict:80/200(L)--   --dict:133/256(ro)(G)--   --dict:320/325(ro)(G)--   --dict:31/32(L)--
Current allocation mode is local
GPL Ghostscript 9.53.3: Unrecoverable error, exit code 1

Solution

  • That isn't a crash. It's a graceful exit on an error condition.

    .setfillconstantalpha is a non-standard PostScript extension, PostScript does not support transparency (except in some limited fashions) so you can't use alpha blending in a normal PostScript program.

    Ghostscript, because of the needs of PDF, does support transparency in the graphics library, and some limited support was added to the PostScript language to enable its use. This is decidedly non-standard and will not work on any other PostScript interpreter.

    However, the use of these extensions is dependent on various operations happening in the correct sequence; get it wrong and it may crash. So by default, you can't use them in order to prevent malicious programs crashing the interpreter (or worse).

    If you want to use these extensions (and take the risk of things blowing up) then you need to specifically allow them. This is documented, see the online documentation here and look for -dALLOWPSTRANSPARENCY. Also here.