How to get correct rendering size when printing html elements

前端 未结 3 989
忘了有多久
忘了有多久 2021-02-08 10:41

I have trouble understanding how to render html elements with correct size when printing them to A4 size paper.

To illustrate my purpose, I simplified my code to a html

相关标签:
3条回答
  • 2021-02-08 11:03

    Cover page should be filled with some image up the very edges of A4 paper.

    You're never going to satisfy this requirement. Trust me, I've been doing dashboards and reports on the web for a long time and you simply don't get fine-grained control over rendering like this. The web isn't designed for it.

    You can still generate some great reports if you're willing to work within a margin and not try for pixel-perfect layouts. Web reports can look super sharp and you can cover multiple media with one code base.

    But for situations where pixel-perfect rendering matters, in addition to control over page breaks and such, only a PDF library will suffice. There are some good ones out there--I've had success with PDFSharp.

    Why don't you display a cover image that doesn't span the entire page?

    0 讨论(0)
  • 2021-02-08 11:10

    You could use phantomjs to render your pdf (you ask for pdf eventually). In php I have successfully used https://github.com/kriansa/h2p to generate pdf's. (also with rendering javascript based charts with d3.js). It is not easy but with headless browsing you can make it work.

    0 讨论(0)
  • 2021-02-08 11:15

    You are tackling a difficult problem which is a bane of many programmers' existence. Printing from HTML and ensuring compatibility with different browsers is basically a unicorn. You shouldn't manage that concern yourself. The quirks of CSS styling and the fragmentation of the browser ecosystem will make sure you don't succeed.

    My advice is that you take a look at a PDF generator API like PDF Kit or iText.

    From my research, page and form printing is especially problematic on Firefox. As you've noticed from first hand experience, you can't manage margins in a sane way. I also tried with Firefox 49.0.2 without success.

    I thought about using @media print{} but Firefox was unwilling to collaborate.

    That being said, your code worked just fine for me running Chrome on the version you mentioned. Note that I set the margins to 'none'.

    0 讨论(0)
提交回复
热议问题