How Do I Add a rel="canonical" HTTP Header to Embedded PDF Files?
So the problem you're running into is all about context. Twig operates in the context of the http request for the parent page; so any headers you add via Twig will be added to the page http header, which is not what you want.

This could be done server-side, as the article you reference mentions. But it becomes a bit more involved when we're dealing with dynamic content, which presumably we are if a CMS is in the mix.

Because what you need is something that will intercept the http requests for documents you want to affect the header of, and then set it based on the dynamic page where it's coming from.

You could accomplish this via a plugin by writing a controller that sets the headers and then returns the actual file. Then in your Twig code, you'd link to the controller not the PDF file.

If you're using SEOmatic for Craft CMS 3, you can use the built in seomatic.helper.seoFileLink() function to do all of this for you.