The money raised from candy sales and fundraisers was supposed to be used for student affairs — not the principal’s.

But that didn’t stop a Bronx headmaster from stealing nearly $30,000 from his school’s bank account to shower his mistress with lavish gifts and pricey dinners, officials said.

Robert Hannibal, the former principal at JHS 145 in the Morrisania section, was arrested Thursday and charged with felony grand larceny.

Investigators said the longtime administrator used the school’s bank account for nearly three years​, admitting to them that he used the money​ to fund a torrid affair complete with wine, flowers, romantic dinners and cash to pay some of her bills.

Hannibal said he put $8,000 of his own money into the account, but later admitted it was only $5,000. Hannibal, 59, admitted that he used the account to hide the withdrawals — and the affair — from his wife, but he didn’t consider it stealing.

School officials and prosecutors disagreed.

Hannibal lost his job in August 2013 and ple​a​d​ed​ guilty to felony larceny charges Thursday, but will not face jail time.

He paid $21,080 in restitution and is expected to pay an additional $5,000 fine on Friday.

Department of Education spokesman Harry Hartfield said Hannibal is “barred” from future employment in city public schools.

“During his time at JHS 145, he engaged in illegal activity and violated the trust of the students, families, and city he was supposed to serve,” said Hartfield. “There is no place for this sort of behavior in our schools.”

The Office of Special Commissioner of Investigation probe began on May 1, 2013 when chancellor’s investigators noticed unusual activity on the Arturo Toscanini Junior High School general school fund account that Hannibal controlled.

Hannibal could not be reached for comment. His mistress was not identified.

He started working for the Department of Education in February 1979 and served as principal of the school since May 1993. He earned $148,224 in his last year on the job.