是否可以遍历包含图片的文件夹,同时首先过滤文件扩展名 tikz、png、pdf 或 eps,然后获取目录的文件名列表以用于 for 循环,并使用它们的文件名作为图像文本添加到我的 latex 代码中?我尝试在谷歌上搜索代码示例,但还没有找到。
答案1
这个答案我早就准备好了,就等待有人来问。此处(点击)是历史。
批处理文件
rem batch.bat
echo off
rem %1 path (relative to the main input file) to the files to be iterated
rem %2 output file name
rem remaining args represent the extension of file to be iterated
set curdir=%CD%
cd "%~1"
shift
rem output must be enclosed with "" to allow spaces in the path
set output="%curdir%\%~1.list"
if exist %output% del %output%
copy nul %output%
shift
:loop
if "%~1"=="" goto :eof
dir /b *.%~1 >> %output%
shift
goto :loop
文件名.tex
% filename.tex must be compiled with
% pdflatex -shell-escape filename.tex
\documentclass[preview,border=12pt]{standalone}
\usepackage{graphicx}
\newread\reader
\newcount\TotalFiles
\makeatletter
\newcommand\IterateImages[2]{%
% #1: directory path with a trailing /
% #2: a list of file extensions: eps pdf jpg png
\immediate\write18{batch "#1" \jobname\space #2}
\openin\reader=\jobname.list\relax
\loop
\read\reader to \filename
\unless\ifeof\reader
\filename@parse{\filename}
\section*{\filename}
\begin{center}
\includegraphics[scale=0.1]{"#1\filename@base"}
\end{center}
\endgraf
\advance\TotalFiles1\relax
\repeat
\closein\reader
}
\makeatother
\begin{document}
% ./ also works
\IterateImages{Sample Pictures/}{jpg png pdf}
\section*{Summary}
There is(are) \the\TotalFiles\ file(s) in total.
\end{document}
输出
为了证明我没有说谎。
笔记
出于安全原因,filecontents
不允许我们batch.bat
即时创建。
答案2
在 OSX 上运行时我需要添加
\endlinechar=-1
来删除添加到输入行末尾的默认字符。
\documentclass[]{article}
\usepackage{graphicx}
\usepackage[colorlinks=true, pdfstartview=FitV, linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref}
\usepackage[hyphenbreaks]{breakurl}
\usepackage[space]{grffile}% used to allow spaces within the filenames
\newread\reader
\newcommand\IterateLines[2]{
\immediate\write18{ls -1 "#1" > \jobname.txt}
\openin\reader=\jobname.txt\relax
\endlinechar=-1
\loop
\read\reader to \line
\unless\ifeof\reader
{\line}\par
\includegraphics[width=2cm]{{#1\line}} %
\par
\repeat
\closein\reader
}
\makeatother
\begin{document}
Images from \url{https://www.pexels.com/public-domain-images/}\par
\IterateLines{testimages/}{png}
\end{document}