Watermark all pdfs in folder with the file's name

I have a bunch of pdf files in a folder. I would like to watermark all of them. The watermak should be the name of the file itself. How?

I'm using ubuntu 18.04LTS


Solution 1:

  • Create a script gedit /home/user/folderwithpdfs/pdfstamp.sh, which will generate watermark.pdf file with shortened filename's text inside as a watermark:

    #!/bin/bash
    text=${1?missing text to show}
    # Restricts string to 15 symbols from start, without extension and folder's path
    mtext=$(echo ${text:0:15} | sed 's/.pdf//' | sed -e 's,.*/,,') 
    angle=45 # in degrees counterclockwise from horizontal
    grey=0.75 # 0 is black 1 is white
    
    ps2pdf - - <<!
    %!PS
    /cm { 28.4 mul } bind def
    /draft-Bigfont /Helvetica-Bold findfont 72 scalefont def
    /draft-copy {
            gsave initgraphics $grey setgray
            5 cm 10 cm moveto
            $angle rotate
            draft-Bigfont setfont
            ($mtext) show grestore
     } def
    draft-copy showpage
    !
    
  • Place it to folder with pdf files

  • Run the next command inside the folder with pdf files, which will create watermark.pdf file each time, apply it to current file and output it to the new file:

    for f in ./*.pdf 
      do ./pdfstamp.sh "$f" > watermark.pdf
      pdftk "$f" stamp watermark.pdf output "$f.pdf"
    done
    

    The command will create filename.pdf.pdf files with watermark of file names but without extension and with 15 symbols length.

    Script mostly created by @meuh.

    Result:

    enter image description here

The next variant of the command will place watermark to the background, so it could look like transparent:

for f in ./*.pdf; do ./pdfstamp.sh "$f" > watermark.pdf && pdftk "$f" background watermark.pdf output "$f.pdf"; done

enter image description here

But this method has a downside: this watermark could be covered over by images.