2

I would like to use \includegraphics{folder/*.pdf} in this simple way, I've got a folder inside which I have different files and I want to pick only the pdf one. Is this possible ?

  • “The” PDF one? Will there be just one? – egreg May 9 at 13:24
  • yes, in my case. – Andrea May 9 at 14:03
1

Assuming a Unix system:

\documentclass{article}
\usepackage{xparse}
\usepackage{graphicx}

\ExplSyntaxOn
\NewDocumentCommand{\includegraphicsfromfolder}{O{}mm}
 {% #1 = options, #2 = folder path, #3 = extension
  \sys_get_shell:nnN { ls~-m~#2/* } { } \l_tmpa_tl
  \seq_set_split:NnV \l_tmpa_seq { , } \l_tmpa_tl
  \seq_map_inline:Nn \l_tmpa_seq
   {
    \regex_match:nnT { \.#3\Z } { ##1 }
     {
      \includegraphics[#1]{##1}
      \seq_map_break:
     }
   }
 }
\ExplSyntaxOff

\begin{document}

\includegraphicsfromfolder[width=4cm]{folder}{pdf}

\includegraphicsfromfolder[height=2cm]{folder}{png}

\end{document}

This requires the -shell-escape option.

We get a ls from the given folder, with entries separated by commas; then the list is split at commas and each entry is tested to end with the required extension; in the case of success, the image is included and the mapping is stopped.

It could be possible to add code for ensuring that some warning is issued if no suitable image is found.

enter image description here

The folder subdirectory for the example contains

> ls folder
example-image-a.png example-image.pdf
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.