As Francois Ziegler pointed out, the result that you need is the so-called fundamental theorem of geometry (FTG), which states the following: if a transformation of $\mathbb R^d$ with $d\ge2$ is bijective and maps lines onto lines, then it is affine.
The main result in AMS Proc. 1999 implies that, more generally, if a transformation of $\mathbb R^d$ with $d\ge2$ is surjective and maps lines into lines, then it is affine. As shown in Remark 11 in that paper, the surjectivity condition cannot be dropped. As the example given in Lev Borisov's answer shows, the surjectivity condition cannot be dropped even if the transformation is assumed to be continuous.
As far as the rendition of the FTG on page 52 in the book by Berger Geometry (cited in Francois Ziegler's answer) is concerned, it is explained on page 2737 in the mentioned paper AMS Proc. 1999 that the proof in Berger's book contains gaps/errors. Also, as noted above, one only needs the surjectivity, rather than the bijectivity condition assumed in Berger's book.