我如何确保表格和图形不会划分段落?

我如何确保表格和图形不会划分段落?

根据我所在大学的书面作业规则,表格或图形不能分割段落。在下面的 MWE 中,表格不适合放在第一页,因此放在第二页。这没问题,但下面的段落被表格的位置分割了。理想情况下,表格应该出现在这个分割段落之后,或者分割段落应该出现在表格之后。我一般该怎么做,因为这种情况经常在我的文本中重复出现?

\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{blindtext}
\begin{document}
\blindtext[3]\par

Text text \textbf{The table should appear here, avoiding splitting the paragraph. According to the rules for my work, paragraphs should be complete, either before or after tables and figures.}\par

\begin{table}[h!]
\centering
\caption{The caption}
\begin{tabular}{|c|c|}
\hline
 &  \\
\hline
1 & 7 \\
\hline
2 & 77 \\
\hline
3 & 777 \\
\hline
4 & 777 \\
\hline
5 & 7777 \\
\hline
\end{tabular}
\end{table}

\blindtext\par

\end{document}

在此处输入图片描述

答案1

如果两个页面不适合,这将创建命令\partable将表格放在段落前面。

\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{blindtext}

% Place the paragrpah first it there is enougth room for both.
\makeatletter
\newif\ifparfirst

\newcommand{\partable}[2]% #1 = paragraph, #2 = table
{\bgroup\par% use local registers
  \setbox7=\vbox{#1}% measure height
  \sbox9{\parbox[b]{\columnwidth}{\def\@captype{table}#2}}%
  \parfirsttrue
  \ifdim\pagegoal=\maxdimen% new page
  \else
    \setlength{\dimen7}{\dimexpr \pagegoal-\pagetotal}% remaining space on page
    \setlength{\dimen9}{\dimexpr \ht7 + \dp7 + \ht9 + \dp9 + \intextsep}%
    \ifdim\dimen7<\dimen9
      \parfirstfalse
    \fi
  \fi
  \ifparfirst
    \unvbox7
    \begin{table}[h]\usebox9\end{table}
  \else
    \begin{table}[h]\usebox9\end{table}
    \unvbox7
  \fi
  %\the\dimen7\par\the\dimen9\par\the\dimexpr \ht9 + \dp9 + \intextsep\relax
\par\egroup}
\makeatother    

\begin{document}
\blindtext[3]\par

\partable{Text text \textbf{The table should appear here, avoiding splitting the paragraph. According to the rules for my work, paragraphs should be complete, either before or after tables and figures.}}%
{\centering
\caption{The caption}
\begin{tabular}{|c|c|}
\hline
 &  \\
\hline
1 & 7 \\
\hline
2 & 77 \\
\hline
3 & 777 \\
\hline
4 & 777 \\
\hline
5 & 7777 \\
\hline
\end{tabular}
}

\blindtext\par

\end{document}

相关内容