將參數副檔名變更為 \includegraphics (\includegraphics{xyz.svg} → \includegraphics{xyz.pdf

將參數副檔名變更為 \includegraphics (\includegraphics{xyz.svg} → \includegraphics{xyz.pdf

我正在嘗試編寫一個宏,它將文件名作為輸入,更改其擴展名,然後將其傳遞給\includegraphics.

我見過\includegraphics,嘗試另一個擴展,這提供了一個替代解決方案,但我很好奇為什麼我會得到結束名稱參數號我當前程式碼中的錯誤(另外,我認為該解決方案在 xelatex 中不起作用):

\documentclass{article}

\usepackage{graphicx}
\usepackage{xstring}

\usepackage{letltxmacro}
\LetLtxMacro{\IncludeGraphics}{\includegraphics}

\newcommand{\svgtopdf}[1]
  {\IfSubStr{#1}{.svg}{\StrSubstitute*{#1}{.svg}}{#1}}

\newcommand{\includegraphicsNaive}[2][]
  {\IncludeGraphics[#1]{\svgtopdf{#2}}}

\newcommand{\includegraphicsEdef}[2][]
  {\edef\pdfname{\svgtopdf{#2}}
   \IncludeGraphics[#1]{\pdfname}}

\newcommand{\includegraphicsNoExpand}[2][]
  {\edef\x{\noexpand\IncludeGraphics[#1]{\svgtopdf{#2}}}%
   \x{}}

\newcommand{\includegraphicsExpandafter}[2][]
  {\IncludeGraphics[#1]\expandafter{\svgtopdf{#2}}}

\begin{document}
\includegraphicsNaive{img.svg} % ERROR: Missing endcsname inserted.
\includegraphicsEdef{img.svg} % ERROR: Illegal parameter number in definition of \pdfname.
\includegraphicsNoExpand{img.svg} % ERROR: Illegal parameter number in definition of \x.
\includegraphicsExpandafter{img.svg} % ERROR: LaTeX Error: File `' not found.
\end{document}
  • 第一種方法是天真的方法,我思考它不起作用的原因是,graphicx 在內部建構了一個命令,其中包含部分文件名參數(文件的擴展名),以便為每種文件類型使用不同的宏,而且它似乎沒有擴展其參數在這樣做之前。

  • 第二種方法可能會因同樣的原因而失敗(\pdfname未擴展),但我不確定為什麼會出現不同的錯誤。

  • 我對第三種方法充滿希望,但不知道為什麼它行不通。

  • 我認為最後一個在發揮其魔力之前就會被expandafter消耗殆盡。includegraphics

正確的方法是什麼?

答案1

巨集xstring末尾有一個可選參數,用於將操作結果儲存在巨集中,可以在本例中使用。

此外,\StrSubstitute沒有加星號的版本。此外,您應該提供三個參數:完整字串、搜尋字串和替換字串,而您的 MWE 只有完整字串和搜尋字串。如果您願意,可以將替換字串留空 ( \StrSubstitute{#1}{.svg}{}[\tmpname]) 以嘗試所有可用的擴充。

工作中的 MWE:

\documentclass{article}

\usepackage{graphicx}
\usepackage{xstring}

\usepackage{letltxmacro}
\LetLtxMacro{\IncludeGraphics}{\includegraphics}

\newcommand{\svgtopdf}[1]
  {\IfSubStr{#1}{.svg}{\StrSubstitute{#1}{.svg}{.pdf}[\tmpname]}{\def\tmpname{#1}}}

\newcommand{\includegraphicsNaive}[2][]
  {\svgtopdf{#2}%
  \IncludeGraphics[#1]{\tmpname}}

\begin{document}
\includegraphicsNaive[width=3cm]{example-image.svg}
\includegraphicsNaive[width=3cm]{example-image-a.pdf}
\includegraphicsNaive[width=3cm]{example-image-b}
\end{document}

結果:

在此輸入影像描述

相關內容