[Tex/LaTex] How to change the background color within a page

backgroundscolor

I have a one page document like below. I would like the background color would be green, then I would like change it to yellow. Is it possible?

\documentstyle{article}

\begin{document}

\pagecolor{green}
I would like the background color of the page until here would be green.\\

\pagecolor{yellow}
Then from now on, I would like the background would be yellow.

\end{document}

Best Answer

A command, which changes the page color from the current position does not need to know the exact location. Instead a large colored rectangle can be drawn. The following example moves \paperwidth to the left and draws a rectangle with width 2\paperwidth and height \paperheight. This covers the whole of the remaining page regardless of the current position on the page. An additional LaTeX run is not needed.

After drawing the rectangle, \pagecolor is used inside \afterpage to also get the real page color changed.

The command \changepagecolor supports the full syntax of \color or \pagecolor including the optional argument.

\documentclass{article}
\usepackage[a6paper, hmargin=12mm, vmargin=12mm, includefoot]{geometry}
\usepackage{lipsum}

\usepackage{color}
\usepackage{afterpage}

\makeatletter
% Macro \changepagecolor has the same syntax as \pagecolor or \color
% with an optional argument and a mandatory argument.
\newcommand*{\changepagecolor}{%
  \@ifnextchar[\@changepagecolor@i\@changepagecolor@ii
}
% Case: \changepagecolor[...]{...}
\def\@changepagecolor@i[#1]#2{%
  \@changepagecolor@do{[{#1}]{#2}}%
}
% Case: \changepagecolor{...}
\newcommand*{\@changepagecolor@ii}[1]{%
  \@changepagecolor@do{{#1}}%
}
\newcommand*{\@changepagecolor@do}[1]{%
  % Fill the remaining space with a colored rule
  \begingroup
    \offinterlineskip
    \hbox to 0pt{%
      \kern-\paperwidth
      \vtop to 0pt{%
        \color#1%
        \hrule width 2\paperwidth height \paperheight
        \vss
      }%
      \hss
    }%
  \endgroup
  % Set page color for the next page
  \afterpage{\pagecolor#1}%
}
\makeatother

\begin{document}
\pagecolor{green}
\lipsum[2]
\changepagecolor{yellow}
\lipsum[3]
\lipsum[4]
\end{document}

Page 1 Page 2

Related Question