You are not permitted to download, save or email this image. Visit image gallery to purchase the image.
Police identified the shooter as Euler Fernando Gandolfo (49) a systems analyst with no criminal record.
Gandolfo entered the cathedral and sat down among mainly elderly worshippers who remained to pray after midday mass.
"I suddenly saw a man stand up, take position in front of a couple and shoot them point blank. I ran out fast and he continued firing, many shots," said Pedro Rodrigues, a 66-year-old retiree.
"It was frightful," said another witness, Alexandre Moraes, on GloboNews channel. "He shot randomly at people. They were all praying."
Campinas police chief Jose Henrique Ventura said security cameras showed Gandolfo walk into the cathedral and sit down. A little later he started shooting at people.
Police in the plaza outside rushed in when they heard the shots, Ventura told a news conference.
The gunman ran to the altar while firing at police and was hit in the side. He fell to ground and shot himself, Ventura said. Gandolfo had two guns with 28 rounds left when he died.
Four people were shot dead and four others were wounded, but Ventura said they were out of danger in a hospital in Campinas, an industrial city 100km northwest of Sao Paulo.
Police have not established a motive.
Brazil had nearly 64,000 murders last year - more than any other country, according to the United Nations.
However, random mass shootings are relatively rare, with few American-style shootings in schools or other public areas.
The rise in armed violence helped far-right politician Jair Bolsonaro win October's presidential election, vowing to crack down on corruption, drug gangs and crime in the streets of Brazilian cities.
Bolsonaro, who takes office on January 1, plans to ease gun laws to allow Brazilians to arm themselves against criminals, a policy his critics say will only increase the murder rate.