3
submitted
1 week ago* (last edited 1 week ago)
by
LibreMonk@linkage.ds8.zone
to
c/tex_typesetting@lemmy.sdf.org
Some might find it useful to import a text file and put the contents into a PDF annotation. E.g. a PDF is in language A and you want to make a translation available in language B, in a PDF annotation.
Here’s how:
\documentclass{article}
\usepackage{mwe}
\usepackage{pdfpages}
\usepackage{pdfcomment}
\usepackage{newfile}
\usepackage{xstring}
\usepackage{catchfile}
% heredoc holding text that normally breaks the \pdfcomment command:
\begin{filecontents*}{\jobname_sample.txt}
line one
line two
tricky symbols: _&%
\end{filecontents*}
% normally the above file is whatever you supply to be imported into the PDF annotation. The heredoc is just to provide a self-contained sample.
% Create \pdfcommentfile, which is a version of \pdfcomment that can read from a file:
\makeatletter
\gdef\pdfcommentfile#1{%
\begingroup
\everyeof{\noexpand}%
\long\edef\temp{\noexpand\pdfcomment{\@@input{#1}}}%
\temp
\endgroup
}%
\makeatother
\CatchFileDef{\cfile}{\jobname_sample.txt}{} % side-effects: replaces blank lines with “\par” and drops percent symbols
% Replace blank lines with \textLF and replace special symbols with those that are safe for \pdfcomment. Warning: this is probably not a complete list of all constructs that break \pdfcomment!
\StrSubstitute{\cfile}{\par}{\string\noexpand\string\textLF\ }[\pdfannotationtxt] % the hard space is after textLF is a bit unfortunate; not sure how to do a normal space there
\StrSubstitute{\pdfannotationtxt}{\%}{\string\noexpand\string\%}[\pdfannotationtxt]
\StrSubstitute{\pdfannotationtxt}{_}{\string\noexpand\string\_}[\pdfannotationtxt]
\StrSubstitute{\pdfannotationtxt}{&}{\string\noexpand\string\&}[\pdfannotationtxt]
% the \pdfcomment command cannot directly handle the above substitutions (nor can it handle the original unsubstituted version). So we write the new version to another file:
\newoutputstream{filteredresult}
\openoutputfile{\jobname_filtered.txt}{filteredresult}
\addtostream{filteredresult}{\pdfannotationtxt}
\closeoutputstream{filteredresult}
\begin{document}
\pdfcommentfile{\jobname_filtered.txt}
\includepdf{example-image-a.pdf}
\end{document}
There should be a way to substitute the special characters and blank lines then feed it directly to \pdfcomment, but I’ve exhausted that effort. I’ve been in this LaTeX rabbit hole for days now trying to do something that should be simple. So this is as far as I go. The code above works but it’s ugly as fuck that we have to write the filtered text to file then read the file back in. The file i/o slows down compilation much more than what I consider reasonable.