检查字体系列是否存在

检查字体系列是否存在

我想检查实际使用的字体是否安装了特殊的字体系列,例如:

%check for semibold
\ifx\fontseries{sb} % doesnt work
    \def\textsb#1{\fontseries{sb}\selectfont #1}
\else
    \let\textsb\textbf
\fi

如果您不使用额外的包,我将非常感激您的答复。

答案1

\documentclass{article}

\usepackage{libertine} % Libertine has sb

\makeatletter
\DeclareRobustCommand{\sbseries}{%
  \@tempswafalse
  \sbox\z@{%
    % Disable warnings for missing fonts
    \let\@font@warning\@gobble
    % Save the current value of \@defaultsubs
    \let\@tempsubs\@defaultsubs
    % try sb
    \fontseries{sb}\selectfont
    % the value of \@defaultsubs might have changed
    \global\let\@defaultsubs\@tempsubs
    % define a temporary macro for \ifx
    \escapechar\m@ne
    \edef\@tempa{\string\sb}%
    % get the computed current series
    % see \define@newfont in latex.ltx
    \expandafter\expandafter\expandafter
       \split@name\expandafter\string\font@name\@nil
    % compare the current series with sb
    \ifx\f@series\@tempa
      \aftergroup\@tempswatrue
    \fi
  }%
  \if@tempswa
    % sb exists
    \fontseries{sb}\selectfont
  \else
    \bfseries
  \fi
}
\DeclareTextFontCommand{\textsb}{\sbseries}
\makeatother  

\begin{document}

abc

\textsb{abc}

\textbf{abc}

\fontfamily{cmr}\selectfont
abc

\textsb{abc}

\textbf{abc}

\end{document}

在此处输入图片描述

答案2

egreg 的回答非常好,可能比我要建议的更好。

\documentclass[a4paper]{article}
\usepackage{libertine}% has sb
\makeatletter
\def\checkseries#1#2{%
  {\ifcsname\f@encoding/\f@family/#1/\f@shape\endcsname
    \fontseries{#1}%
  \else
    \fontseries{\bfdefault}%
  \fi
  \selectfont #2}%
}
\makeatother
\begin{document}
rm \checkseries{sb}{sb?} \textbf{bf}
\par\fontfamily{cmr}\selectfont
rm \checkseries{sb}{sb?} \textbf{bf}
\end{document}

事实上,我在这里回答的主要原因是想问一下这种方法是否有缺陷。有时越简单越好,但并非总是如此!

相关内容