How to dynamically adjust font size for variable content to fit a page?

I am in a situation, where some content is dynamic in nature. Sometimes it fits exactly one page, but sometimes there are more texts and it takes more than one page.

If it fits exactly one page, or even part of a page, we can continue with the current font size. But in the second case we would like to dynamically reduce the font size from the current one to make the content fit exactly one page.

I have some rough idea to do this, but can not seem to execute my idea.

This is what I have brainstormed so far.

\documentclass[12pt]{article}

\usepackage{lipsum}

\usepackage{relsize}

\makeatletter
\long\def\fittopage#1{%
% Find number of pages required including fractional pages
\def\n@pages{\p@gesneed{#1}}

% Get downsizing needed if any
\def\df@ctor{\downsizingf@ctor{\n@pages}}

\def\df@ctor{1}                 % Value forced for testing purpose
% Render the page
{\smaller[\df@ctor]#1}}

% Actual computation engines
\long\def\p@gesneed#1{\relax}

\def\downsizingf@ctor{\relax}

\makeatother

\begin{document}

\fittopage{\lipsum[1]}

\clearpage

\fittopage{\lipsum[1-10]}

\end{document}


Scaling down a boxed content is not an option since that would also reduce the width. That is not permitted under the present scenario.

You can box the content and measure the box height...

Note this uses fix-cm to get scalable cm sizes, other font families normally allow arbitrary scaling by default.

\RequirePackage{fix-cm}
\documentclass[12pt]{article}

\usepackage{lipsum}

\usepackage{relsize}

\makeatletter
\long\def\fittopage#1{{%
\sbox0{\begin{minipage}[b]{\textwidth}#1\end{minipage}}%
\ifdim\ht0>\textheight
\relscale{0.9}%
\typeout{trying: \f@size}%
\fittopage{#1}%
\else
\noindent\usebox0
\fi
}}

\makeatother

\begin{document}

\fittopage{\lipsum[1]}

\clearpage

\fittopage{\lipsum[1-10]}

\end{document}

• I could adapt your solution to my scenario with some tweaks. The recursive call was causing some problems with database loadings, which had to be handled separately. Anyway, there is no reason not to accept your solution. And thanks a lot. – Masroor May 14 at 17:37