我有这个可以根据文本大小缩放的简单表格。
\documentclass[a4paper,table]{article}
\usepackage[a4paper, headheight=2cm, left=2cm, right=2cm, bottom=3cm, top=2cm]{geometry} %a4paper, letterpaper
\usepackage{inputenc}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{titling}
\usepackage{float}
\usepackage{fontspec}
\pagenumbering{gobble}
\begin{document}
\begin{table}[]
\resizebox{\textwidth}{!}{%
\begin{tabular}{ll}
\multicolumn{1}{c}{\cellcolor[HTML]{9B9B9B}\textbf{Test}} & \\ \hline
\multicolumn{1}{|l|}{1} & \multicolumn{1}{l|}{1} \\ \hline
\end{tabular}%
}
\end{table}
\end{document}
一切都很好,但是当文本很短时,表格和文本都会很大(如上例所示)。
有没有办法设置文本的默认大小以避免出现这种过大的字体?例如,我需要以某种方式检查是否有足够的空间,将字体大小设置为 12,否则缩放表格。
谢谢
答案1
您可以将表格排版到框中并测量。如果太大,请按比例缩放以适合:
笔记:
- 第一张桌子不太大,所以没有缩放。第二张桌子太大,因此缩放以适合。
- 考虑将该
booktabs
包用于您的表格。
代码:
\documentclass[a4paper,table,12pt]{article}
\usepackage[a4paper, headheight=2cm, left=2cm, right=2cm, bottom=3cm, top=2cm]{geometry} %a4paper, letterpaper
\usepackage{inputenc}
\usepackage{xcolor,showframe}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{titling}
\usepackage{float}
\usepackage{fontspec}
\pagenumbering{gobble}
\newsavebox{\MyTable}
\newcommand*{\ResizeTableIfTooBig}[1]{%
%% #1 = table
\savebox{\MyTable}{#1}%
\ifdim\wd\MyTable<\linewidth
\usebox{\MyTable}%
\else
\resizebox{\textwidth}{!}{\usebox{\MyTable}}%
\fi
}%
\begin{document}
\noindent
\ResizeTableIfTooBig{%
\begin{tabular}{ll}
\multicolumn{1}{c}{\cellcolor[HTML]{9B9B9B}\textbf{Test}} & \\ \hline
\multicolumn{1}{|l|}{1} & \multicolumn{1}{l|}{1} \\ \hline
\end{tabular}%
}%
\noindent
\ResizeTableIfTooBig{%
\begin{tabular}{ll}
\multicolumn{1}{c}{\cellcolor[HTML]{9B9B9B}\textbf{Test}} & \\ \hline
1 & Some very very long text that is too wide to fit here so table will need to be scaled to get it to fit\\ \hline
\multicolumn{1}{|l|}{1} & \multicolumn{1}{l|}{1} \\ \hline
\end{tabular}%
}%
\end{document}
答案2
该包adjustbox
可以做到这一点。
\documentclass[a4paper,table]{article}
\usepackage[
a4paper,
headheight=2cm,
left=2cm,
right=2cm,
bottom=3cm,
top=2cm,
]{geometry}
\usepackage{xcolor}
\usepackage{adjustbox}
\newcommand{\multicolumncolor}[4]{%
\multicolumn{#1}{#2}{\cellcolor[HTML]{#3}#4}%
}
\begin{document}
\begin{table}[htp]
\centering
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{ll}
\multicolumncolor{1}{c}{9B9B9B}{\textbf{Test}} & \\
\hline
1 & 1 \\
\hline
\end{tabular}
\end{adjustbox}
\end{table}
\end{document}