How can I politely decline a job offer from an employer in writing? What are the factors I should consider?
Keep it short, keep it to the point, keep it humble.
Say that you're not going to pursue the position because you've had an offer you can't refuse from elsewhere (do not tell them where or what, unless you want them to compete). Apologise and thank them for time and anything else they've spent giving you an opportunity to present yourself. Wish them good luck in finding the right candidate.
That's really all it takes.
I've received a few of these in my time and sent a couple too. There has never been any hard feelings.
Take any good rejection letter you received, and invert it to fit. That would do just fine, as long as it's civil and to the point.
You don't need to give justification. You can if you really want and feel the need to, but it's unlikely they will be hurt if you don't, and care if you do. Keep it short and professional.
The ideal solution to me would be to propose another person to substitute you and explain why s/he would be a better fit than you.
a clarification note:
Why do I say this is the ideal solution?
Because it's a win-win situation all three parties - you, the company and the guy you referred.
You win double - you may get the respect and appreciation of the company because you did not leave them in the lurch - you offered them a capable guy and you would also most probably win admiration from the guy for referring him.
The company wins because they are left with an option even though you have declined. And who knows, that guy might be even better than you.
The guy wins an opportunity to get a new job or at least an opportunity to get inside view of a company in his field of work.
Of course one may speculate that the company might not accept that suggestion or even deem it disrespectful. The guy might not like the company at all and regret spending time with them. But if you are really confident that the guy and company are a good match for each other, things should take a positive course naturally, unless you are wrong in your judgement. Even in the latter case, this is the ideal thing which you could undertake - and I am talking about the ideal thing you could do, no the ideal thing that could happen.
A less than perfect way would be to keep it short as pointed in the first answer. You could Briefly explain why you chose your other alternative over them, if they are smart enough to take advantage of honest feedback.
If they had been a highly preferred alternative in your final decision, you could tell them under what circumstances you would do some occasional or freelance work for them. If they had been far too low on your list just politely inform them of your decision.