First iterate over the fields you are using for X and determine which ones have a value that's not an empty string. Get the page number for that field using the Field.page property. Then use those numbers to set the PrintParams.printRange property.
I just checked, the form fields are called Page1, Page2, Page3, etc...
So... I'm not understanding something.
Is the value of the field "Page1" always "1" and the value of the field "Page2" always "2"? If that's the case, the value of the fields that represent X are irrelevant, you just need the value of Y.
Or is it possible that the 3rd page in the 20 page PDF is labeled Page 1 of 5 for example? If this is the case, you'll and the range is always continuous, then you have a bit more work to do but it's a relatively simple use of Math.max and Math.min methods to get the range.
We can't really give you copy/paste scripts without having the form in question to play with... at least, not for this sort of thing.
Here is a link to the form if you would like to visualize this, it'll be much easier. Basically, yes, the pages will be sequential, however the form is made so that in case someone needs in excess of 20 pages, they can open another copy of the same form and go from there.
Also, I was just thinking that basing the script off of a field that could be blank vs filled would be the easiest way to do this. So "Page1" will almost always be "1" and "Page2" will almost always be "2" and "Page10" will be "10", but Page11, Page12, etc will be empty and, ergo, should not print.
Does that make sense? lol
Also, thank you for that link! I'm checking it out right now.
Ok - Stop what you're doing. Back away slowly and don't make any sudden movements.
There are far better ways to approach what you're trying to do.
You don't need a 20 page file. You need a two page file and a template page that can be spawned as number of times as needed. If you use page templates, you'll always have a document that's exactly as long as you need it to be and no longer. Read the article at the link below. It's old but the concepts are still valid, the code probably even still works.
OH MY GOD YOU ARE AMAZING!!!! Yes this will be MUCH easier to do!! Fantastic! Thank you so much!!!!
Joel, I have a followup question about the Spawn and page templates but it doens't fit this topic. Link is below in case you had any knowledge of this one too. Thank you again!