如何使用wkhtmltopdf在页眉/页脚htmls页面编号?

问题描述:

我正在开发一个电子发票系统,我们的一个特点是生成发票的PDF并邮寄。我们有多个发票模板,并且会在以后创建,所以我们决定使用HTML模板,生成HTML文档,然后将其转换为PDF。但是我们遇到了wkhtmltopdf的一个问题,就我所知(我已经在Google上找到解决方案的日子),我们不能简单地使用HTML作为页眉/页脚,并在其中显示页码。

I'm developing an electronic invoicing system, and one of our features is generating PDFs of the invoices, and mailing them. We have multiple templates for invoices, and will create more later, so we decided to use HTML templates, generate HTML document, and then convert it to PDF. But we're facing a problem with wkhtmltopdf, that as far as I know (I've been Googleing for days to find the solution) we cannot simply both use HTML as header/footer, and show page numbers in them.

在错误报告(或类似报告)中( http ://code.google.com/p/wkhtmltopdf/issues/detail?id = 140 )我读到使用JavaScript它是可以实现的这个组合。但是没有关于如何做的其他信息可以在这个页面或其他地方找到。

In a bug report (or such) ( http://code.google.com/p/wkhtmltopdf/issues/detail?id=140 ) I read that with JavaScript it is achievable this combo. But no other information on how to do it can be found on this page, or elsewhere.

当然,强制使用JavaScript是不重要的,如果使用wkhtmltopdf一些CSS魔法可以工作,它将像其他任何解决方案一样真棒。

It is, of course not so important to force using JavaScript, if with wkhtmltopdf some CSS magic could work, it would be just as awesome, as any other hackish solutions.

谢谢!

要显示页码和总页数,您可以在页脚或标题代码中使用此JavaScript代码段:

To show the page number and total pages you can use this javascript snippet in your footer or header code:

  var pdfInfo = {};
  var x = document.location.search.substring(1).split('&');
  for (var i in x) { var z = x[i].split('=',2); pdfInfo[z[0]] = unescape(z[1]); }
  function getPdfInfo() {
    var page = pdfInfo.page || 1;
    var pageCount = pdfInfo.topage || 1;
    document.getElementById('pdfkit_page_current').textContent = page;
    document.getElementById('pdfkit_page_count').textContent = pageCount;
  }

并使用page onload调用getPdfInfo

And call getPdfInfo with page onload

当然,pdfkit_page_current和pdfkit_page_count是显示数字的两个元素。

Of course pdfkit_page_current and pdfkit_page_count will be the two elements that show the numbers.

摘录自这里