For representing a non-periodic function on the interval $[-L,L]$, we use
\begin{equation*}
f(x)=k_1+\frac{k_2x}{L}+\sum_{n=1}^{\infty} \left(A_n\cos\frac{n\pi x}{L}+B_n\sin\frac{n\pi x}{L}\right).
\end{equation*}
By evaluating the above series at $x=-L,L$, we get
\begin{equation*}
k_2=\frac{f(L)-f(-L)}{2}.
\end{equation*}
Let
\begin{equation*}
\tilde{f}(x)=f(x)-\frac{k_2x}{L}.
\end{equation*}
Then using the orthogonality of the sine and cosine functions, we get
\begin{align*}
k_1&=\frac{1}{2L}\int_{-L}^L \tilde{f}(\hat{x})\,d\hat{x}, \\
A_n&=\frac{1}{L}\int_{-L}^L \tilde{f}(\hat{x})\cos\frac{n\pi\hat{x}}{L}\,d\hat{x}, \\
B_n&=\frac{1}{L}\int_{-L}^L \tilde{f}(\hat{x})\sin\frac{n\pi\hat{x}}{L}\,d\hat{x}.
\end{align*}
For your function $x-x^2$, and with $L=\pi$, we get
\begin{equation*}
x-x^2=x-\frac{\pi^2}{3}+\sum_{n=1}^{\infty}\frac{4(-1)^{n+1}\cos(nx)}{n^2}.
\end{equation*}
For why the $x$ term should be present while representing non-periodic functions, see
https://www.awesomemath.org/wp-pdf-files/math-reflections/mr-2022-03/mr_3_2022_fourier.pdf.
In your function, since an `$x$' was present, it again appears on the right hand side also.
Note that the above series is valid over the entire range $[-\pi,\pi]$ (no Gibb's phenomenon!). By substituting special values of $x$, you can get interesting identities. For example, for $x=0$ and
for $x=\pi$, we get
\begin{align*}
&\sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^2}=\frac{\pi^2}{12}, \\
&\sum_{n=1}^{\infty} \frac{1}{n^2}=\frac{\pi^2}{6},
\end{align*}
the latter of which is the solution to the Basel problem!