You could even get on the train and by the ticket onboard just find the conductor and tell him you need a ticket but there will be a $5 surcharge for that service so I would recommend buy it right before you get onboard DUS Heidelberg is not that busy this time of the year. if you need more advice feel free to email me.
------------------
Viele Grüße
Oliver