[Tex/LaTex] Automating the appearance of email addresses as images

pdftexprivacyurls

Publishing pdf manuscripts on the web with emails embedded in the file results in spam.

More generally, I am looking for a way to automate the conversion of a string to an image.

It's quite easy to solve this old problem using \includegraphics an image (more here). The trouble is that you need a distinct file and typesetting run, and you end up with unnecessary image files that you cannot delete carelessly lest you also delete non-generated images.

Can you think of a way to do this on the fly? It's understood that people will have to type the email addresses if they need to message you, but that's the point.

More briefly/concretely

With what can one replace #1

\documentclass{article}
\newcommand\showasimage[1]{#1}
\begin{document}
\showasimage{joe@foo.bar}
\end{document}

such that #1 appears as an image?

Edit

It would be really nice if the pdf file remains vectorial.

Best Answer

The following solution does not (anymore) use ImageMagick's convert command as this would always create raster images, which will stand out from the text. Instead, it uses Ghostscript to vectorise the letters so that they appear like normal text but are in fact an uncopyable image. Note that you also have to run pdflatex with the --shell-escape switch enabled, so that the commands from \write18 will indeed be sent to the shell.

The image will be cropped so that it is placed on the base line (with descenders taken into account), and the font will match the one from the context. The temporary files (using a counter to allow more than one image on the same page) will be deleted at the end.

\documentclass{article}
\usepackage{graphicx}
\makeatletter
\newcount\@emailcount
\newcommand\showasimage[1]{%
  \global\advance\@emailcount 1
  \edef\x{email-\the\@emailcount}%
  \immediate\write18{echo '\unexpanded{\\font\\1=}\fontname\font' > \x.tex}%
  \immediate\write18{echo '\unexpanded{\\1#1\\nopagenumbers\\bye}' >> \x.tex}%
  \immediate\write18{pdftex \x.tex}%
  %\immediate\write18{convert -units PixelsPerInch -density 300 -trim \x.pdf \x.png}% raster
  \immediate\write18{gs -dNOCACHE -sDEVICE=epswrite -dQUIET -o \x.eps \x.pdf}% vector
  \immediate\write18{epstopdf --hires \x.eps}%
  \settodepth{\@tempdima}{#1}%
  \raisebox{-\the\@tempdima}{\includegraphics{\x.pdf}}%
}
\AtEndDocument{%
  \loop
    \immediate\write18{rm email-\the\@emailcount.*}%
    \advance\@emailcount-1
    \ifnum\@emailcount>0\repeat
}
\makeatother
\begin{document}
Email \showasimage{oe@foo.bar} not copyable

\textit{match font and depth: \showasimage{joe@foo.bar}} 

\end{document}

which yields (with the first line selected):

emails as images