where to add page-break related css in wkhtmltopdf

2019-04-29 07:14发布

问题:

I am using wkhtmltopdf 0.12.3.2 on Windows.

I know there are a lot of questions and answers around this topic, but I still can't find an answer to my problem; I don't know where to put the according CSS - or the CSS doesn't work for some (other) reason:

for example i tried to put the page-break related CSS directly into my html file which i want to render. i tried to force page-breaks with <span class="break_here"></span> in my <body>:

<!-- ... -->
<head>
    <style>
        span.break_here {
            page-break-after: always !important;
        }
    </style>
</head>
<!-- ... -->

this didn't do anything.

then i also tried to put it into @media print{} or @media screen{} which did not change anything either:

<style>
    @media screen{
        span.break_here {
            page-break-after: always !important;
        }
    }
</style>

thanks for any help!

edit: there is even another possibility by adding the --user-style-sheet option for using an external stylesheet.

回答1:

Adding pagebreaks via a standalone element in wkhtmltopdf has caused me problems as well.

I've found that applying the pagebreaks to an element which wraps the contents to be much more reliable.

This doesn't work so well:

<div>some content</div>
<div class="pagebreak"></div>

Whereas this does the trick:

<div class="pagebreak">some content</div>

To make this work, I did not use .pagebreak{page-break-after: always!important;}

But, instead used: .pagebreak{page-break-inside: avoid!important;}

It's also good to note that pagebreaks on print should be as high-up in the dom-tree as possible. Applying pagebreak rules to elements that are deeply nested can cause headaches (or at least has for me in the past)

Hope this helps!