The tourists, who resumed the day at 118-5 in reply to Sri Lanka's 300, piled up 417 in their first innings before being dismissed in the post-tea session with a lead of 117 runs in Galle.
Sri Lanka were 63-2 in their second knock at stumps, having lost first-innings centurion Kaushal Silva (five) and star batsman Kumar Sangakkara (18) in the 21 overs before close.
Azhar Ali caught Silva at third slip off Wahab Riaz and later snapped up Sangakkara at short-leg off Yasir Shah.
Pakistan's last five wickets put on 321 runs after the top five had fallen for 96 on Friday as the home team's bowlers struggled on a slow pitch at the Galle International Stadium.
Also Read
Shafiq was last man dismissed for 131, his seventh Test century and the third in the last four matches following scores of 137 against New Zealand in Sharjah and 107 against Bangladesh in Dhaka.
Sarfraz missed his fourth Test century when he ambitiously attempted to sweep a ball from seamer Dhammika Prasad that was pitched outside the off-stump and dragged the ball onto his stumps.
Tailender Zulfiqar Babar, essentially a left-arm spinner, smashed a career-best 56 off 60 balls with six boundaries and two sixes as he helped Shafiq add 101 valuable runs for the ninth wicket.
The entertaining partnership ended when Babar was caught in the deep, while Shafiq was stumped soon after to terminate the innings.