How do I properly expand a macro \myviewport so that it is parsed as the viewport=0pt 10pt 100pt 200pt argument of \includegraphics[clip, \myviewport]{somepdf.pdf}?
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\newcommand*{\aport}{45.29pt 86.28pt 235pt 187pt}
\includegraphics[clip, viewport={\aport}]{somepdf.pdf}
\end{document}
Error: ! Argument of \Gread@parse@vp has an extra }.
My simple idea was based on
\includegraphics optional argument not resolved if macro
What does work is giving individual macros for each viewport value:
\documentclass{article}
\usepackage{graphicx}
\usepackage{calc}
\begin{document}
\newlength{\Xoffset}
\setlength{\Xoffset}{35pt}
\newlength{\myl}
\setlength{\myl}{235pt - \Xoffset}
\newcommand*{\lux}{200pt}
\includegraphics[clip, viewport=10pt 50pt \lux{} \the\myl{}, page=3]{somepdf.pdf}
\end{document}
Note that \myl is a length and \lux is a "string".
In the long run I'd like to automate the cropping of some pdf files (which have Media Boxes not starting at 0 0):
\documentclass{article}
\usepackage{graphicx}
\usepackage{calc}
\newlength{\Xoffset}
\newlength{\Yoffset}
\newcommand*{\setpdfoffset}[2]{
\setlength{\Xoffset}{#1}
\setlength{\Yoffset}{#2}
}
\newcommand*{\aviewport}{} %set an empty default
\setpdfoffset{0pt}{0pt} %set a default
\newcommand*{\setviewport}[4]{
\newlength{\mylux}\setlength{\mylux}{#1-\Xoffset}
\newlength{\myluy}\setlength{\myluy}{#2-\Yoffset}
\newlength{\myrox}\setlength{\myrox}{#3-\Xoffset}
\newlength{\myroy}\setlength{\myroy}{#4-\Yoffset}
\renewcommand*{\aviewport}{viewport={\the\mylux} {\the\myluy} {\the\myrox} {\the\myroy}}
}
\begin{document}
%in Windows command line:
% pdfinfo -box somepdf.pdf |awk "/MediaBox/ {print; print \"Xoffset=\"$2 \" Yoffset=\"$3\"\n\"; print \"\\newlength{\\Xoffset}\\setlength{\\Xoffset}{\"$2\"pt} \\newlength{\\Yoffset}\\setlength{\\Yoffset}{\"$3\"pt}\"}"
\setpdfoffset{35.29pt}{36.28pt}
\setviewport{45.29pt}{86.28pt}{235pt}{187pt}
\emph{\aviewport}
\fbox{\includegraphics[clip, \aviewport{}, page=2]{somepdf}
\end{document}
Error: keyval: viewport={10.0pt} {50.0pt} {199.71pt} {150.72pt} undefined. ...lip, \aviewport]{somepdf}}
XeLaTeX is my first choice, but pdfLaTeX doesn't like this code either.
Bonus: Get the X and Y Offset values for \setpdfoffset by using \input{|"pdfinfo -box somepdf.pdf |awk ..."}, but this is an escaping question and not an expanding.


key=valuepart in a macro breaks in general with keyval methods as the parser for keys doesn't see the right name: that's general and not dependent on the key involved. Here, you have a second issue asviewportis looking for four values separated by spaces, and again hiding stuff in a macro confuses the internals. – Joseph Wright Jan 07 '15 at 07:02