LaTeX error "Can be used only in preamble": cause and fix
A command that sets up the document stands after \begin{document}. Such commands only work in the preamble, the part between \documentclass and \begin{document}.
Why it happens
\usepackage{...}stands in the body of the document.- A file loaded with
\inputin the body has its own\documentclass,\usepackageor\begin{document}line. - Another preamble command is used in the body, for example
\DeclareMathOperatorfromamsmath,\geometryfromgeometryor\includeonly. \begin{document}appears twice.
How to fix it
- Move the line above
\begin{document}. - Remove the preamble from files you load with
\input, or usesubfileswhen each file should also compile alone. - To change the margins in the middle of a document, use
\newgeometry{...}in place of\geometry{...}.
A document that produces the message
\documentclass{article}
\begin{document}
\usepackage{graphicx}
\includegraphics[width=4cm]{image}
\end{document}The corrected document
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\includegraphics[width=4cm]{image}
\end{document}Both documents were compiled with pdfLaTeX from TeX Live 2023. The first produces the message, the second compiles without an error.
Finding the line in the editor
The editor lists every error and warning of a compile run with file and line. Select an entry and the cursor jumps to that line. See Error list with jump to the line.