How to get pdf page numbers created by html using wkhtmltopdf

Here is our answer:

We are currently using wkhtmltopdf to create a PDF file from this html template.

Some background information:

We use Sulu CMF to create our back end, which is based on Symfony2 . The KnpSnappy Bundle is used as the symfony wrapper for wkhtmltopdf.

How we create PDF files:

Since many PDF files have the same header and footer, we created BasePDFBundle, which offers PDFManager for creating PDFs on the fly using this TWIG template. By default, a common header and footer (usually with a customer name and logo) are included.

Footer / page numbers in the footer (or header):

It is very useful to add page numbers to PDF files, for example. for orders, however, most of our content is added dynamically (for example, a list of products). Since the style of the PDF can change, and the content itself is dynamically added, there should be a quick and easy way to add the current and general page to the generated PDF file. Here's what we did:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <base href="{{ app.request.schemeAndHttpHost }}" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="stylesheet" href="{{ asset('bundles/pdfbase/css/pdfstyles.css') }}"/> </head> <body class="footer"> <div class="footer-container"> <div class="footer-widget"> <b>FooBar Company Name</b> </div> <div class="text-align-right"> <span class="page"></span>/<span class="topage"></span> </div> </div> <script type="text/javascript"> (function() { // get all url parameters and transform it to a list // pdf generator adds a param for current and the total page sum // add the value to the html elements var urlParams = document.location.search.substring(1).split('&'); var urlParamsList = {}; var pagingElements = ['topage', 'page']; for (var i in urlParams) { var param = urlParams[i].split('=', 2); urlParamsList[param[0]] = unescape(param[1]); } for (var i in pagingElements) { var elem = document.getElementsByClassName(pagingElements[i]); for (var j = 0; j < elem.length; ++j) { elem[j].textContent = urlParamsList[pagingElements[i]]; } } })(); </script> </body> 

Yes, the page and topage variable names may be better, but they are the same as the KnpSnappy shell used when merging branch templates with the final PDF template. This is the easiest way to get the current and total page number, because you can let the shell do all the calculations.

In the end, you just need to replace the text of the html tags and here it is!

Differences between local machine and server:

Since wkhtmltopdf opens a virtual browser for "rendering" twig templates, this can lead to errors in your pdf generation on your server. We found that using event tags such as <body onload="doSomething()"> is not recommended, most likely you should run your javascript code, as we did in the above example.

+6
source share
1 answer

If you use KnpSnappy as a wkhtmltopdf wrapper, you can configure various options for your pdf.

see the "Footers and Headers:" section of the wkhtmltopdf documentation, here http://wkhtmltopdf.org/usage/wkhtmltopdf.txt

[page] Replaced by the number of pages that are currently being printed.

[topage] Replaced by the last page number to print

Below is a sample Symfony2 controller, check the footer-html checkbox in the $ pdfOptions array, where I used both placeholders to print the page number in the footer of each page of the pdf file.

 <?php namespace Rm\PdfBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; /** * Pdf controller */ class PdfController extends Controller { /** * Serve pdf * * @Route("/article/{slug}", name="rm_pdf_view") * @Method({"GET"}) */ public function viewAction(Request $request, $slug) { // build html $html = $this->renderView('RmPdfBundle:Pdf:view.html.twig', array( 'data' => $yourDataToTemplate, )); // prepare pdf options $pdfOptions = array( 'footer-html' => '<p>Page : [page] of [pageTo]</p>', 'footer-font-size' => '10', 'page-size' => 'A4', 'orientation' => 'Portrait', 'margin-top' => 10, 'margin-bottom' => 20, 'margin-left' => 15, 'margin-right' => 15, ); // file name of pdf $pdfFileName = "nameOfYourPdfFile.pdf"; // server pdf file to user using knp_snappy.pdf service return new Response( $this->get('knp_snappy.pdf')->getOutputFromHtml($html, $pdfOptions), 200, array( 'Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="'.$pdfFileName.'"', ) ); } } 
0
source

Source: https://habr.com/ru/post/989511/


All Articles