Window get Selection and ranges

This is the problem i am trying to solve:

1) User uploads a file. (TXT, DOC, DOCX) 2) I parse it and spit out the HTML for the user on a window pane, user selects parts of the text, and clicks on export and i use window.getSelection to create a new pane with that selected text, and ability to comment on that text. 3) User comments. 4) This way i have a collection of Comment boxes, with text and respective comments. 5) Now i want to create a PDF file that has the whole file HTML that i had parsed initially, and i want to plug in the comments on the relevant sections that the user selected and created comment boxes for, as explained in point 3 and 4.

Question:

How do i mash together the selections with comments and the original text to create that PDF. I think i need to do something with ranges, but i don't quite understand how, what is the data structure i might need?

I am using Node.js

Thanks!

EDIT

Will make it more precise, how do i add a HTML wrapper over the selection, so that i can uniquely identify it, it might get easier from there.