Victory allowed the top seeded Serb, also the 2011 winner, to end a run of three successive defeats in Grand Slam finals.
But the 27-year-old struggled to get across the finish line having surrendered a 5-2 lead in the fourth set and then a match point.
Defeat for 32-year-old Federer, who won the most recent of his 17 Grand Slam titles at the All England Club in 2012, ended his bid to become the oldest Wimbledon champion in the Open Era and of breaking the tie of seven titles he shares with Pete Sampras.