UPDATE: Check out Password-protect current pdf (revisted) for a simpler version.
Every so often, I need to password-protect a pdf. On macOS, Preview has a simple solution, but I figured there must be a command line utility to make this happen. There are options, but qdf did the job just fine.
qpdf --verbose --encrypt USER-PASSWORD OWNER-PASSWORD KEY-LENGTH -- input.pdf output.pdf
So what does qpdf
have to do with Emacs? Command-line utilities are easy to invoke from Emacs via shell-command
(M-!), but I don't want to remember the command nor the parameters. I may as well add a function that does what I mean and password-protect either buffers or dired files.
(defun pdf-password-protect ()
"Password protect current pdf in buffer or `dired' file."
(interactive)
(unless (executable-find "qpdf")
(user-error "qpdf not installed"))
(unless (equal "pdf"
(or (when (buffer-file-name)
(downcase (file-name-extension (buffer-file-name))))
(when (dired-get-filename nil t)
(downcase (file-name-extension (dired-get-filename nil t))))))
(user-error "no pdf to act on"))
(let* ((user-password (read-passwd "user-password: "))
(owner-password (read-passwd "owner-password: "))
(input (or (buffer-file-name)
(dired-get-filename nil t)))
(output (concat (file-name-sans-extension input)
"_enc.pdf")))
(message
(string-trim
(shell-command-to-string
(format "qpdf --verbose --encrypt '%s' '%s' 256 -- '%s' '%s'"
user-password owner-password input output))))))