Here is an elementary derivation. By the Taylor's theorem, if $|\epsilon| \leq x$ then
$$
\frac{1}{\cosh(nx+\epsilon)}
= \frac{1}{\cosh(nx)} - \frac{\sinh(nx)}{\cosh^2(nx)} \epsilon + \mathcal{O}\left(\frac{x^2}{\cosh(nx)}\right).
$$
Here, the implicit bound of the error term is independent of both $x$ and $n$, owing to the exponential decay of the second derivative of $\operatorname{sech}$. Then rearranging and averaging both sides w.r.t. $\epsilon$ over the interval $[0,x]$, we obtain
$$ \frac{1}{\cosh(nx)}
= \frac{1}{x} \int_{nx}^{(n+1)x} \frac{du}{\cosh u}
+ \frac{\sinh(nx)}{\cosh^2(nx)} \cdot \frac{x}{2}
+ \mathcal{O}\left(\frac{x^2}{\cosh(nx)}\right). $$
Applying similar trick to the second term in the RHS, we also obtain
$$ \frac{1}{\cosh(nx)}
= \frac{1}{x} \int_{nx}^{(n+1)x} \frac{du}{\cosh u}
+ \frac{1}{2}\int_{nx}^{(n+1)x} \frac{\sinh u}{\cosh^2 u} \, du + \mathcal{O}\left(\frac{x^2}{\cosh(nx)}\right). $$
Summing over $n = 0, 1, \cdots$, we have
\begin{align*}
f(x)
&= \frac{1}{x}\int_{0}^{\infty} \frac{du}{\cosh u}
+ \frac{1}{2}\int_{0}^{\infty} \frac{\sinh u}{\cosh^2 u} \, du
+ \mathcal{O}\left(\sum_{n=0}^{\infty} \frac{x^2}{\cosh(nx)}\right) \\
&= \frac{\pi}{2x} + \frac{1}{2} + \mathcal{O}\left(\sum_{n=0}^{\infty} \frac{x^2}{\cosh(nx)}\right).
\end{align*}
But it is easy to prove that $\sum_{n=0}^{\infty} \frac{x}{\cosh(nx)} \leq x + \int_{0}^{\infty} \frac{du}{\cosh u}$, so the above error term is $\mathcal{O}(x)$. Therefore we obtain
$$ f(x) = \frac{\pi}{2x} + \frac{1}{2} + \mathcal{O}(x). $$