How to add page numbers to Postscript/PDF

前端 未结 14 1933
臣服心动
臣服心动 2020-12-07 12:06

If you\'ve got a large document (500 pages+) in Postscript and want to add page numbers, does anyone know how to do this?

14条回答
  •  渐次进展
    2020-12-07 12:15

    I wrote the following shell script to solve this for LaTeX beamer style slides produced with inkscape (I pdftk cat the slides together into the final presentation PDF & then add slide numbers using the script below):

    #!/bin/sh
    
    # create working directory
    tmpdir=$(mktemp --directory)
    
    # read un-numbered beamer slides PDF from STDIN & create temporary copy
    cat > $tmpdir/input.pdf
    
    # get total number of pages
    pagenum=$(pdftk $tmpdir/input.pdf dump_data | awk '/NumberOfPages/{print $NF}')
    
    # generate latex beamer document with the desired number of empty but numbered slides
    printf '%s' '
    \documentclass{beamer}
    \usenavigationsymbolstemplate{}
    \setbeamertemplate{footline}[frame number]
    \usepackage{forloop}
    \begin{document}
     \newcounter{thepage}
      \forloop{thepage}{0}{\value{thepage} < '$pagenum'}{
        \begin{frame}
        \end{frame}
      }
    \end{document}
    ' > $tmpdir/numbers.tex
    
    # compile latex file into PDF (2nd run needed for total number of pages) & redirect output to STDERR
    pdflatex -output-directory=$tmpdir numbers.tex >&2 && pdflatex -output-directory=$tmpdir numbers.tex >&2
    
    # add empty numbered PDF slides as background to (transparent background) input slides (page by
    # page) & write results to STDOUT
    pdftk $tmpdir/input.pdf multibackground $tmpdir/numbers.pdf output -
    
    # remove temporary working directory with all intermediate files
    rm -r $tmpdir >&2
    

    The script reads STDIN & writes STDOUT printing diagnostic pdflatex output to STDERR.

    So just copy-paste the above code in a text file, say enumerate_slides.sh, make it executable (chmod +x enumerate_slides.sh) & call it like this:

    ./enumerate_slides.sh < input.pdf > output.pdf [2>/dev/null]
    

    It should be easy to adjust this to any other kind of document by adjusting the LaTeX template to use the proper documentclass, paper size & style options.

    edit: I replaced echo by $(which echo) since in ubuntu symlinks /bin/sh to dash which overrides the echo command by a shell internal interpreting escape sequences by default & not providing the -E option to override this behaviour. Note that alternatively you could escape all \ in the LaTeX template as \\.

    edit: I replaced $(which echo) by printf '%s' since in zsh, which echo returns echo: shell built-in command instead of /bin/echo. See this question for details why I decided to use printf in the end.

提交回复
热议问题