wkhtmltopdf is the preferred option when we talk about the generation of PDF from HTML. This command line tool is widely used by a lot of developers around the world due to its simplicity, accuracy, speed and compatibility with different platforms and programming languages (as it's a command line tool it can be invoked from any programming language). If you're new with the generation of PDFs with wkhtmltopdf and you don't know how to add a new one, you will learn how to it easily in this article.
To add a new page to your document, you can add the following CSS rule to the element where the new page should be added:
page-break-before: always;
The page-break-before
property sets whether a page break should occur before a specified element. Obviously, if there's no available element where (and usually used as a good practice) the rule should be added, you can simply create an empty div element with the style:
<div style="page-break-before: always;"></div>
Alternatively you can create a class in your document that has the specific CSS rule and you would only need to add the class to an empty div
:
<style type="text/css" media="screen,print">
.new-page{
page-break-before: always;
}
</style>
<!-- Add new page -->
<div class="new-page"></div>
<!--
Begin new page elements
...
...
-->
Example
The following HTML should generate a PDF file with 3 pages with some text that specifies the current page number. It uses the new-page
class to add the css rule to empty div elements:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<style type="text/css" media="screen,print">
.new-page {
page-break-before: always;
}
</style>
</head>
<body>
<div>
<p>Page 1</p>
<div class="new-page"></div>
<p>Page 2</p>
<div class="new-page"></div>
<p>Page 3</p>
</div>
</body>
Happy coding !