Nice out of the box thinking. You might want to try the external file option and put the string you build dynamicly inside this document. My assumption is that this external file can not be a Mendix filedocument. Allthough it might be possible to create a deeplink URL. Then use the deeplink to retrieve the just created file and return that one. Otherwise you need to find a location outside of Mendix where you can place this document and need to device a way to get the document there.
The best road would be to create a widget for what you want to do. But that depends on your developer skills.
The Format String widget is the go-to for HTML rendering with data.
Not sure how well it would work with rendering data for a D3 chart though. Seems like that would need more deeply nested data than just one deep references.
I would definitely consider one of the dedicated D3 widgets suggested above or possibly the ChartsJS widget.
Did you manage to resolve this in the end? We are looking to achieve a similar outcome with the Forced Layout Graph.
Looks like Amresh's team made a custom widget. This add on just released to the app store: https://appstore.home.mendix.com/link/app/70561/Tammina-Solutions/Tech-Tammina-D3-Charts