GeneralCalculating max point size to fit textwidth

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
petersfreeman
Posts: 19
Joined: Wed Apr 28, 2021 9:40 am

Calculating max point size to fit textwidth

Post by petersfreeman »

I want to be able to calculate the maximum point size I can use for a phrase in a serif font so that it fits within \textwidth. For the calculation, there would be two inputs:

Phrase
\textwidth

The output would be the point size of the font. In a simple way, I'm thinking it would go something like this procedurally:

1. Measure Actual Phrase Width: Use LaTeX’s \settowidth command to measure the width of the phrase at a known font size.
2. Scale Proportionally: Once I have the width at a known size, calculate the scaling factor needed to fit within \textwidth.

I have the first part working but I don't know how to calculate the scaling factor:

Code: Select all

\documentclass{article}
\usepackage{calc} % For length calculations

\newlength{\phraselength}

\newcommand{\measurephrase}[1]{%
    \settowidth{\phraselength}{#1}% Measure the width of the phrase
    The width of the phrase ``#1'' is \the\phraselength.%
}

\begin{document}

% Example usage
\measurephrase{Sample Phrase}

\end{document}

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX Beginner's Guide LaTeX Cookbook LaTeX TikZ graphics TikZによるLaTeXグラフィックス
cpierquet
Posts: 9
Joined: Thu May 23, 2024 7:40 pm

Re: Calculating max point size to fit textwidth

Post by cpierquet »

I don't know if's the way to achieve it, but it's seems to work (I guess...), but maybe not the optimal way.

Code: Select all

\documentclass{article}
\usepackage[showframe]{geometry}
\usepackage{calc} % For length calculations
\usepackage{graphicx}
\usepackage{pgf}

\newlength{\phraselength}

\newcommand{\measurephrase}[1]{%
    \settowidth{\phraselength}{#1}% Measure the width of the phrase
    \noindent The width of the phrase ``#1'' is \the\phraselength.\par
    \pgfmathsetmacro{\calcscale}{\linewidth/\phraselength}%
    \noindent The scale is \calcscale.\par
    \noindent \scalebox{\calcscale}[\calcscale]{#1}
}

\begin{document}

% Example usage
\measurephrase{Sample Phrase}

\measurephrase{Other Sample Phrase}

\end{document}
Post Reply