I've begun relying on building DOM trees and then using a render() function to serialize them. e.g. <https://gist.github.com/HalCanary/fd4ec75ae950196454f09051a5...> or <https://gist.github.com/HalCanary/169105aad5971268988fee80d1...>.
When producing PDF document back when I was in charge of SkPDF (used by billions!), we had to generate the PDF files that way, since the serialized format is very precise.