[Tex/LaTex] Fit sidewaysfigure to page width including caption and source

floatsrotating

I'm trying to add a sidewaysfigure to my document, but when I set the width to \textwidth it comes out too wide.

This is my code:

\usepackage{rotating}

\begin{sidewaysfigure}
   \centering
   \begin{minipage}{\textwidth}
      \caption{The caption}
      \includegraphics[width=\textwidth]{img/diagramm_hs.png}\\
      \source{The source}
      \label{fig:diagramm_hs}
   \end{minipage}
\end{sidewaysfigure}

And here is the result:
screenshot of latex output

As you can see, the image is wider than the textwidth (textwidth is as wide as the line in the header), especially with the caption and source.

How can I make the image as large as possible on the page while everything, including caption and source, remain in the textarea?

EDIT: The image dimensions are 1327×960 px.
This is my documentclass:

\documentclass[
paper=A4,
fontsize=12pt,
BCOR12mm,
DIV14,
parskip=half*,
headsepline,
listof=totoc,
footinclude=false,
headinclude=true,
final
]{scrartcl}

Best Answer

First, the original \textwidth is lost using sidewaysfigure. Second, I needed to test if the total figure was too big. Finally, I needed the image height using [width=\textwidth] in order to determine what [height=] should be to compensate.

I tested \listoffigures to make sure only one caption showed up.

\documentclass{article}
\usepackage{showframe}
\usepackage[Export]{adjustbox}
\usepackage{rotating}
\usepackage{caption}
\captionsetup{justification=raggedright,
               singlelinecheck=false}

\newcommand{\source}[1]{\ttfamily #1}

\newsavebox{\tempbox}
\newlength{\tempdima}
\newlength{\tempdimb}
\newlength{\tempdimc}

\begin{document}
  \tempdima=\textwidth% inside \textwidth=\linewidth=\textheight
  \begin{sidewaysfigure}
  \textheight=\tempdima
  \settoheight{\tempdimb}{\includegraphics[width=\textwidth]{example-image-a}}% default height
  \savebox{\tempbox}{\begin{minipage}{\textwidth}
    \caption{The caption}
    \addtocounter{figure}{-1}% reset
    \rule{\textwidth}{\tempdimb}% same size but faster
    \par\source{The source}
    \end{minipage}}%
  \tempdima=\ht\tempbox\relax% can't get \dimexpr to work
  \advance\tempdima by \dp\tempbox\relax
  \tempdimc=\tempdimb
  \ifdim\textheight<\tempdima
    \advance\tempdimb by \textheight
    \advance\tempdimb by -\tempdima
  \fi
  \tempdima=\dimexpr \tempdimb*\textwidth/\tempdimc\relax% compute scaled width
  \hfil\begin{minipage}{\tempdima}
  \caption{The caption}
  \includegraphics[width=\textwidth]{example-image-a}\par
  \source{The source}
  \end{minipage}
  \end{sidewaysfigure}
\end{document}

full page with frames

Related Question