We show, based on systematic first-principles calculations, that the ultraviolet (UV) optical properties of the nonlinear optical crystal K2Al2B2O7 can be dramatically improved by eliminating the Fe impurity through the controlling of Fe charge state during crystal growth. Our results reveal that the Fe3+ impurity can easily replace the Al site with very low formation energy, resulting in the strong UV absorption which can be quantitatively understood from the formation of in-gap states and corresponding p-d transition. Moreover, it is demonstrated that modification of the Fe charge state greatly increases its formation energy, which prevents it from incorporation into the crystal during the growth process and results in the elimination of these absorption peaks and the improvement of UV optical properties.