pdfghostscriptpostscriptpdfstamper

/EndPage count never increases


I'm trying to add a piece of text to a 2-pages pdf with ghostscript. Looking at similar questions (https://stackoverflow.com/a/9783516/1581629 and https://stackoverflow.com/a/12596669/1581629 https://stackoverflow.com/a/18774237/1581629) I was trying to use /EndPage and I was expecting to get a "page counter" on the stack and use it to choose the page to modify.

However, when the "reason" in the stack of /EndPage (pg.441 of the Postscript language reference) is 0, the "counter" is also always 0.

A MWE could be (using gs 9.23 from git repo):

gs -o out.pdf -sDEVICE=pdfwrite a.ps in.pdf

where a.ps is:

<<
    /EndPage
    {
        (-----------------START\n) print
        stack
        true
        (------------------END\n) print
    }
>> setpagedevice

and in.pdf was made with pdflatex (texlive 2017):

\documentclass{article}
\begin{document}
aaa

\newpage

bbb
\end{document}

Can anyone point me on what I'm missing here?


Solution

  • The Ghostscript PDF interpreter executes setpagedevice at the start of each page of the PDF file.

    It does this because each page in a PDF file can have a different MediaBox, so it extracts the MediaBox and constructs a dictionary with a PageSize entry containing the MediaBox in order to set the (potentially) new media size.

    Each execution of setpagedevice resets the count of pages, so each page is effectively the first page.

    If you need a page count then you can create a private dictionary, initialise a counter to 0, then open the dictionary test the current count value (and optionally increment it) in the EndPage procedure.