引数の拡張子を \includegraphics に変更します (\includegraphics{xyz.svg} → \includegraphics{xyz.pdf

引数の拡張子を \includegraphics に変更します (\includegraphics{xyz.svg} → \includegraphics{xyz.pdf

ファイル名を入力として受け取り、その拡張子を変更して、それを に渡すマクロを作成しようとしています\includegraphics

私は見た\includegraphics、別の拡張子を試してください、これは別の解決策を示していますが、なぜ私が終了csnameそしてパラメータ番号現在のコードにエラーがあります (また、その解決策は 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 が内部的にファイル名引数の一部 (ファイルの拡張子) を含むコマンドを構築して、ファイルの種類ごとに異なるマクロを使用するため、その前に引数を展開していないように見えるためです。

  • 2 番目のアプローチはおそらく同じ理由 (\pdfname展開されていない) で失敗しますが、なぜ別のエラーが発生するのかはわかりません。

  • 3 番目は期待していたのですが、なぜ機能しないのかわかりません。

  • 最後のものは、魔法が効く前expandafterに消費されてしまうと思います。includegraphics

正しい方法は何ですか?

答え1

マクロxstringには最後にオプションの引数があり、マクロ内の操作の結果を保存するために使用されます。この場合、これを使用できます。

また、 に\StrSubstituteは星付きバージョンがありません。さらに、完全な文字列、検索文字列、置換文字列の 3 つの引数を指定する必要がありますが、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}

結果:

ここに画像の説明を入力してください

関連情報