Sri Lanka had hoped for quick wickets in the morning when Pakistan resumed on 118 for five but a sixth-wicket stand of 139 between Sarfraz and Asad Shafiq (131) put paid to their chances.
Another 101-run stand for the ninth wicket between Shafiq and Zulfiqar Babar (56) gave the visitors the upper hand in the match. Pakistan were finally all out for 417 with a first-innings lead of 117.
Pakistan then piled on the pressure and picked up two wickets in the remainder of the day's play as Sri Lanka reached stumps on 63-2 in their second innings, still trailing by 54 runs.
Kaushal Silva (five), a centurion in the first innings, and the experienced Kumar Sangakkara (18) were the batsmen out.
Opener Dimuth Karunaratne (36) and nightwatchman Dilruwan Perera (nought) were at the crease for the hosts.
Earlier, wicketkeeper-batsman Sarfraz caused disarray in Sri Lanka's disciplined attack with his innovative batting and hit 13 fours in his 86-ball knock.
His downfall came when he tried an unorthodox sweep against fast bowler Dhammika Prasad, with the ball catching the inside edge and going on to hit the stumps.
The dismissal gave Prasad his third wicket of the innings.
Shafiq was calm and composed during the partnership and hit five fours in his 253-ball stay.
He brought up his hundred with a boundary as the right-hander danced down the track to loft off-spinner Perera straight back over his head.
Shafiq continued to frustrate Sri Lanka's bowlers with useful partnerships with the tail.
He added 38 with Wahab Riaz (14) for the seventh wicket and another 29 for the eighth with Yasir Shah (23) that took Pakistan past 300.
The ninth-wicket partnership with Babar, who also posted his highest Test score and first 50, took Pakistan's lead into three figures.
Shafiq became the final Pakistan wicket to fall when he was stumped by wicketkeeper Dinesh Chandimal.
Perera was the most successful Sri Lankan bowler with four wickets while Prasad picked up three.
Scorecard
Sri Lanka 1st innings: 300
Pakistan 1st innings (overnight 118-5):
Mohammad Hafeez c Karunaratne b Prasad 2
Ahmed Shehzad lbw b Prasad 9
Azhar Ali lbw b Herath 8
Younis Khan b Perera 47
Misbah-ul Haq c Sangakkara b Pradeep 20
Asad Shafiq st Chandimal b Perera 131
Sarfraz Ahmed b Prasad 96
Wahab Riaz b Perera 14
Yasir Shah c Chandimal b Pradeep 23
Zulfiqar Babar c Vithanage b Perera 56
Junaid Khan not out 6
Extras: (lb1, nb3, w1) 5
Total (all out, 113.1 overs) 417
Fall of wickets: 1-2, 2-11, 3-35, 4-86, 5-96, 6-235, 7-273, 8-302, 9-403.
Bowling: Prasad 24-4-91-3, Pradeep 19-1-71-2, Herath 30-4-99-1, Perera 31.1-3-122-4, Mathews 6-1-12-0, Vithanage 3-0-21-0.
Sri Lanka 2nd innings:
K. Silva c Azhar b Wahab 5
D. Karunaratne not out 36
K. Sangakkara c Azhar b Yasir 18
D. Perera not out 0
Extras: (b4) 4
Total (for two wickets, 21 overs) 63
Fall of wickets: 1-18, 2-63.
Bowling: Wahab 6-3-11-1, Junaid 4-0-19-0, Yasir 7-1-21-1, Hafeez 4-1-8-0.
Image: Asad Shafiq
Photograph: Francois Nel/Getty Images