\padnumTeX 数字的可扩展宏

\padnumTeX 数字的可扩展宏

我试图将大量图像纳入文档,并决定使用计数器来生成文件名。一个最小(不起作用)的示例如下所示:

\documentclass{article}
\usepackage{graphicx}
\usepackage{fmtcount}

\newcounter{imgnr}

\begin{document}    
    % image names are img000.png, img001.png, ..., img999.png
    \setcounter{imgnr}{1}
    \includegraphics[width=0.5\linewidth]{./images/img\padzeroes[3]\decimal{imgnr}.png}
    \setcounter{imgnr}{2}
    \includegraphics[width=0.5\linewidth]{./images/img\padzeroes[3]\decimal{imgnr}.png}
    \setcounter{imgnr}{10}
    \includegraphics[width=0.5\linewidth]{./images/img\padzeroes[3]\decimal{imgnr}.png}
\end{document}

此示例出现错误TeX capacity exceeded, sorry [input stack size=5000]。有什么办法可以修复此问题吗?或者这是错误的做法?

在实际示例中,计数器会递增,然后为每个图像添加一个带有标题、一些文本和表格以及图像的模板。这就是我使用计数器的原因。我可以很好地选择给定图像的数据。

奖励:Image 'imgxxx.png' is missing如果找不到图像,则显示一个框。

答案1

您需要一个可扩展版本的填充。以下示例重新定义\theimgnr为扩展为用零填充的数字:

\documentclass{article}
\usepackage{graphicx}

\newcounter{imgnr}
\renewcommand{\theimgnr}{%
  \ifnum\value{imgnr}<10 0\fi
  \ifnum\value{imgnr}<100 0\fi
  \the\value{imgnr}%
}

\begin{document}
    % image names are img000.png, img001.png, ..., img999.png
    \setcounter{imgnr}{1}

\includegraphics[width=0.5\linewidth]{./images/img\theimgnr.png}
    \setcounter{imgnr}{2}

\includegraphics[width=0.5\linewidth]{./images/img\theimgnr.png}
    \setcounter{imgnr}{10}

\includegraphics[width=0.5\linewidth]{./images/img\theimgnr.png}
\end{document}

\padnumTeX 数字的可扩展宏

TeX 的数字范围是有限的,最大数字是 2 31 -1。因此宏\padnum利用这个事实使其实现简单。第一个参数是数字的个数,第二个参数是 0 到 2 31 -1 之间的数字。

\documentclass{article}
\usepackage{graphicx}

\newcounter{imgnr}

\makeatletter
\newcommand{\padnum}[2]{%
  \ifnum#1>1 \ifnum#2<10 0\fi
  \ifnum#1>2 \ifnum#2<100 0\fi
  \ifnum#1>3 \ifnum#2<1000 0\fi
  \ifnum#1>4 \ifnum#2<10000 0\fi
  \ifnum#1>5 \ifnum#2<100000 0\fi
  \ifnum#1>6 \ifnum#2<1000000 0\fi
  \ifnum#1>7 \ifnum#2<10000000 0\fi
  \ifnum#1>8 \ifnum#2<100000000 0\fi
  \ifnum#1>9 \ifnum#2<1000000000 0\fi
  \fi\fi\fi\fi\fi\fi\fi\fi\fi
  \expandafter\@firstofone\expandafter{\number#2}%
}

\makeatother

% image names are img000.png, img001.png, ..., img999.png
\setcounter{imgnr}{1}

\includegraphics[width=0.5\linewidth]{./images/img\padnum{3}{\value{imgnr}}.png
    \setcounter{imgnr}{2}

\includegraphics[width=0.5\linewidth]{./images/img\padnum{3}{\value{imgnr}}.png
    \setcounter{imgnr}{10}

\includegraphics[width=0.5\linewidth]{./images/img\padnum{3}{\value{imgnr}}.png
\end{document}

评论:

  • \padnum否, via 的可选参数\newcommand*{\padnum}[2][3]{...}不是可能,因为\padnum不再可扩展并且文件名的使用将会中断。

相关内容