Lee's invasion of Pennsylvania was done for a number of reasons.
First, he thought that he would be able to get food and other supplies from the rich land of the area he was invading.
Perhaps more important were two other reasons, having to do with politics more than battles. One of these was that Lee hoped that a successful invasion would increase anti-war sentiment in the North and lead to a peace treaty. Second, the Confederates hoped that perhaps an important foreign country like England or France would recognize the CSA.
Meade's army tracked Lee to be sure that he did not turn his army to attack Washington, D.C.
Confederate General Robert E. Lee's Army of Northern Virginia was at its absolute apex after having just crushed the Union army at the battle of Chancellorsville. Though drastically outnumbered, Lee had taken the bold step of dividing his army in the face of the enemy, sending his trusted Gen. T. J. "Stonewall" Jackson around the enemy position to strike with a devastating flank attack that nearly routed the entire Union force. Sadly for the Confederates, the attack took place too late in the afternoon for the Southerners to completely destroy Gen. Joe Hooker's Army of the Potomac, and then, later that night, Jackson was mortally wounded.
Deprived of his "right arm," Lee was forced to reorganize the Army of Northern Virginia before moving north. Naturally, it would have been beneficial for new corps commanders Gen. Dick Ewell and Gen. A. P. Hill to have had some previous experience at their new posts, but Lee decided to invade Maryland and Pennsylvania anyway. His army was absolutely the most lethal fighting force in the world at this particular time; Lee had the utmost confidence in his men and he (and most of the soldiers themselves) thought they were invincible.
His plans for invasion would benefit the Confederacy in several ways. It would eliminate planned Union advances in the South; relieve the pressure against Vicksburg in the Western theatre; and give the nation a new field of harvest from which to feed itself during the long marches on Union soil. Lee still hoped to enlist more volunteers from Maryland, a border state with a large population of Southern sympathizers. Additionally, a major Confederate victory was needed to insure official recognition and aid from England and France. Lee originally planned to march northward to Baltimore and possibly even Philadelphia, before heading south and capturing Washington. It was truly an audacious plan, but one which Lee thought his men capable.
Meade, the new Union commander, had more troops available to him and needed to remain close to Lee's army in order to prevent the Confederates from ransacking their way through Maryland and Pennsylvania and gathering the momentum necessary to force the capture of Washington. He hoped to catch Lee's men off-guard--which he ultimately did when the two armies collided at Gettysburg.