# Get write18 to execute after file parsing

Follow up to Get write18 to accept / expand command

I want to crop a pdf and print it. My \the\pdfshellescape is 1, so my shell-escape is working. My MWE is

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}

\usepackage{graphicx}

\newcommand{\filename}{}
\newcommand{\croppedfilename}{}
\newcommand{\includecroppedgraphics}[1]{%
\makeatletter
\filename@parse{#1}
\renewcommand{\filename}{#1}
\renewcommand{\croppedfilename}{\filename@area\filename@base.cropped.\filename@ext}
\makeatother
\immediate\write18{pdfcrop #1 \croppedfilename}%
\fbox{\includegraphics[width=\linewidth]{\croppedfilename}}
}

\begin{document}

\includecroppedgraphics{mypath/myimage.pdf}

\the\pdfshellescape

\end{document}


This does not produce the cropped image. From the log I get

runsystem(pdfcrop mypath/myimage.pdf mypath/myimage.pdf@areamypath/myimage.pdf@ base.cropped.mypath/myimage.pdf@ext)...executed.

Obviously the parsing I got from https://tex.stackexchange.com/a/39636/49283 did not work even though it did work in Get write18 to accept / expand command

How do I get the parsing right here?

A few errors to fix:

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}

\usepackage{graphicx,grffile}

\newcommand{\filename}{}
\newcommand{\croppedfilename}{}

\makeatletter
\newcommand{\includecroppedgraphics}[1]{%
\filename@parse{#1}%
\edef\croppedfilename{\filename@area\filename@base.cropped.\filename@ext}%
\immediate\write18{pdfcrop #1 \croppedfilename}%
\fbox{\includegraphics[width=\linewidth]{\croppedfilename}}%
}
\makeatother

\begin{document}

\includecroppedgraphics{mypath/myimage.pdf}

\end{document}

1. \makeatletter and \makeatother must surround a definition using @-commands

2. \renewcommand is not good for \croppedfilename, you have to fully expand everything in the replacement text

3. grffile is needed for multiple periods in the file name

4. Don't forget to protect end-of-lines

• My pdf has different pages and I want each page to be cropped individually, since I am going to use \includegraphics[width=\linewidth, page=#1]. Currently small images are still only cropped as much as other pages that have larger images. – Make42 Feb 26 '18 at 13:34
• @Make42 That's quite a different problem – egreg Feb 26 '18 at 13:42
• Should I post a new question, or is this not a LaTeX question? – Make42 Feb 26 '18 at 13:47
• @Make42 If I do pdfcrop on a multipage document, a single PDF file is created where every page is cropped differently according to the page contents; if I later include the pages with \includegraphics[page=<n>]{file.pdf}, I get the expected bounding boxes. – egreg Feb 26 '18 at 13:53
• onetransistor.blogspot.de/2016/01/pdf-crop-linux-software.html says that pdfcrop is not able to do this - maybe we are using different versions? I am using pdfcrop 2012/11/02 v1.38 – Make42 Feb 26 '18 at 14:29