[Tex/LaTex] how to use fancyhdr package to customize headers in landscape page

fancyhdrheader-footerlandscapepdflscape

I have used the fancyhdr package to customize the header of my pages. However, when I want a page to be landscape (by using the pdflscape package), it does produce a page in landscape orientation, but the header is on the right side of the page (see attached picture). I am using the article document class. Here is my code:

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\sectionmark}[1]{\markboth{\thesection.\ #1}{}}
\lhead{\leftmark} %section 
\rhead{\thepage} %page number


\newpage
\begin{landscape}
\subsection{asdasd}
\end{landscape}

How can I move the header to the top of the page?

this is the result which make me sad

@grimler solved the problem with rotation of the header but now the pictures cannot be in the center and the margines of the landscape page is not symmetric

\documentclass[12pt]{article}               
\usepackage[left=2cm, right=2cm, bottom=2cm, top=3cm]{geometry}
\geometry{letterpaper} 

\begin{document}

\section{Nima}
\subsection{aaaaaaaaaaaaa}
\lipsum[1]
\begin{figure}[H]
  \centering
  \includegraphics[width=0.5\linewidth]{male.jpg}
  \caption{Example of a forward looking algorithm that identifies peaks \&     troughs.}
  \label{fig:old_zig_1}
\end{figure}


\newpage


\paperwidth=\pdfpageheight
\paperheight=\pdfpagewidth
\pdfpageheight=\paperheight
\pdfpagewidth=\paperwidth
\headwidth=\textheight



\begingroup 
\vsize=\textwidth
\hsize=\textheight


\begin{figure}[H]
\begin{center}
  \includegraphics[width=0.4\linewidth]{male.jpg}
\end{center}
  \caption{Example of a forward looking algorithm that identifies peaks \& troughs.}
  \label{fig:old_zig_1}

\end{figure}

\endgroup

enter image description here

enter image description here

Best Answer

Same question as keeping-header-on-top-in-landscape-mode?

@touhami provided an excellent answer. Instead of using the landscape environment, change the geometry to landscape using:

\paperwidth=\pdfpageheight
\paperheight=\pdfpagewidth
\pdfpageheight=\paperheight
\pdfpagewidth=\paperwidth

and then set the headwidth to the textheight:

\headwidth=\textheight

Now set the textwidth & textheight locally within a group and write your landscape stuff:

\begingroup 
\vsize=\textwidth
\hsize=\textheight
%landscape stuff
\endgroup

and then change back to portrait using the same code (with the difference that the headwidth should be the textwidth).

Full MWE:

\documentclass{article}
\usepackage{fancyhdr}
\usepackage{lipsum}
\begin{document}

\pagestyle{fancy}
\fancyhf{}
\lipsum[1]
\newpage
\paperwidth=\pdfpageheight
\paperheight=\pdfpagewidth
\pdfpageheight=\paperheight
\pdfpagewidth=\paperwidth
\headwidth=\textheight
\begingroup 
\vsize=\textwidth
\hsize=\textheight
\lipsum[2]
\endgroup
\newpage
\paperwidth=\pdfpageheight
\paperheight=\pdfpagewidth
\pdfpageheight=\paperheight
\pdfpagewidth=\paperwidth
\headwidth=\textwidth

\lipsum[3]
\end{document}