Hacker News new | ask | show | jobs
by andreareina 2947 days ago
A warning from my own experience: do not use web technologies for any printing (including rendering to pdf) where positioning is critical (e.g. for filling out pre-printed forms). Fiddling with `@media print {…}` and `position: absolute` will work… until there's some minor change in the rendering engine that will throw all that careful work into disarray and leave you asking questions like, "why is this right-aligned bit of text in an 8.5-inch wide container being printed down the middle of my page?" (the preview looked great btw). Oh, and the vertical scale was only slightly short, so I couldn't just scale the page. The right answer in this case was a package that actually spoke pdf and would flow text into a fixed-size box at a fixed location. Oh, and once you've got the file, don't let the browser print it either -- somehow both Firefox and Chrome wouldn't render it to the printer correctly, and of course they would mess up in different ways.

Browsers are good at laying things out on the screen. On paper, not so much.

2 comments

Could you go into more detail about why printing a web page doesn't do what you want? You mean for example different versions of Chrome would screw up your previously working layout? How about between the same browser on different operating systems?

I've looked into JS libraries that will directly generate PDFs you can print but each library seems to come with a lot of caveats.

Yes, different versions would produce different layouts. Element positions and bounding boxes would change, more so in the horizontal dimension than the vertical. The text itself would be rendered at the proper size though. FWIW Chrome was better-behaved in this regard than Firefox, but even a 10% shift is too much when you need to get text into a specific box that's already been printed.

I didn't bother to check whether the same browser version on different operating systems would produce the same results.

What makes this so hard? Why can’t browsers just treat the page size as a viewport? Is the problem dealing with page breaks?
It's simply not part of the problem that browsers exist to solve, so probably not worth spending the engineer-hours to get exactly right. Printing in general is, but they just need to get things onto the page in some approximation of what the page looks like; millimeter-perfect accuracy isn't needed.