How can I count CSS page breaks for printed HTML?

前端 未结 5 792
臣服心动
臣服心动 2021-02-04 12:19

I am generating reports using HTML and I am using CSS to control the page breaking using page-break-after, etc. I have given the user the option to print multiple reports at onc

5条回答
  •  日久生厌
    2021-02-04 13:01

    You can't count page breaks, but you can count column breaks, which behave very similarly.

    Wherever you have page break styles, pair them with a matching column break:

    -webkit-column-break-inside: avoid;
    -webkit-break-inside: avoid;
    

    Then set the report to use columns that match the size of a printed page:

    .page.precalc {
        width: 16800mm;
        height: 257mm;
        -webkit-column-width: 168mm;
        .content {
            width: 168mm;
        }
    }
    

    Column breaks work very similarly to page breaks, so you can determine the page number of an element simply by measuring the horizontal position.

    var left = el.getBoundingClientRect().left;
    pageNumber = Math.round(left/635) + 1
    

    CSS columns still have somewhat spotty support, so may not print correctly. However, you can remove the .precalc style as soon as you are done with layout calculations, so that the view will return to the original vertical layout. Depending on use case, a screen/print media query could also work.

    The above works for me to generate a table of contents with phantomjs. Getting it to work in an arbitrary browser controlled by the user is somewhat more complex.

提交回复
热议问题